Uploaded image for project: 'Moodle'
  1. Moodle
  2. MDL-28606

core_course_get_courses_by_shortname + core_user_get_users_by_username

XMLWordPrintable

    • Icon: New Feature New Feature
    • Resolution: Duplicate
    • Icon: Minor Minor
    • None
    • 2.0.2
    • Course, Web Services
    • Any
    • MOODLE_20_STABLE

      I've been working on code to provision courses and users from an ldap tree to moodle, and one of the first steps in provisioning is to see if the user or course already exists in moodle. To check this, I need external functions to search for users and courses by username and shortname, respectively. Here's the two functions I came up with:

      moodleDir/course/externallib.php

          public static function get_courses_by_shortname_parameters() {
              return new external_function_parameters(
                      array('options' => new external_single_structure(
                                  array('shortnames' => new external_multiple_structure(
                                              new external_value(PARAM_RAW, 'Short Name')
                                              , 'List of short names. If empty return all courses
                                                  except front page course.',
                                              VALUE_OPTIONAL)
                                  ), 'options - operator OR is used', VALUE_DEFAULT, array())
                      )
              );
          }
       
          /**
           * Get courses
           * @param array $options
           * @return array
           */
          public static function get_courses_by_shortname($options) {
              global $CFG, $DB;
              require_once($CFG->dirroot . "/course/lib.php");
       
              //validate parameter
              $params = self::validate_parameters(self::get_courses_by_shortname_parameters(),
                              array('options' => $options));
       
              //retrieve courses
              if (!key_exists('shortnames', $params['options'])
                      or empty($params['options']['shortnames'])) {
                  $courses = $DB->get_records('course');
              } else {
                  $courses = $DB->get_records_list('course', 'shortname', $params['options']['shortnames']);
              }
       
              //create return value
              $coursesinfo = array();
              foreach ($courses as $course) {
       
                  // now security checks
                  $context = get_context_instance(CONTEXT_COURSE, $course->id);
                  try {
                      self::validate_context($context);
                  } catch (Exception $e) {
                      $exceptionparam = new stdClass();
                      $exceptionparam->message = $e->getMessage();
                      $exceptionparam->shortname = $course->shortname;
                      throw new moodle_exception(
                              get_string('errorcoursecontextnotvalid', 'webservice', $exceptionparam));
                  }
                  require_capability('moodle/course:view', $context);
       
                  $courseinfo = array();
                  $courseinfo['id'] = $course->id;
                  $courseinfo['fullname'] = $course->fullname;
                  $courseinfo['shortname'] = $course->shortname;
                  $courseinfo['categoryid'] = $course->category;
                  $courseinfo['summary'] = $course->summary;
                  $courseinfo['summaryformat'] = $course->summaryformat;
                  $courseinfo['format'] = $course->format;
                  $courseinfo['startdate'] = $course->startdate;
                  $courseinfo['numsections'] = $course->numsections;
       
                  //some field should be returned only if the user has update permission
                  $courseadmin = has_capability('moodle/course:update', $context);
                  if ($courseadmin) {
                      $courseinfo['categorysortorder'] = $course->sortorder;
                      $courseinfo['idnumber'] = $course->idnumber;
                      $courseinfo['showgrades'] = $course->showgrades;
                      $courseinfo['showreports'] = $course->showreports;
                      $courseinfo['newsitems'] = $course->newsitems;
                      $courseinfo['visible'] = $course->visible;
                      $courseinfo['maxbytes'] = $course->maxbytes;
                      $courseinfo['hiddensections'] = $course->hiddensections;
                      $courseinfo['groupmode'] = $course->groupmode;
                      $courseinfo['groupmodeforce'] = $course->groupmodeforce;
                      $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
                      $courseinfo['lang'] = $course->lang;
                      $courseinfo['timecreated'] = $course->timecreated;
                      $courseinfo['timemodified'] = $course->timemodified;
                      $courseinfo['forcetheme'] = $course->theme;
                      $courseinfo['enablecompletion'] = $course->enablecompletion;
                      $courseinfo['completionstartonenrol'] = $course->completionstartonenrol;
                      $courseinfo['completionnotify'] = $course->completionnotify;
                  }
       
                  if ($courseadmin or $course->visible
                          or has_capability('moodle/course:viewhiddencourses', $context)) {
                      $coursesinfo[] = $courseinfo;
                  }
              }
       
              return $coursesinfo;
          }
       
          /**
           * Returns description of method result value
           * @return external_description
           */
          public static function get_courses_by_shortname_returns() {
              return new external_multiple_structure(
                      new external_single_structure(
                              array(
                                  'id' => new external_value(PARAM_INT, 'course id'),
                                  'shortname' => new external_value(PARAM_TEXT, 'course short name'),
                                  'categoryid' => new external_value(PARAM_INT, 'category id'),
                                  'categorysortorder' => new external_value(PARAM_INT,
                                          'sort order into the category', VALUE_OPTIONAL),
                                  'fullname' => new external_value(PARAM_TEXT, 'full name'),
                                  'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
                                  'summary' => new external_value(PARAM_RAW, 'summary'),
                                  'summaryformat' => new external_value(PARAM_INT,
                                          'the summary text Moodle format'),
                                  'format' => new external_value(PARAM_ALPHANUMEXT,
                                          'course format: weeks, topics, social, site,..'),
                                  'showgrades' => new external_value(PARAM_INT,
                                          '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
                                  'newsitems' => new external_value(PARAM_INT,
                                          'number of recent items appearing on the course page', VALUE_OPTIONAL),
                                  'startdate' => new external_value(PARAM_INT,
                                          'timestamp when the course start'),
                                  'numsections' => new external_value(PARAM_INT, 'number of weeks/topics'),
                                  'maxbytes' => new external_value(PARAM_INT,
                                          'largest size of file that can be uploaded into the course',
                                          VALUE_OPTIONAL),
                                  'showreports' => new external_value(PARAM_INT,
                                          'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
                                  'visible' => new external_value(PARAM_INT,
                                          '1: available to student, 0:not available', VALUE_OPTIONAL),
                                  'hiddensections' => new external_value(PARAM_INT,
                                          'How the hidden sections in the course are displayed to students',
                                          VALUE_OPTIONAL),
                                  'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
                                          VALUE_OPTIONAL),
                                  'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
                                          VALUE_OPTIONAL),
                                  'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
                                          VALUE_OPTIONAL),
                                  'timecreated' => new external_value(PARAM_INT,
                                          'timestamp when the course have been created', VALUE_OPTIONAL),
                                  'timemodified' => new external_value(PARAM_INT,
                                          'timestamp when the course have been modified', VALUE_OPTIONAL),
                                  'enablecompletion' => new external_value(PARAM_INT,
                                          'Enabled, control via completion and activity settings. Disbaled,
                                              not shown in activity settings.',
                                          VALUE_OPTIONAL),
                                  'completionstartonenrol' => new external_value(PARAM_INT,
                                          '1: begin tracking a student\'s progress in course completion
                                              after course enrolment. 0: does not',
                                          VALUE_OPTIONAL),
                                  'completionnotify' => new external_value(PARAM_INT,
                                          '1: yes 0: no', VALUE_OPTIONAL),
                                  'lang' => new external_value(PARAM_ALPHANUMEXT,
                                          'forced course language', VALUE_OPTIONAL),
                                  'forcetheme' => new external_value(PARAM_ALPHANUMEXT,
                                          'name of the force theme', VALUE_OPTIONAL),
                              ), 'course'
                      )
              );
          }

      And for users:

      moodleDir/user/externallib.php

                /**
           * Returns description of method parameters
           * @return external_function_parameters
           */
          public static function get_users_by_username_parameters() {
              return new external_function_parameters(
                      array(
                          'usernames' => new external_multiple_structure(new external_value(PARAM_RAW, 'User Name')),
                      )
              );
          }
          
           
          
             /**
           * Get user information
           *
           * @param array $usernames  array of usernames
           * @return array An array of arrays describing users
           */
          public static function get_users_by_username($usernames) {
              global $CFG;
              require_once($CFG->dirroot . "/user/lib.php");
              //required for customfields related function
              //TODO: move the functions somewhere else as
              //they are "user" related
              require_once($CFG->dirroot . "/user/profile/lib.php");
       
              $params = self::validate_parameters(self::get_users_by_username_parameters(),
                      array('usernames'=>$usernames));
       
              //TODO: check if there is any performance issue: we do one DB request to retrieve
              //  all user, then for each user the profile_load_data does at least two DB requests
       
              $users = user_get_users_by_username($params['usernames']);
       
              $result = array();
              foreach ($users as $user) {
       
                  $context = get_context_instance(CONTEXT_USER, $user->id);
                  require_capability('moodle/user:viewalldetails', $context);
                  self::validate_context($context);
       
                  if (empty($user->deleted)) {
       
                      $userarray = array();
                     //we want to return an array not an object
                      /// now we transfert all profile_field_xxx into the customfields
                      // external_multiple_structure required by description
                      $userarray['id'] = $user->id;
                      $userarray['username'] = $user->username;
                      $userarray['firstname'] = $user->firstname;
                      $userarray['lastname'] = $user->lastname;
                      $userarray['email'] = $user->email;
                      $userarray['auth'] = $user->auth;
                      $userarray['confirmed'] = $user->confirmed;
                      $userarray['idnumber'] = $user->idnumber;
                      $userarray['lang'] = $user->lang;
                      $userarray['theme'] = $user->theme;
                      $userarray['timezone'] = $user->timezone;
                      $userarray['mailformat'] = $user->mailformat;
                      $userarray['description'] = $user->description;
                      $userarray['descriptionformat'] = $user->descriptionformat;
                      $userarray['city'] = $user->city;
                      $userarray['country'] = $user->country;
                      $userarray['customfields'] = array();
                      $customfields = profile_user_record($user->id);
                      $customfields = (array) $customfields;
                      foreach ($customfields as $key => $value) {
                          $userarray['customfields'][] = array('type' => $key, 'value' => $value);
                      }
       
                      $result[] = $userarray;
                  }
              }
      	
              return $result;
          }
          
              /**
           * Returns description of method result value
           * @return external_description
           */
          public static function get_users_by_username_returns() {
              return new external_multiple_structure(
                      new external_single_structure(
                              array(
                          'id'    => new external_value(PARAM_NUMBER, 'ID of the user'),
                          'username'    => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config'),
                          'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
                          'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user'),
                          'email'       => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost'),
                          'auth'        => new external_value(PARAM_SAFEDIR, 'Auth plugins include manual, ldap, imap, etc'),
                          'confirmed'   => new external_value(PARAM_NUMBER, 'Active user: 1 if confirmed, 0 otherwise'),
                          'idnumber'    => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution'),
                          'lang'        => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server'),
                          'theme'       => new external_value(PARAM_SAFEDIR, 'Theme name such as "standard", must exist on server'),
                          'timezone'    => new external_value(PARAM_ALPHANUMEXT, 'Timezone code such as Australia/Perth, or 99 for default'),
                          'mailformat'  => new external_value(PARAM_INTEGER, 'Mail format code is 0 for plain text, 1 for HTML etc'),
                          'description' => new external_value(PARAM_RAW, 'User profile description'),
                          'descriptionformat' => new external_value(PARAM_INT, 'User profile description format'),
                          'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user'),
                          'country'     => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ'),
                          'customfields' => new external_multiple_structure(
                                          new external_single_structure(
                                                  array(
                                                      'type'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
                                                      'value' => new external_value(PARAM_RAW, 'The value of the custom field')
                                                  )
                                          ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
                              )
                      )
              );
          }

            jerome Jérôme Mouneyrac
            cbaker118 Craig Baker
            Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved:

                Error rendering 'clockify-timesheets-time-tracking-reports:timer-sidebar'. Please contact your Jira administrators.