Search moodle.org's
Developer Documentation


   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  /**
  19   * External course participation api.
  20   *
  21   * This api is mostly read only, the actual enrol and unenrol
  22   * support is in each enrol plugin.
  23   *
  24   * @package    core_enrol
  25   * @category   external
  26   * @copyright  2010 Jerome Mouneyrac
  27   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  28   */
  29  
  30  defined('MOODLE_INTERNAL') || die();
  31  
  32  require_once("$CFG->libdir/externallib.php");
  33  
  34  /**
  35   * Enrol external functions
  36   *
  37   * @package    core_enrol
  38   * @category   external
  39   * @copyright  2011 Jerome Mouneyrac
  40   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  41   * @since Moodle 2.2
  42   */
  43  class core_enrol_external extends external_api {
  44  
  45      /**
  46       * Returns description of method parameters
  47       *
  48       * @return external_function_parameters
  49       * @since Moodle 2.4
  50       */
  51      public static function get_enrolled_users_with_capability_parameters() {
  52          return new external_function_parameters(
  53              array (
  54                  'coursecapabilities' => new external_multiple_structure(
  55                      new external_single_structure(
  56                          array (
  57                              'courseid' => new external_value(PARAM_INT, 'Course ID number in the Moodle course table'),
  58                              'capabilities' => new external_multiple_structure(
  59                                  new external_value(PARAM_CAPABILITY, 'Capability name, such as mod/forum:viewdiscussion')),
  60                          )
  61                      )
  62                  , 'course id and associated capability name'),
  63                   'options'  => new external_multiple_structure(
  64                      new external_single_structure(
  65                          array(
  66                              'name'  => new external_value(PARAM_ALPHANUMEXT, 'option name'),
  67                              'value' => new external_value(PARAM_RAW, 'option value')
  68                          )
  69                      ), 'Option names:
  70                              * groupid (integer) return only users in this group id. Requires \'moodle/site:accessallgroups\' .
  71                              * onlyactive (integer) only users with active enrolments. Requires \'moodle/course:enrolreview\' .
  72                              * userfields (\'string, string, ...\') return only the values of these user fields.
  73                              * limitfrom (integer) sql limit from.
  74                              * limitnumber (integer) max number of users per course and capability.', VALUE_DEFAULT, array())
  75              )
  76          );
  77      }
  78  
  79      /**
  80       * Return users that have the capabilities for each course specified. For each course and capability specified,
  81       * a list of the users that are enrolled in the course and have that capability are returned.
  82       *
  83       * @param array $coursecapabilities array of course ids and associated capability names {courseid, {capabilities}}
  84       * @return array An array of arrays describing users for each associated courseid and capability
  85       * @since  Moodle 2.4
  86       */
  87      public static function get_enrolled_users_with_capability($coursecapabilities, $options) {
  88          global $CFG, $DB;
  89          require_once($CFG->dirroot . "/user/lib.php");
  90  
  91          if (empty($coursecapabilities)) {
  92              throw new invalid_parameter_exception('Parameter can not be empty');
  93          }
  94          $params = self::validate_parameters(self::get_enrolled_users_with_capability_parameters(),
  95              array ('coursecapabilities' => $coursecapabilities,  'options'=>$options));
  96          $result = array();
  97          $userlist = array();
  98          $groupid        = 0;
  99          $onlyactive     = false;
 100          $userfields     = array();
 101          $limitfrom = 0;
 102          $limitnumber = 0;
 103          foreach ($params['options'] as $option) {
 104              switch ($option['name']) {
 105                  case 'groupid':
 106                      $groupid = (int)$option['value'];
 107                      break;
 108                  case 'onlyactive':
 109                      $onlyactive = !empty($option['value']);
 110                      break;
 111                  case 'userfields':
 112                      $thefields = explode(',', $option['value']);
 113                      foreach ($thefields as $f) {
 114                          $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
 115                      }
 116                      break;
 117                  case 'limitfrom' :
 118                      $limitfrom = clean_param($option['value'], PARAM_INT);
 119                      break;
 120                  case 'limitnumber' :
 121                      $limitnumber = clean_param($option['value'], PARAM_INT);
 122                      break;
 123              }
 124          }
 125  
 126          foreach ($params['coursecapabilities'] as $coursecapability) {
 127              $courseid = $coursecapability['courseid'];
 128              $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
 129              $coursecontext = context_course::instance($courseid);
 130              if (!$coursecontext) {
 131                  throw new moodle_exception('cannotfindcourse', 'error', '', null,
 132                          'The course id ' . $courseid . ' doesn\'t exist.');
 133              }
 134              if ($courseid == SITEID) {
 135                  $context = context_system::instance();
 136              } else {
 137                  $context = $coursecontext;
 138              }
 139              try {
 140                  self::validate_context($context);
 141              } catch (Exception $e) {
 142                  $exceptionparam = new stdClass();
 143                  $exceptionparam->message = $e->getMessage();
 144                  $exceptionparam->courseid = $params['courseid'];
 145                  throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
 146              }
 147  
 148              if ($courseid == SITEID) {
 149                  require_capability('moodle/site:viewparticipants', $context);
 150              } else {
 151                  require_capability('moodle/course:viewparticipants', $context);
 152              }
 153              // The accessallgroups capability is needed to use this option.
 154              if (!empty($groupid) && groups_is_member($groupid)) {
 155                  require_capability('moodle/site:accessallgroups', $coursecontext);
 156              }
 157              // The course:enrolereview capability is needed to use this option.
 158              if ($onlyactive) {
 159                  require_capability('moodle/course:enrolreview', $coursecontext);
 160              }
 161  
 162              // To see the permissions of others role:review capability is required.
 163              require_capability('moodle/role:review', $coursecontext);
 164              foreach ($coursecapability['capabilities'] as $capability) {
 165                  $courseusers['courseid'] = $courseid;
 166                  $courseusers['capability'] = $capability;
 167  
 168                  list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $capability, $groupid, $onlyactive);
 169  
 170                  $sql = "SELECT u.* FROM {user} u WHERE u.id IN ($enrolledsql) ORDER BY u.id ASC";
 171  
 172                  $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
 173                  $users = array();
 174                  foreach ($enrolledusers as $courseuser) {
 175                      if ($userdetails = user_get_user_details($courseuser, $course, $userfields)) {
 176                          $users[] = $userdetails;
 177                      }
 178                  }
 179                  $enrolledusers->close();
 180                  $courseusers['users'] = $users;
 181                  $result[] = $courseusers;
 182              }
 183          }
 184          return $result;
 185      }
 186  
 187      /**
 188       * Returns description of method result value
 189       *
 190       * @return external_multiple_structure
 191       * @since Moodle 2.4
 192       */
 193      public static function get_enrolled_users_with_capability_returns() {
 194          return  new external_multiple_structure( new external_single_structure (
 195                  array (
 196                      'courseid' => new external_value(PARAM_INT, 'Course ID number in the Moodle course table'),
 197                      'capability' => new external_value(PARAM_CAPABILITY, 'Capability name'),
 198                      'users' => new external_multiple_structure(
 199                          new external_single_structure(
 200                  array(
 201                      'id'    => new external_value(PARAM_INT, 'ID of the user'),
 202                      'username'    => new external_value(PARAM_RAW, 'Username', VALUE_OPTIONAL),
 203                      'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
 204                      'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
 205                      'fullname'    => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
 206                      'email'       => new external_value(PARAM_TEXT, 'Email address', VALUE_OPTIONAL),
 207                      'address'     => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
 208                      'phone1'      => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
 209                      'phone2'      => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
 210                      'icq'         => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
 211                      'skype'       => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
 212                      'yahoo'       => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
 213                      'aim'         => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
 214                      'msn'         => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
 215                      'department'  => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
 216                      'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
 217                      'interests'   => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
 218                      'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
 219                      'lastaccess'  => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
 220                      'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
 221                      'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
 222                      'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
 223                      'url'         => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
 224                      'country'     => new external_value(PARAM_ALPHA, 'Country code of the user, such as AU or CZ', VALUE_OPTIONAL),
 225                      'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small', VALUE_OPTIONAL),
 226                      'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big', VALUE_OPTIONAL),
 227                      'customfields' => new external_multiple_structure(
 228                          new external_single_structure(
 229                              array(
 230                                  'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field'),
 231                                  'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
 232                                  'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
 233                                  'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field'),
 234                              )
 235                          ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
 236                      'groups' => new external_multiple_structure(
 237                          new external_single_structure(
 238                              array(
 239                                  'id'  => new external_value(PARAM_INT, 'group id'),
 240                                  'name' => new external_value(PARAM_RAW, 'group name'),
 241                                  'description' => new external_value(PARAM_RAW, 'group description'),
 242                              )
 243                          ), 'user groups', VALUE_OPTIONAL),
 244                      'roles' => new external_multiple_structure(
 245                          new external_single_structure(
 246                              array(
 247                                  'roleid'       => new external_value(PARAM_INT, 'role id'),
 248                                  'name'         => new external_value(PARAM_RAW, 'role name'),
 249                                  'shortname'    => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
 250                                  'sortorder'    => new external_value(PARAM_INT, 'role sortorder')
 251                              )
 252                          ), 'user roles', VALUE_OPTIONAL),
 253                      'preferences' => new external_multiple_structure(
 254                          new external_single_structure(
 255                              array(
 256                                  'name'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
 257                                  'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
 258                              )
 259                      ), 'User preferences', VALUE_OPTIONAL),
 260                      'enrolledcourses' => new external_multiple_structure(
 261                          new external_single_structure(
 262                              array(
 263                                  'id'  => new external_value(PARAM_INT, 'Id of the course'),
 264                                  'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
 265                                  'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
 266                              )
 267                      ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
 268                  )
 269                          ), 'List of users that are enrolled in the course and have the specified capability'),
 270                      )
 271                  )
 272              );
 273      }
 274  
 275      /**
 276       * Returns description of method parameters
 277       *
 278       * @return external_function_parameters
 279       */
 280      public static function get_users_courses_parameters() {
 281          return new external_function_parameters(
 282              array(
 283                  'userid' => new external_value(PARAM_INT, 'user id'),
 284              )
 285          );
 286      }
 287  
 288      /**
 289       * Get list of courses user is enrolled in (only active enrolments are returned).
 290       * Please note the current user must be able to access the course, otherwise the course is not included.
 291       *
 292       * @param int $userid
 293       * @return array of courses
 294       */
 295      public static function get_users_courses($userid) {
 296          global $USER, $DB;
 297  
 298          // Do basic automatic PARAM checks on incoming data, using params description
 299          // If any problems are found then exceptions are thrown with helpful error messages
 300          $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid'=>$userid));
 301  
 302          $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible');
 303          $result = array();
 304  
 305          foreach ($courses as $course) {
 306              $context = context_course::instance($course->id, IGNORE_MISSING);
 307              try {
 308                  self::validate_context($context);
 309              } catch (Exception $e) {
 310                  // current user can not access this course, sorry we can not disclose who is enrolled in this course!
 311                  continue;
 312              }
 313  
 314              if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) {
 315                  // we need capability to view participants
 316                  continue;
 317              }
 318  
 319              list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
 320              $enrolledsql = "SELECT COUNT('x') FROM ($enrolledsqlselect) enrolleduserids";
 321              $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams);
 322  
 323              $result[] = array('id'=>$course->id, 'shortname'=>$course->shortname, 'fullname'=>$course->fullname, 'idnumber'=>$course->idnumber,'visible'=>$course->visible, 'enrolledusercount'=>$enrolledusercount);
 324          }
 325  
 326          return $result;
 327      }
 328  
 329      /**
 330       * Returns description of method result value
 331       *
 332       * @return external_description
 333       */
 334      public static function get_users_courses_returns() {
 335          return new external_multiple_structure(
 336              new external_single_structure(
 337                  array(
 338                      'id'        => new external_value(PARAM_INT, 'id of course'),
 339                      'shortname' => new external_value(PARAM_RAW, 'short name of course'),
 340                      'fullname'  => new external_value(PARAM_RAW, 'long name of course'),
 341                      'enrolledusercount' => new external_value(PARAM_INT, 'Number of enrolled users in this course'),
 342                      'idnumber'  => new external_value(PARAM_RAW, 'id number of course'),
 343                      'visible'   => new external_value(PARAM_INT, '1 means visible, 0 means hidden course'),
 344                  )
 345              )
 346          );
 347      }
 348  
 349      /**
 350       * Returns description of method parameters
 351       *
 352       * @return external_function_parameters
 353       */
 354      public static function get_enrolled_users_parameters() {
 355          return new external_function_parameters(
 356              array(
 357                  'courseid' => new external_value(PARAM_INT, 'course id'),
 358                  'options'  => new external_multiple_structure(
 359                      new external_single_structure(
 360                          array(
 361                              'name'  => new external_value(PARAM_ALPHANUMEXT, 'option name'),
 362                              'value' => new external_value(PARAM_RAW, 'option value')
 363                          )
 364                      ), 'Option names:
 365                              * withcapability (string) return only users with this capability. This option requires \'moodle/role:review\' on the course context.
 366                              * groupid (integer) return only users in this group id. If the course has groups enabled and this param
 367                                                  isn\'t defined, returns all the viewable users.
 368                                                  This option requires \'moodle/site:accessallgroups\' on the course context if the
 369                                                  user doesn\'t belong to the group.
 370                              * onlyactive (integer) return only users with active enrolments and matching time restrictions. This option requires \'moodle/course:enrolreview\' on the course context.
 371                              * userfields (\'string, string, ...\') return only the values of these user fields.
 372                              * limitfrom (integer) sql limit from.
 373                              * limitnumber (integer) maximum number of returned users.', VALUE_DEFAULT, array()),
 374              )
 375          );
 376      }
 377  
 378      /**
 379       * Get course participants details
 380       *
 381       * @param int $courseid  course id
 382       * @param array $options options {
 383       *                                'name' => option name
 384       *                                'value' => option value
 385       *                               }
 386       * @return array An array of users
 387       */
 388      public static function get_enrolled_users($courseid, $options = array()) {
 389          global $CFG, $USER, $DB;
 390          require_once($CFG->dirroot . "/user/lib.php");
 391  
 392          $params = self::validate_parameters(
 393              self::get_enrolled_users_parameters(),
 394              array(
 395                  'courseid'=>$courseid,
 396                  'options'=>$options
 397              )
 398          );
 399          $withcapability = '';
 400          $groupid        = 0;
 401          $onlyactive     = false;
 402          $userfields     = array();
 403          $limitfrom = 0;
 404          $limitnumber = 0;
 405          foreach ($options as $option) {
 406              switch ($option['name']) {
 407              case 'withcapability':
 408                  $withcapability = $option['value'];
 409                  break;
 410              case 'groupid':
 411                  $groupid = (int)$option['value'];
 412                  break;
 413              case 'onlyactive':
 414                  $onlyactive = !empty($option['value']);
 415                  break;
 416              case 'userfields':
 417                  $thefields = explode(',', $option['value']);
 418                  foreach ($thefields as $f) {
 419                      $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
 420                  }
 421                  break;
 422              case 'limitfrom' :
 423                  $limitfrom = clean_param($option['value'], PARAM_INT);
 424                  break;
 425              case 'limitnumber' :
 426                  $limitnumber = clean_param($option['value'], PARAM_INT);
 427                  break;
 428              }
 429          }
 430  
 431          $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
 432          $coursecontext = context_course::instance($courseid, IGNORE_MISSING);
 433          if ($courseid == SITEID) {
 434              $context = context_system::instance();
 435          } else {
 436              $context = $coursecontext;
 437          }
 438          try {
 439              self::validate_context($context);
 440          } catch (Exception $e) {
 441              $exceptionparam = new stdClass();
 442              $exceptionparam->message = $e->getMessage();
 443              $exceptionparam->courseid = $params['courseid'];
 444              throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
 445          }
 446  
 447          if ($courseid == SITEID) {
 448              require_capability('moodle/site:viewparticipants', $context);
 449          } else {
 450              require_capability('moodle/course:viewparticipants', $context);
 451          }
 452          // to overwrite this parameter, you need role:review capability
 453          if ($withcapability) {
 454              require_capability('moodle/role:review', $coursecontext);
 455          }
 456          // need accessallgroups capability if you want to overwrite this option
 457          if (!empty($groupid) && !groups_is_member($groupid)) {
 458              require_capability('moodle/site:accessallgroups', $coursecontext);
 459          }
 460          // to overwrite this option, you need course:enrolereview permission
 461          if ($onlyactive) {
 462              require_capability('moodle/course:enrolreview', $coursecontext);
 463          }
 464  
 465          list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
 466          $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
 467          $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
 468          $enrolledparams['contextlevel'] = CONTEXT_USER;
 469  
 470          $groupjoin = '';
 471          if (empty($groupid) && groups_get_course_groupmode($course) == SEPARATEGROUPS &&
 472                  !has_capability('moodle/site:accessallgroups', $coursecontext)) {
 473              // Filter by groups the user can view.
 474              $usergroups = groups_get_user_groups($course->id);
 475              if (!empty($usergroups['0'])) {
 476                  list($groupsql, $groupparams) = $DB->get_in_or_equal($usergroups['0'], SQL_PARAMS_NAMED);
 477                  $groupjoin = "JOIN {groups_members} gm ON (u.id = gm.userid AND gm.groupid $groupsql)";
 478                  $enrolledparams = array_merge($enrolledparams, $groupparams);
 479              } else {
 480                  // User doesn't belong to any group, so he can't see any user. Return an empty array.
 481                  return array();
 482              }
 483          }
 484          $sql = "SELECT us.*
 485                    FROM {user} us
 486                    JOIN (
 487                        SELECT DISTINCT u.id $ctxselect
 488                          FROM {user} u $ctxjoin $groupjoin
 489                         WHERE u.id IN ($enrolledsql)
 490                    ) q ON q.id = us.id
 491                  ORDER BY us.id ASC";
 492          $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
 493          $users = array();
 494          foreach ($enrolledusers as $user) {
 495              context_helper::preload_from_record($user);
 496              if ($userdetails = user_get_user_details($user, $course, $userfields)) {
 497                  $users[] = $userdetails;
 498              }
 499          }
 500          $enrolledusers->close();
 501  
 502          return $users;
 503      }
 504  
 505      /**
 506       * Returns description of method result value
 507       *
 508       * @return external_description
 509       */
 510      public static function get_enrolled_users_returns() {
 511          return new external_multiple_structure(
 512              new external_single_structure(
 513                  array(
 514                      'id'    => new external_value(PARAM_INT, 'ID of the user'),
 515                      'username'    => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
 516                      'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
 517                      'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
 518                      'fullname'    => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
 519                      'email'       => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
 520                      'address'     => new external_value(PARAM_TEXT, 'Postal address', VALUE_OPTIONAL),
 521                      'phone1'      => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
 522                      'phone2'      => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
 523                      'icq'         => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
 524                      'skype'       => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
 525                      'yahoo'       => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
 526                      'aim'         => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
 527                      'msn'         => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
 528                      'department'  => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
 529                      'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
 530                      'idnumber'    => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
 531                      'interests'   => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
 532                      'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
 533                      'lastaccess'  => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
 534                      'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
 535                      'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
 536                      'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
 537                      'url'         => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
 538                      'country'     => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
 539                      'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version', VALUE_OPTIONAL),
 540                      'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version', VALUE_OPTIONAL),
 541                      'customfields' => new external_multiple_structure(
 542                          new external_single_structure(
 543                              array(
 544                                  'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
 545                                  'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
 546                                  'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
 547                                  'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
 548                              )
 549                          ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
 550                      'groups' => new external_multiple_structure(
 551                          new external_single_structure(
 552                              array(
 553                                  'id'  => new external_value(PARAM_INT, 'group id'),
 554                                  'name' => new external_value(PARAM_RAW, 'group name'),
 555                                  'description' => new external_value(PARAM_RAW, 'group description'),
 556                                  'descriptionformat' => new external_format_value('description'),
 557                              )
 558                          ), 'user groups', VALUE_OPTIONAL),
 559                      'roles' => new external_multiple_structure(
 560                          new external_single_structure(
 561                              array(
 562                                  'roleid'       => new external_value(PARAM_INT, 'role id'),
 563                                  'name'         => new external_value(PARAM_RAW, 'role name'),
 564                                  'shortname'    => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
 565                                  'sortorder'    => new external_value(PARAM_INT, 'role sortorder')
 566                              )
 567                          ), 'user roles', VALUE_OPTIONAL),
 568                      'preferences' => new external_multiple_structure(
 569                          new external_single_structure(
 570                              array(
 571                                  'name'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
 572                                  'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
 573                              )
 574                      ), 'User preferences', VALUE_OPTIONAL),
 575                      'enrolledcourses' => new external_multiple_structure(
 576                          new external_single_structure(
 577                              array(
 578                                  'id'  => new external_value(PARAM_INT, 'Id of the course'),
 579                                  'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
 580                                  'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
 581                              )
 582                      ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
 583                  )
 584              )
 585          );
 586      }
 587  
 588      /**
 589       * Returns description of get_course_enrolment_methods() parameters
 590       *
 591       * @return external_function_parameters
 592       */
 593      public static function get_course_enrolment_methods_parameters() {
 594          return new external_function_parameters(
 595              array(
 596                  'courseid' => new external_value(PARAM_INT, 'Course id')
 597              )
 598          );
 599      }
 600  
 601      /**
 602       * Get list of active course enrolment methods for current user.
 603       *
 604       * @param int $courseid
 605       * @return array of course enrolment methods
 606       * @throws moodle_exception
 607       */
 608      public static function get_course_enrolment_methods($courseid) {
 609          global $DB;
 610  
 611          $params = self::validate_parameters(self::get_course_enrolment_methods_parameters(), array('courseid' => $courseid));
 612  
 613          // Note that we can't use validate_context because the user is not enrolled in the course.
 614          require_login(null, false, null, false, true);
 615  
 616          $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
 617          $context = context_course::instance($course->id);
 618          if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) {
 619              throw new moodle_exception('coursehidden');
 620          }
 621  
 622          $result = array();
 623          $enrolinstances = enrol_get_instances($params['courseid'], true);
 624          foreach ($enrolinstances as $enrolinstance) {
 625              if ($enrolplugin = enrol_get_plugin($enrolinstance->enrol)) {
 626                  if ($instanceinfo = $enrolplugin->get_enrol_info($enrolinstance)) {
 627                      $result[] = (array) $instanceinfo;
 628                  }
 629              }
 630          }
 631          return $result;
 632      }
 633  
 634      /**
 635       * Returns description of get_course_enrolment_methods() result value
 636       *
 637       * @return external_description
 638       */
 639      public static function get_course_enrolment_methods_returns() {
 640          return new external_multiple_structure(
 641              new external_single_structure(
 642                  array(
 643                      'id' => new external_value(PARAM_INT, 'id of course enrolment instance'),
 644                      'courseid' => new external_value(PARAM_INT, 'id of course'),
 645                      'type' => new external_value(PARAM_PLUGIN, 'type of enrolment plugin'),
 646                      'name' => new external_value(PARAM_RAW, 'name of enrolment plugin'),
 647                      'status' => new external_value(PARAM_RAW, 'status of enrolment plugin'),
 648                      'wsfunction' => new external_value(PARAM_ALPHANUMEXT, 'webservice function to get more information', VALUE_OPTIONAL),
 649                  )
 650              )
 651          );
 652      }
 653  }
 654  
 655  /**
 656   * Role external functions
 657   *
 658   * @package    core_role
 659   * @category   external
 660   * @copyright  2011 Jerome Mouneyrac
 661   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 662   * @since Moodle 2.2
 663   */
 664  class core_role_external extends external_api {
 665  
 666      /**
 667       * Returns description of method parameters
 668       *
 669       * @return external_function_parameters
 670       */
 671      public static function assign_roles_parameters() {
 672          return new external_function_parameters(
 673              array(
 674                  'assignments' => new external_multiple_structure(
 675                      new external_single_structure(
 676                          array(
 677                              'roleid'    => new external_value(PARAM_INT, 'Role to assign to the user'),
 678                              'userid'    => new external_value(PARAM_INT, 'The user that is going to be assigned'),
 679                              'contextid' => new external_value(PARAM_INT, 'The context to assign the user role in', VALUE_OPTIONAL),
 680                              'contextlevel' => new external_value(PARAM_ALPHA, 'The context level to assign the user role in
 681                                      (block, course, coursecat, system, user, module)', VALUE_OPTIONAL),
 682                              'instanceid' => new external_value(PARAM_INT, 'The Instance id of item where the role needs to be assigned', VALUE_OPTIONAL),
 683                          )
 684                      )
 685                  )
 686              )
 687          );
 688      }
 689  
 690      /**
 691       * Manual role assignments to users
 692       *
 693       * @param array $assignments An array of manual role assignment
 694       */
 695      public static function assign_roles($assignments) {
 696          global $DB;
 697  
 698          // Do basic automatic PARAM checks on incoming data, using params description
 699          // If any problems are found then exceptions are thrown with helpful error messages
 700          $params = self::validate_parameters(self::assign_roles_parameters(), array('assignments'=>$assignments));
 701  
 702          $transaction = $DB->start_delegated_transaction();
 703  
 704          foreach ($params['assignments'] as $assignment) {
 705              // Ensure correct context level with a instance id or contextid is passed.
 706              $context = self::get_context_from_params($assignment);
 707  
 708              // Ensure the current user is allowed to run this function in the enrolment context.
 709              self::validate_context($context);
 710              require_capability('moodle/role:assign', $context);
 711  
 712              // throw an exception if user is not able to assign the role in this context
 713              $roles = get_assignable_roles($context, ROLENAME_SHORT);
 714  
 715              if (!array_key_exists($assignment['roleid'], $roles)) {
 716                  throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
 717              }
 718  
 719              role_assign($assignment['roleid'], $assignment['userid'], $context->id);
 720          }
 721  
 722          $transaction->allow_commit();
 723      }
 724  
 725      /**
 726       * Returns description of method result value
 727       *
 728       * @return null
 729       */
 730      public static function assign_roles_returns() {
 731          return null;
 732      }
 733  
 734  
 735      /**
 736       * Returns description of method parameters
 737       *
 738       * @return external_function_parameters
 739       */
 740      public static function unassign_roles_parameters() {
 741          return new external_function_parameters(
 742              array(
 743                  'unassignments' => new external_multiple_structure(
 744                      new external_single_structure(
 745                          array(
 746                              'roleid'    => new external_value(PARAM_INT, 'Role to assign to the user'),
 747                              'userid'    => new external_value(PARAM_INT, 'The user that is going to be assigned'),
 748                              'contextid' => new external_value(PARAM_INT, 'The context to unassign the user role from', VALUE_OPTIONAL),
 749                              'contextlevel' => new external_value(PARAM_ALPHA, 'The context level to unassign the user role in
 750  +                                    (block, course, coursecat, system, user, module)', VALUE_OPTIONAL),
 751                              'instanceid' => new external_value(PARAM_INT, 'The Instance id of item where the role needs to be unassigned', VALUE_OPTIONAL),
 752                          )
 753                      )
 754                  )
 755              )
 756          );
 757      }
 758  
 759       /**
 760       * Unassign roles from users
 761       *
 762       * @param array $unassignments An array of unassignment
 763       */
 764      public static function unassign_roles($unassignments) {
 765           global $DB;
 766  
 767          // Do basic automatic PARAM checks on incoming data, using params description
 768          // If any problems are found then exceptions are thrown with helpful error messages
 769          $params = self::validate_parameters(self::unassign_roles_parameters(), array('unassignments'=>$unassignments));
 770  
 771          $transaction = $DB->start_delegated_transaction();
 772  
 773          foreach ($params['unassignments'] as $unassignment) {
 774              // Ensure the current user is allowed to run this function in the unassignment context
 775              $context = self::get_context_from_params($unassignment);
 776              self::validate_context($context);
 777              require_capability('moodle/role:assign', $context);
 778  
 779              // throw an exception if user is not able to unassign the role in this context
 780              $roles = get_assignable_roles($context, ROLENAME_SHORT);
 781              if (!array_key_exists($unassignment['roleid'], $roles)) {
 782                  throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
 783              }
 784  
 785              role_unassign($unassignment['roleid'], $unassignment['userid'], $context->id);
 786          }
 787  
 788          $transaction->allow_commit();
 789      }
 790  
 791     /**
 792       * Returns description of method result value
 793       *
 794       * @return null
 795       */
 796      public static function unassign_roles_returns() {
 797          return null;
 798      }
 799  }
 800  
 801  
 802  /**
 803   * Deprecated enrol and role external functions
 804   *
 805   * @package    core_enrol
 806   * @copyright  2010 Jerome Mouneyrac
 807   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 808   * @since Moodle 2.0
 809   * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
 810   * @see core_enrol_external
 811   * @see core_role_external
 812   */
 813  class moodle_enrol_external extends external_api {
 814  
 815  
 816      /**
 817       * Returns description of method parameters
 818       *
 819       * @return external_function_parameters
 820       * @since Moodle 2.0
 821       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 822       * @see core_enrol_external::get_enrolled_users_parameters()
 823       */
 824      public static function get_enrolled_users_parameters() {
 825          return new external_function_parameters(
 826              array(
 827                  'courseid'       => new external_value(PARAM_INT, 'Course id'),
 828                  'withcapability' => new external_value(PARAM_CAPABILITY, 'User should have this capability', VALUE_DEFAULT, null),
 829                  'groupid'        => new external_value(PARAM_INT, 'Group id, null means all groups', VALUE_DEFAULT, null),
 830                  'onlyactive'     => new external_value(PARAM_INT, 'True means only active, false means all participants', VALUE_DEFAULT, 0),
 831              )
 832          );
 833      }
 834  
 835      /**
 836       * Get list of course participants.
 837       *
 838       * @param int $courseid
 839       * @param text $withcapability
 840       * @param int $groupid
 841       * @param bool $onlyactive
 842       * @return array of course participants
 843       * @since Moodle 2.0
 844       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 845       * @see core_enrol_external::get_enrolled_users()
 846       */
 847      public static function get_enrolled_users($courseid, $withcapability = null, $groupid = null, $onlyactive = false) {
 848          global $DB, $CFG, $USER;
 849  
 850          // Do basic automatic PARAM checks on incoming data, using params description
 851          // If any problems are found then exceptions are thrown with helpful error messages
 852          $params = self::validate_parameters(self::get_enrolled_users_parameters(), array(
 853              'courseid'=>$courseid,
 854              'withcapability'=>$withcapability,
 855              'groupid'=>$groupid,
 856              'onlyactive'=>$onlyactive)
 857          );
 858  
 859          $coursecontext = context_course::instance($params['courseid'], IGNORE_MISSING);
 860          if ($courseid == SITEID) {
 861              $context = context_system::instance();
 862          } else {
 863              $context = $coursecontext;
 864          }
 865  
 866          try {
 867              self::validate_context($context);
 868          } catch (Exception $e) {
 869              $exceptionparam = new stdClass();
 870              $exceptionparam->message = $e->getMessage();
 871              $exceptionparam->courseid = $params['courseid'];
 872              throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
 873          }
 874  
 875          if ($courseid == SITEID) {
 876              require_capability('moodle/site:viewparticipants', $context);
 877          } else {
 878              require_capability('moodle/course:viewparticipants', $context);
 879          }
 880  
 881          if ($withcapability) {
 882              require_capability('moodle/role:review', $coursecontext);
 883          }
 884          if ($groupid && groups_is_member($groupid)) {
 885              require_capability('moodle/site:accessallgroups', $coursecontext);
 886          }
 887          if ($onlyactive) {
 888              require_capability('moodle/course:enrolreview', $coursecontext);
 889          }
 890  
 891          list($sqlparams, $params) =  get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
 892          $sql = "SELECT ue.userid, e.courseid, u.firstname, u.lastname, u.username, c.id as usercontextid
 893                    FROM {user_enrolments} ue
 894                    JOIN {enrol} e ON (e.id = ue.enrolid)
 895                    JOIN {user} u ON (ue.userid = u.id)
 896                    JOIN {context} c ON (u.id = c.instanceid AND contextlevel = " . CONTEXT_USER . ")
 897                    WHERE e.courseid = :courseid AND ue.userid IN ($sqlparams)
 898                    GROUP BY ue.userid, e.courseid, u.firstname, u.lastname, u.username, c.id";
 899          $params['courseid'] = $courseid;
 900          $enrolledusers = $DB->get_records_sql($sql, $params);
 901          $result = array();
 902          $isadmin = is_siteadmin($USER);
 903          $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
 904          foreach ($enrolledusers as $enrolleduser) {
 905              $profilimgurl = moodle_url::make_pluginfile_url($enrolleduser->usercontextid, 'user', 'icon', NULL, '/', 'f1');
 906              $profilimgurlsmall = moodle_url::make_pluginfile_url($enrolleduser->usercontextid, 'user', 'icon', NULL, '/', 'f2');
 907              $resultuser = array(
 908                  'courseid' => $enrolleduser->courseid,
 909                  'userid' => $enrolleduser->userid,
 910                  'fullname' => fullname($enrolleduser),
 911                  'profileimgurl' => $profilimgurl->out(false),
 912                  'profileimgurlsmall' => $profilimgurlsmall->out(false)
 913              );
 914              // check if we can return username
 915              if ($isadmin) {
 916                  $resultuser['username'] = $enrolleduser->username;
 917              }
 918              // check if we can return first and last name
 919              if ($isadmin or $canviewfullnames) {
 920                  $resultuser['firstname'] = $enrolleduser->firstname;
 921                  $resultuser['lastname'] = $enrolleduser->lastname;
 922              }
 923              $result[] = $resultuser;
 924          }
 925  
 926          return $result;
 927      }
 928  
 929      /**
 930       * Returns description of method result value
 931       *
 932       * @return external_description
 933       * @since Moodle 2.0
 934       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 935       * @see core_enrol_external::get_enrolled_users_returns()
 936       */
 937      public static function get_enrolled_users_returns() {
 938          return new external_multiple_structure(
 939              new external_single_structure(
 940                  array(
 941                      'courseid' => new external_value(PARAM_INT, 'id of course'),
 942                      'userid' => new external_value(PARAM_INT, 'id of user'),
 943                      'firstname' => new external_value(PARAM_RAW, 'first name of user', VALUE_OPTIONAL),
 944                      'lastname' => new external_value(PARAM_RAW, 'last name of user', VALUE_OPTIONAL),
 945                      'fullname' => new external_value(PARAM_RAW, 'fullname of user'),
 946                      'username' => new external_value(PARAM_RAW, 'username of user', VALUE_OPTIONAL),
 947                      'profileimgurl' => new external_value(PARAM_URL, 'url of the profile image'),
 948                      'profileimgurlsmall' => new external_value(PARAM_URL, 'url of the profile image (small version)')
 949                  )
 950              )
 951          );
 952      }
 953  
 954      /**
 955       * Returns description of method parameters
 956       *
 957       * @return external_function_parameters
 958       * @since Moodle 2.1
 959       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 960       * @see core_enrol_external::get_users_courses_parameters()
 961       */
 962      public static function get_users_courses_parameters() {
 963          return core_enrol_external::get_users_courses_parameters();
 964      }
 965  
 966      /**
 967       * Get list of courses user is enrolled in (only active enrolments are returned).
 968       * Please note the current user must be able to access the course, otherwise the course is not included.
 969       *
 970       * @param int $userid
 971       * @return array of courses
 972       * @since Moodle 2.1
 973       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 974       * @see use core_enrol_external::get_users_courses()
 975       */
 976      public static function get_users_courses($userid) {
 977          return core_enrol_external::get_users_courses($userid);
 978      }
 979  
 980      /**
 981       * Returns description of method result value
 982       *
 983       * @return external_description
 984       * @since Moodle 2.1
 985       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 986       * @see core_enrol_external::get_users_courses_returns()
 987       */
 988      public static function get_users_courses_returns() {
 989          return core_enrol_external::get_users_courses_returns();
 990      }
 991  
 992  
 993      /**
 994       * Returns description of method parameters
 995       *
 996       * @return external_function_parameters
 997       * @since Moodle 2.0
 998       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
 999       * @see core_role_external::assign_roles_parameters()
1000       */
1001      public static function role_assign_parameters() {
1002          return core_role_external::assign_roles_parameters();
1003      }
1004  
1005      /**
1006       * Manual role assignments to users
1007       *
1008       * @param array $assignments An array of manual role assignment
1009       * @since Moodle 2.0
1010       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1011       * @see core_role_external::assign_roles()
1012       */
1013      public static function role_assign($assignments) {
1014          return core_role_external::assign_roles($assignments);
1015      }
1016  
1017      /**
1018       * Returns description of method result value
1019       *
1020       * @return null
1021       * @since Moodle 2.0
1022       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1023       * @see core_role_external::assign_roles_returns()
1024       */
1025      public static function role_assign_returns() {
1026          return core_role_external::assign_roles_returns();
1027      }
1028  
1029  
1030      /**
1031       * Returns description of method parameters
1032       *
1033       * @return external_function_parameters
1034       * @since Moodle 2.0
1035       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1036       * @see core_role_external::unassign_roles_parameters()
1037       */
1038      public static function role_unassign_parameters() {
1039          return core_role_external::unassign_roles_parameters();
1040      }
1041  
1042       /**
1043       * Unassign roles from users
1044       *
1045       * @param array $unassignments An array of unassignment
1046       * @since Moodle 2.0
1047       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1048       * @see core_role_external::unassign_roles()
1049       */
1050      public static function role_unassign($unassignments) {
1051           return core_role_external::unassign_roles($unassignments);
1052      }
1053  
1054     /**
1055       * Returns description of method result value
1056       *
1057       * @return null
1058       * @since Moodle 2.0
1059       * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1060       * @see core_role_external::unassign_roles_returns()
1061       */
1062      public static function role_unassign_returns() {
1063          return core_role_external::unassign_roles_returns();
1064      }
1065  }

Search This Site: