Пример #1
0
 /**
  * Initialise this screen
  *
  * @param bool $selfitemisempty Has an item been selected (will be false)
  */
 public function init($selfitemisempty = false)
 {
     global $DB;
     $roleids = explode(',', get_config('moodle', 'gradebookroles'));
     $this->items = get_role_users($roleids, $this->context, false, '', 'u.id, u.lastname, u.firstname', null, $this->groupid, $this->perpage * $this->page, $this->perpage);
     $this->item = $DB->get_record('course', array('id' => $this->courseid));
 }
/**
 * Find the list of users and get a list with the ids of students and a list of non-students
 * @param type $context_course
 * @return array(array($studentIds), array($non_studentIds), array($activeids), array($user_records))
 */
function blended_get_users_by_type($context_course)
{
    // Get users with gradable roles
    global $CFG;
    $gradable_roles = $CFG->gradebookroles;
    $roles = explode(',', $gradable_roles);
    $students = array();
    foreach ($roles as $roleid) {
        $users_in_role = get_role_users($roleid, $context_course);
        $ids = array_keys($users_in_role);
        $students = array_merge($students, $ids);
        $students = array_unique($students);
    }
    // get enrolled users
    $user_records = get_enrolled_users($context_course, '', 0, '*');
    $users = array_keys($user_records);
    $non_students = array_diff($users, $students);
    // select active userids
    $activeids = array();
    global $DB;
    list($select, $params) = $DB->get_in_or_equal($students);
    $select = "userid {$select}";
    $select .= " AND courseid = ?";
    $params[] = (int) $context_course->instanceid;
    $last_accesses = $DB->get_records_select('user_lastaccess', $select, $params);
    foreach ($last_accesses as $record) {
        $activeids[] = $record->userid;
    }
    return array($students, $non_students, $activeids, $user_records);
}
Пример #3
0
 /**
  * Renders course info box.
  *
  * @param stdClass $course
  * @return string
  */
 public function course_info_box(stdClass $course)
 {
     global $CFG;
     $context = context_course::instance($course->id);
     $content = '';
     $content .= $this->output->box_start('generalbox info');
     $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
     $content .= format_text($summary, $course->summaryformat, array('overflowdiv' => true), $course->id);
     if (!empty($CFG->coursecontact)) {
         $coursecontactroles = explode(',', $CFG->coursecontact);
         foreach ($coursecontactroles as $roleid) {
             if ($users = get_role_users($roleid, $context, true)) {
                 foreach ($users as $teacher) {
                     $role = new stdClass();
                     $role->id = $teacher->roleid;
                     $role->name = $teacher->rolename;
                     $role->shortname = $teacher->roleshortname;
                     $role->coursealias = $teacher->rolecoursealias;
                     $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
                     $namesarray[] = role_get_name($role, $context) . ': <a href="' . $CFG->wwwroot . '/user/view.php?id=' . $teacher->id . '&amp;course=' . SITEID . '">' . $fullname . '</a>';
                 }
             }
         }
         if (!empty($namesarray)) {
             $content .= "<ul class=\"teachers\">\n<li>";
             $content .= implode('</li><li>', $namesarray);
             $content .= "</li></ul>";
         }
     }
     $content .= $this->output->box_end();
     return $content;
 }
 function execute($data, $user, $courseid)
 {
     $context = get_context_instance(CONTEXT_COURSE, $courseid);
     if ($users = get_role_users($data->roles, $context, false, 'u.id')) {
         return array_keys($users);
     }
     return array();
 }
Пример #5
0
 function execute($data, $user, $courseid)
 {
     global $DB;
     $context = cr_get_context(CONTEXT_COURSE, $courseid);
     if ($users = get_role_users($data->roles, $context, false, 'u.id', 'u.id')) {
         return array_keys($users);
     }
     return array();
 }
Пример #6
0
function getStudentsByCourse($courseId)
{

$courses = get_courses();
            $context = context_course::instance($courseId);//course id
   
            $students = get_role_users(5, $context); //student context
                  return   $students ;

}
Пример #7
0
/**
* @desc Finds all of the users in the course
* @param $courseid   -- the course id
* @return record containing user information ( username, userid)
*/
function _wwassignment_get_course_students($courseid)
{
    debugLog("Begin get_course_students({$courseid} )");
    debugLog("courseID is " . print_r($courseid, true));
    $context = get_context_instance(CONTEXT_COURSE, $courseid);
    debugLog("context is " . print_r($context, true));
    $users = array();
    $roles_used_in_context = get_roles_used_in_context($context);
    //debugLog("roles used ". print_r($roles_used_in_context, true));
    foreach ($roles_used_in_context as $role) {
        $roleid = $role->id;
        debugLog("roleid should be 5 for a student {$roleid}");
        //debugLog(get_role_users($roleid, $context, true) );
        if ($new_users = get_role_users($roleid, $context, true)) {
            $users = array_merge($users, $new_users);
            //FIXME a user could be liseted twice
        }
        debugLog("display users " . print_r($users, true));
    }
    debugLog("display users in course--on");
    debugLog("users again" . print_r($users, true));
    debugLog("End get_course_students({$courseid} )");
    return $users;
}
 /**
  * Retrieve all known users for the current Moodle user
  * @return array Array of objects featuring name and Moodle id
  */
 function getKnownUsers()
 {
     global $course;
     $context = get_context_instance(CONTEXT_COURSE, $course->id);
     $students = get_role_users(5, $context);
     $tmp = (array) null;
     foreach ($students as $student) {
         $knownUser = (object) null;
         $knownUser->id = $student->id;
         if ($student->maildisplay) {
             $knownUser->email = $student->email;
         }
         $fullname = $student->firstname . ' ' . $student->lastname;
         if (strlen(trim($fullname)) == 0) {
             $fullname = $student->username;
         }
         $knownUser->name = $fullname;
         if ($account_link = get_record("studynotes_account_links", "system", "moodle", "external_id", $student->id)) {
             $knownUser->mb_id = $account_link->internal_id;
         }
         $tmp[] = $knownUser;
     }
     return $tmp;
 }
Пример #9
0
			function get_course_absenties($cid){

				$context = context_course::instance($cid);
				$enrolledStudents = get_role_users(5 , $context);//getting all the students from a course level
				$loggedinusers=get_all_loggedin_users('All');


				$logstuarr=array();$cnt=0;
				foreach($loggedinusers as $logstudent){

					$logstuarr[$cnt++]=array('stid'=>$logstudent->userid);

				}
				$lgss=array_column($logstuarr, 'stid');
				//print_r($lgss);

				$absented_Students=array();$stcnt=0;
				foreach($enrolledStudents as $student){
					if(in_array($student->id, $lgss)){}
					else{
						$absented_Students[$stcnt++]=array('stid'=>$student->id);
					}
				}
				$absented_Students=array_column($absented_Students,'stid');
				return $absented_Students;

			}
Пример #10
0
 /**
  * Send welcome email to specified user.
  *
  * @param stdClass $instance
  * @param stdClass $user user record
  * @return void
  */
 protected function email_welcome_message($instance, $user)
 {
     global $CFG, $DB;
     $course = $DB->get_record('course', array('id' => $instance->courseid), '*', MUST_EXIST);
     $context = context_course::instance($course->id);
     $a = new stdClass();
     $a->coursename = format_string($course->fullname, true, array('context' => $context));
     $a->profileurl = "{$CFG->wwwroot}/user/view.php?id={$user->id}&course={$course->id}";
     if (trim($instance->customtext1) !== '') {
         $message = $instance->customtext1;
         $key = array('{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}');
         $value = array($a->coursename, $a->profileurl, fullname($user), $user->email);
         $message = str_replace($key, $value, $message);
         if (strpos($message, '<') === false) {
             // Plain text only.
             $messagetext = $message;
             $messagehtml = text_to_html($messagetext, null, false, true);
         } else {
             // This is most probably the tag/newline soup known as FORMAT_MOODLE.
             $messagehtml = format_text($message, FORMAT_MOODLE, array('context' => $context, 'para' => false, 'newlines' => true, 'filter' => true));
             $messagetext = html_to_text($messagehtml);
         }
     } else {
         $messagetext = get_string('welcometocoursetext', 'enrol_self', $a);
         $messagehtml = text_to_html($messagetext, null, false, true);
     }
     $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context' => $context)));
     $rusers = array();
     if (!empty($CFG->coursecontact)) {
         $croles = explode(',', $CFG->coursecontact);
         list($sort, $sortparams) = users_order_by_sql('u');
         // We only use the first user.
         $i = 0;
         do {
             $rusers = get_role_users($croles[$i], $context, true, '', 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
             $i++;
         } while (empty($rusers) && !empty($croles[$i]));
     }
     if ($rusers) {
         $contact = reset($rusers);
     } else {
         $contact = core_user::get_support_user();
     }
     // Directly emailing welcome message rather than using messaging.
     email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
 }
Пример #11
0
 function definition()
 {
     global $USER, $CFG, $DB;
     $courseconfig = get_config('moodlecourse');
     $mform =& $this->_form;
     $course = $this->_customdata['course'];
     $category = $this->_customdata['category'];
     $systemcontext = get_context_instance(CONTEXT_SYSTEM);
     $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);
     $disable_meta = false;
     // basic meta course state protection; server-side security checks not needed
     if (!empty($course)) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
         $context = $coursecontext;
         if (course_in_meta($course)) {
             $disable_meta = get_string('metaalreadyinmeta');
         } else {
             if ($course->metacourse) {
                 if ($DB->count_records('course_meta', array('parent_course' => $course->id)) > 0) {
                     $disable_meta = get_string('metaalreadyhascourses');
                 }
             } else {
                 // if users already enrolled directly into coures, do not allow switching to meta,
                 // users with metacourse manage permission are exception
                 // please note that we do not need exact results - anything unexpected here prevents metacourse
                 $managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id');
                 $enrolroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $coursecontext);
                 if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) {
                     foreach ($users as $user) {
                         if (!isset($managers[$user->id])) {
                             $disable_meta = get_string('metaalreadyhasenrolments');
                             break;
                         }
                     }
                 }
                 unset($managers);
                 unset($users);
                 unset($enrolroles);
             }
         }
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     // Must have create course capability in both categories in order to move course
     if (has_capability('moodle/course:create', $categorycontext)) {
         $displaylist = array();
         $parentlist = array();
         make_categories_list($displaylist, $parentlist, 'moodle/course:create');
         $mform->addElement('select', 'category', get_string('category'), $displaylist);
     } else {
         $mform->addElement('hidden', 'category', null);
     }
     $mform->setHelpButton('category', array('coursecategory', get_string('category')));
     $mform->setDefault('category', $category->id);
     $mform->setType('category', PARAM_INT);
     $fullname = get_string('defaultcoursefullname');
     $shortname = get_string('defaultcourseshortname');
     while ($DB->record_exists('course', array('fullname' => $fullname)) or $DB->record_exists('course', array('fullname' => $fullname))) {
         $fullname++;
         $shortname++;
     }
     $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"');
     $mform->setHelpButton('fullname', array('coursefullname', get_string('fullnamecourse')), true);
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changefullname', $coursecontext)) {
         $mform->hardFreeze('fullname');
         $mform->setConstant('fullname', $course->fullname);
     }
     $mform->setDefault('fullname', $fullname);
     $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
     $mform->setHelpButton('shortname', array('courseshortname', get_string('shortnamecourse')), true);
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changeshortname', $coursecontext)) {
         $mform->hardFreeze('shortname');
         $mform->setConstant('shortname', $course->shortname);
     }
     $mform->setDefault('shortname', $shortname);
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->setHelpButton('idnumber', array('courseidnumber', get_string('idnumbercourse')), true);
     $mform->setType('idnumber', PARAM_RAW);
     if ($course and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
         $mform->hardFreeze('idnumber');
         $mform->setConstants('idnumber', $course->idnumber);
     }
     $mform->addElement('htmleditor', 'summary', get_string('summary'), array('rows' => '10', 'cols' => '65'));
     $mform->setHelpButton('summary', array('text2', get_string('helptext')), true);
     $mform->setType('summary', PARAM_RAW);
     $courseformats = get_list_of_plugins('course/format');
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}", "format_{$courseformat}");
         if ($formcourseformats["{$courseformat}"] == "[[format{$courseformat}]]") {
             $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}");
         }
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->setHelpButton('format', array('courseformats', get_string('courseformats')), true);
     $mform->setDefault('format', $courseconfig->format);
     for ($i = 1; $i <= 52; $i++) {
         $sectionmenu[$i] = "{$i}";
     }
     $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu);
     $mform->setDefault('numsections', $courseconfig->numsections);
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->setHelpButton('startdate', array('coursestartdate', get_string('startdate')), true);
     $mform->setDefault('startdate', time() + 3600 * 24);
     $choices = array();
     $choices['0'] = get_string('hiddensectionscollapsed');
     $choices['1'] = get_string('hiddensectionsinvisible');
     $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices);
     $mform->setHelpButton('hiddensections', array('coursehiddensections', get_string('hiddensections')), true);
     $mform->setDefault('hiddensections', $courseconfig->hiddensections);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->setHelpButton('newsitems', array('coursenewsitems', get_string('newsitemsnumber')), true);
     $mform->setDefault('newsitems', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->setHelpButton('showgrades', array('coursegrades', get_string('grades')), true);
     $mform->setDefault('showgrades', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->setHelpButton('showreports', array('coursereports', get_string('activityreport')), true);
     $mform->setDefault('showreports', $courseconfig->showreports);
     $choices = get_max_upload_sizes($CFG->maxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->setHelpButton('maxbytes', array('courseuploadsize', get_string('maximumupload')), true);
     $mform->setDefault('maxbytes', $courseconfig->maxbytes);
     if (!empty($CFG->allowcoursethemes)) {
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $meta = array();
     $meta[0] = get_string('no');
     $meta[1] = get_string('yes');
     if ($disable_meta === false) {
         $mform->addElement('select', 'metacourse', get_string('managemeta'), $meta);
         $mform->setHelpButton('metacourse', array('metacourse', get_string('metacourse')), true);
         $mform->setDefault('metacourse', $courseconfig->metacourse);
     } else {
         // no metacourse element - we do not want to change it anyway!
         $mform->addElement('static', 'nometacourse', get_string('managemeta'), (empty($course->metacourse) ? $meta[0] : $meta[1]) . " - {$disable_meta} ");
         $mform->setHelpButton('nometacourse', array('metacourse', get_string('metacourse')), true);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'enrolhdr', get_string('enrolments'));
     $choices = array();
     $modules = explode(',', $CFG->enrol_plugins_enabled);
     foreach ($modules as $module) {
         $name = get_string('enrolname', "enrol_{$module}");
         $plugin = enrolment_factory::factory($module);
         if (method_exists($plugin, 'print_entry')) {
             $choices[$name] = $module;
         }
     }
     asort($choices);
     $choices = array_flip($choices);
     $choices = array_merge(array('' => get_string('sitedefault') . ' (' . get_string('enrolname', "enrol_{$CFG->enrol}") . ')'), $choices);
     $mform->addElement('select', 'enrol', get_string('enrolmentplugins'), $choices);
     $mform->setHelpButton('enrol', array('courseenrolmentplugins', get_string('enrolmentplugins')), true);
     $mform->setDefault('enrol', $courseconfig->enrol);
     $roles = get_assignable_roles($context);
     if (!empty($course)) {
         // add current default role, so that it is selectable even when user can not assign it
         if ($current_role = $DB->get_record('role', array('id' => $course->defaultrole))) {
             $roles[$current_role->id] = strip_tags(format_string($current_role->name, true));
         }
     }
     $choices = array();
     if ($sitedefaultrole = $DB->get_record('role', array('id' => $CFG->defaultcourseroleid))) {
         $choices[0] = get_string('sitedefault') . ' (' . $sitedefaultrole->name . ')';
     } else {
         $choices[0] = get_string('sitedefault');
     }
     $choices = $choices + $roles;
     // fix for MDL-9197
     foreach ($choices as $choiceid => $choice) {
         $choices[$choiceid] = format_string($choice);
     }
     $mform->addElement('select', 'defaultrole', get_string('defaultrole', 'role'), $choices);
     $mform->setDefault('defaultrole', 0);
     $radio = array();
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('no'), 0);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('yes'), 1);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('enroldate'), 2);
     $mform->addGroup($radio, 'enrollable', get_string('enrollable'), ' ', false);
     $mform->setHelpButton('enrollable', array('courseenrollable2', get_string('enrollable')), true);
     $mform->setDefault('enrollable', $courseconfig->enrollable);
     $mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate'), array('optional' => true));
     $mform->setDefault('enrolstartdate', 0);
     $mform->disabledIf('enrolstartdate', 'enrollable', 'neq', 2);
     $mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate'), array('optional' => true));
     $mform->setDefault('enrolenddate', 0);
     $mform->disabledIf('enrolenddate', 'enrollable', 'neq', 2);
     $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod'), array('optional' => true, 'defaultunit' => 86400));
     $mform->setDefault('enrolperiod', $courseconfig->enrolperiod);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'expirynotifyhdr', get_string('expirynotify'));
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'expirynotify', get_string('notify'), $choices);
     $mform->setHelpButton('expirynotify', array('expirynotify', get_string('expirynotify')), true);
     $mform->setDefault('expirynotify', $courseconfig->expirynotify);
     $mform->addElement('select', 'notifystudents', get_string('expirynotifystudents'), $choices);
     $mform->setHelpButton('notifystudents', array('expirynotifystudents', get_string('expirynotifystudents')), true);
     $mform->setDefault('notifystudents', $courseconfig->notifystudents);
     $thresholdmenu = array();
     for ($i = 1; $i <= 30; $i++) {
         $seconds = $i * 86400;
         $thresholdmenu[$seconds] = get_string('numdays', '', $i);
     }
     $mform->addElement('select', 'expirythreshold', get_string('expirythreshold'), $thresholdmenu);
     $mform->setHelpButton('expirythreshold', array('expirythreshold', get_string('expirythreshold')), true);
     $mform->setDefault('expirythreshold', $courseconfig->expirythreshold);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'groupmode', get_string('groupmode'), $choices);
     $mform->setHelpButton('groupmode', array('groupmode', get_string('groupmode')), true);
     $mform->setDefault('groupmode', $courseconfig->groupmode);
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'groupmodeforce', get_string('force'), $choices);
     $mform->setHelpButton('groupmodeforce', array('groupmodeforce', get_string('groupmodeforce')), true);
     $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
     if (!empty($CFG->enablegroupings)) {
         //default groupings selector
         $options = array();
         $options[0] = get_string('none');
         $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('availability'));
     $choices = array();
     $choices['0'] = get_string('courseavailablenot');
     $choices['1'] = get_string('courseavailable');
     $mform->addElement('select', 'visible', get_string('availability'), $choices);
     $mform->setHelpButton('visible', array('courseavailability', get_string('availability')), true);
     $mform->setDefault('visible', $courseconfig->visible);
     if ($course and !has_capability('moodle/course:visibility', $coursecontext)) {
         $mform->hardFreeze('visible');
         $mform->setConstant('visible', $course->visible);
     }
     $mform->addElement('passwordunmask', 'enrolpassword', get_string('enrolmentkey'), 'size="25"');
     $mform->setHelpButton('enrolpassword', array('enrolmentkey', get_string('enrolmentkey')), true);
     $mform->setDefault('enrolpassword', '');
     $mform->setDefault('enrolpassword', $courseconfig->enrolpassword);
     $mform->setType('enrolpassword', PARAM_RAW);
     if (empty($course) or $course->password !== '' and $course->id != SITEID) {
         // do not require password in existing courses that do not have password yet - backwards compatibility ;-)
         if (!empty($CFG->enrol_manual_requirekey)) {
             $mform->addRule('enrolpassword', get_string('required'), 'required', null, 'client');
         }
     }
     $choices = array();
     $choices['0'] = get_string('guestsno');
     $choices['1'] = get_string('guestsyes');
     $choices['2'] = get_string('guestskey');
     $mform->addElement('select', 'guest', get_string('opentoguests'), $choices);
     $mform->setHelpButton('guest', array('guestaccess', get_string('opentoguests')), true);
     $mform->setDefault('guest', $courseconfig->guest);
     // If we are creating a course, its enrol method isn't yet chosen, BUT the site has a default enrol method which we can use here
     $enrol_object = $CFG;
     if (!empty($course)) {
         $enrol_object = $course;
     }
     // If the print_entry method exists and the course enrol method isn't manual (both set or inherited from site), show cost
     if (method_exists(enrolment_factory::factory($enrol_object->enrol), 'print_entry') && !($enrol_object->enrol == 'manual' || empty($enrol_object->enrol) && $CFG->enrol == 'manual')) {
         $costgroup = array();
         $currencies = get_list_of_currencies();
         $costgroup[] =& MoodleQuickForm::createElement('text', 'cost', '', 'maxlength="6" size="6"');
         $costgroup[] =& MoodleQuickForm::createElement('select', 'currency', '', $currencies);
         $mform->addGroup($costgroup, 'costgrp', get_string('cost'), '&nbsp;', false);
         //defining a rule for a form element within a group :
         $costgrprules = array();
         //set the message to null to tell Moodle to use a default message
         //available for most rules, fetched from language pack (err_{rulename}).
         $costgrprules['cost'][] = array(null, 'numeric', null, 'client');
         $mform->addGroupRule('costgrp', $costgrprules);
         $mform->setHelpButton('costgrp', array('cost', get_string('cost')), true);
         $mform->setDefault('cost', '');
         $mform->setDefault('currency', empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('language'));
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_list_of_languages();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     $mform->setDefault('lang', $courseconfig->lang);
     //--------------------------------------------------------------------------------
     require_once $CFG->libdir . '/completionlib.php';
     if (completion_info::is_enabled_for_site()) {
         $mform->addElement('header', '', get_string('progress', 'completion'));
         $mform->addElement('select', 'enablecompletion', get_string('completion', 'completion'), array(0 => get_string('completiondisabled', 'completion'), 1 => get_string('completionenabled', 'completion')));
         $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
     } else {
         $mform->addElement('hidden', 'enablecompletion');
         $mform->setDefault('enablecompletion', 0);
     }
     //--------------------------------------------------------------------------------
     if (has_capability('moodle/site:config', $systemcontext) && (!empty($course->requested) && $CFG->restrictmodulesfor == 'requested' || $CFG->restrictmodulesfor == 'all')) {
         $mform->addElement('header', '', get_string('restrictmodules'));
         $options = array();
         $options['0'] = get_string('no');
         $options['1'] = get_string('yes');
         $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
         $mods = array(0 => get_string('allownone'));
         $mods += $DB->get_records_menu('modules', array(), 'name', 'id, name');
         $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple' => 'multiple', 'size' => '10'));
         $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
     } else {
         $mform->addElement('hidden', 'restrictmodules', null);
     }
     if ($CFG->restrictmodulesfor == 'all') {
         $mform->setDefault('allowedmods', explode(',', $CFG->defaultallowedmodules));
         if (!empty($CFG->restrictbydefault)) {
             $mform->setDefault('restrictmodules', 1);
         }
     }
     $mform->setType('restrictmodules', PARAM_INT);
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->setHelpButton('rolerenaming', array('rolerenaming', get_string('rolerenaming')), true);
     if ($roles = get_all_roles()) {
         if ($coursecontext) {
             $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW);
         }
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->name));
             if (isset($role->localname)) {
                 $mform->setDefault('role_' . $role->id, $role->localname);
             }
             $mform->setType('role_' . $role->id, PARAM_TEXT);
             if (!in_array($role->id, $assignableroles)) {
                 $mform->setAdvanced('role_' . $role->id);
             }
         }
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
 }
function bigbluebuttonbn_get_users($context)
{
    $roles = bigbluebuttonbn_get_db_moodle_roles();
    $users_array = array();
    foreach ($roles as $role) {
        $users = get_role_users($role->id, $context);
        foreach ($users as $user) {
            array_push($users_array, array("id" => $user->id, "name" => $user->firstname . ' ' . $user->lastname));
        }
    }
    return $users_array;
}
}
foreach ($completion->get_criteria() as $criterion) {
    if (!in_array($criterion->criteriatype, array(COMPLETION_CRITERIA_TYPE_COURSE, COMPLETION_CRITERIA_TYPE_ACTIVITY))) {
        $criteria[] = $criterion;
    }
}
// Can logged in user mark users as complete?
// (if the logged in user has a role defined in the role criteria)
$allow_marking = false;
$allow_marking_criteria = null;
if (!$csv) {
    // Get role criteria
    $rcriteria = $completion->get_criteria(COMPLETION_CRITERIA_TYPE_ROLE);
    if (!empty($rcriteria)) {
        foreach ($rcriteria as $rcriterion) {
            $users = get_role_users($rcriterion->role, $context, true);
            // If logged in user has this role, allow marking complete
            if ($users && in_array($USER->id, array_keys($users))) {
                $allow_marking = true;
                $allow_marking_criteria = $rcriterion->id;
                break;
            }
        }
    }
}
/**
 * Setup page header
 */
if ($csv) {
    header('Content-Disposition: attachment; filename=progress.' . preg_replace('/[^a-z0-9-]/', '_', strtolower($course->shortname)) . '.csv');
    // Unicode byte-order mark for Excel
Пример #14
0
<?php

$role = $DB->get_record('role', array('shortname' => 'student'));
$table = 'jcode_files';
$context = context_course::instance($course->id);
$students = get_role_users($role->id, $context);
$save = optional_param('savequickgrades', '', PARAM_TEXT);
require_once $CFG->libdir . '/gradelib.php';
if (!empty($save)) {
    foreach ($_POST as $name => $value) {
        if (strstr($name, 'quickgrade_') && !strstr($name, 'comments_')) {
            $name = str_replace('quickgrade_', '', $name);
            $nota = new stdClass();
            $nota->grade = $value;
            $grading_info = grade_get_grades($course->id, 'mod', 'jcode', $jcode->id, 0);
            grade_update_outcomes('mod/jcode', $course->id, 'mod', 'jcode', $jcode->id, $name, array('0' => $value));
            if (is_numeric($nota->grade)) {
                $feedback = $_POST['quickgrade_comments_' . $name];
                $nota->feedback = $feedback;
                if ($n = $DB->get_record($table, array('jcode_id' => $jcode->id, 'user_id' => $name))) {
                    $nota->id = $n->id;
                    $DB->update_record($table, $nota);
                } else {
                    $DB->insert($table, $nota);
                }
            }
        }
    }
}
$t = new html_table();
jcode_add_table_row_cells($t, array('Aluno', 'Nota', 'Feedback', 'Data de Entrega', 'Arquivo', 'Resultado'));
Пример #15
0
function tao_message_get_recipients_by_target($target, $course, $user = null)
{
    $user = tao_user_parameter($user);
    $context = get_context_instance(CONTEXT_COURSE, $course->id);
    if (!empty($target->recipientrole) || !empty($target->recipientroles)) {
        if (!empty($target->recipientcontext)) {
            $context = get_context_instance_by_id($target->recipientcontext);
        }
        if (!empty($target->recipientrole)) {
            $roleid = get_field('role', 'id', 'shortname', $target->recipientrole);
        } else {
            $rolesql = " IN ( '" . implode("','", $target->recipientroles) . "' ) ";
            $roleid = array_keys(get_records_select('role', 'shortname ' . $rolesql, '', 'id, id'));
        }
        return get_role_users($roleid, $context);
    } else {
        if (is_array($target->recipientfunction)) {
            // recipientfunction
            $function = $target->recipientfunction['users'];
            $users = $function($user, $course);
            if (empty($target->recipienttransform)) {
                return $users;
            }
            switch ($target->recipienttransform) {
                case 'nested':
                    // these are the grandchild ones
                    $newu = array();
                    foreach ($users as $key => $children) {
                        $newu = array_merge($newu, $children);
                    }
                    return $newu;
            }
        }
    }
}
Пример #16
0
        } else {
            $pageurl = new moodle_url('/badges/award.php', array('id' => $badgeid));
            $issuerrole = new stdClass();
            $issuerrole->roleid = $role;
            $roleselect = get_string('selectaward', 'badges') . $OUTPUT->single_select(new moodle_url($pageurl), 'role', $select, $role, null);
        }
    } else {
        echo $OUTPUT->header();
        $return = html_writer::link(new moodle_url('recipients.php', array('id' => $badge->id)), $strrecipients);
        echo $OUTPUT->notification(get_string('notacceptedrole', 'badges', $return));
        echo $OUTPUT->footer();
        die;
    }
} else {
    // User has to be an admin or the one with the required role.
    $users = get_role_users($acceptedroles[0], $context, true, 'u.id', 'u.id ASC');
    $usersids = array_keys($users);
    if (!$isadmin && !in_array($USER->id, $usersids)) {
        echo $OUTPUT->header();
        $return = html_writer::link(new moodle_url('recipients.php', array('id' => $badge->id)), $strrecipients);
        echo $OUTPUT->notification(get_string('notacceptedrole', 'badges', $return));
        echo $OUTPUT->footer();
        die;
    } else {
        $issuerrole = new stdClass();
        $issuerrole->roleid = $acceptedroles[0];
    }
}
$options = array('badgeid' => $badge->id, 'context' => $context, 'issuerid' => $USER->id, 'issuerrole' => $issuerrole->roleid);
$existingselector = new badge_existing_users_selector('existingrecipients', $options);
$recipientselector = new badge_potential_users_selector('potentialrecipients', $options);
Пример #17
0
 /**
  * Init this page
  *
  * @param bool $selfitemisempty True if we have not selected a user.
  */
 public function init($selfitemisempty = false)
 {
     $roleids = explode(',', get_config('moodle', 'gradebookroles'));
     $this->items = array();
     foreach ($roleids as $roleid) {
         // Keeping the first user appearance.
         $this->items = $this->items + get_role_users($roleid, $this->context, false, '', 'u.lastname, u.firstname', null, $this->groupid);
     }
     $this->totalitemcount = count_role_users($roleids, $this->context);
     if ($selfitemisempty) {
         return;
     }
     $params = array('id' => $this->itemid, 'courseid' => $this->courseid);
     $this->item = grade_item::fetch($params);
     if (!self::filter($this->item)) {
         $this->items = array();
         $this->set_init_error(get_string('gradeitemcannotbeoverridden', 'gradereport_singleview'));
     }
     $this->requiresextra = !$this->item->is_manual_item();
     $this->setup_structure();
     $this->set_definition($this->original_definition());
     $this->set_headers($this->original_headers());
 }
Пример #18
0
 /**
  * Gets list of users in a course whose progress is tracked for display on the
  * progress report.
  *
  * @global object
  * @global object
  * @uses CONTEXT_COURSE
  * @param bool $sortfirstname True to sort with firstname
  * @param int $groupid Optionally restrict to groupid
  * @return array Array of user objects containing id, firstname, lastname (empty if none)
  */
 function internal_get_tracked_users($sortfirstname, $groupid = 0)
 {
     global $CFG, $DB;
     if (!empty($CFG->progresstrackedroles)) {
         $roles = explode(', ', $CFG->progresstrackedroles);
     } else {
         // This causes it to default to everyone (if there is no student role)
         $roles = array();
     }
     $users = get_role_users($roles, get_context_instance(CONTEXT_COURSE, $this->course->id), true, 'u.id, u.firstname, u.lastname, u.idnumber', $sortfirstname ? 'u.firstname ASC' : 'u.lastname ASC', true, $groupid);
     $users = $users ? $users : array();
     // In case it returns false
     return $users;
 }
Пример #19
0
 /**
  * Send welcome email to specified user
  *
  * @param object $instance
  * @param object $user user record
  * @return void
  */
 protected function email_welcome_message($instance, $user)
 {
     global $CFG, $DB;
     $course = $DB->get_record('course', array('id' => $instance->courseid), '*', MUST_EXIST);
     $a = new stdClass();
     $a->coursename = format_string($course->fullname);
     $a->profileurl = "{$CFG->wwwroot}/user/view.php?id={$user->id}&course={$course->id}";
     if (trim($instance->customtext1) !== '') {
         $message = $instance->customtext1;
         $message = str_replace('{$a->coursename}', $a->coursename, $message);
         $message = str_replace('{$a->profileurl}', $a->profileurl, $message);
     } else {
         $message = get_string('welcometocoursetext', 'enrol_self', $a);
     }
     $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname));
     $context = get_context_instance(CONTEXT_COURSE, $course->id);
     $rusers = array();
     if (!empty($CFG->coursecontact)) {
         $croles = explode(',', $CFG->coursecontact);
         $rusers = get_role_users($croles, $context, true, '', 'r.sortorder ASC, u.lastname ASC');
     }
     if ($rusers) {
         $contact = reset($rusers);
     } else {
         $contact = get_admin();
     }
     //directly emailing welcome message rather than using messaging
     email_to_user($user, $contact, $subject, $message);
 }
Пример #20
0
 /**
  * Test getting of role users.
  * @return void
  */
 public function test_get_role_users()
 {
     global $DB;
     $this->resetAfterTest();
     $systemcontext = context_system::instance();
     $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'), '*', MUST_EXIST);
     $course = $this->getDataGenerator()->create_course();
     $coursecontext = context_course::instance($course->id);
     $otherid = create_role('Other role', 'other', 'Some other role', '');
     $teacherrename = (object) array('roleid' => $teacherrole->id, 'name' => 'Učitel', 'contextid' => $coursecontext->id);
     $DB->insert_record('role_names', $teacherrename);
     $otherrename = (object) array('roleid' => $otherid, 'name' => 'Ostatní', 'contextid' => $coursecontext->id);
     $DB->insert_record('role_names', $otherrename);
     $user1 = $this->getDataGenerator()->create_user();
     role_assign($teacherrole->id, $user1->id, $coursecontext->id);
     $user2 = $this->getDataGenerator()->create_user();
     role_assign($teacherrole->id, $user2->id, $systemcontext->id);
     $users = get_role_users($teacherrole->id, $coursecontext);
     $this->assertCount(1, $users);
     $user = reset($users);
     $userid = key($users);
     $this->assertEquals($userid, $user->id);
     $this->assertEquals($teacherrole->id, $user->roleid);
     $this->assertEquals($teacherrole->name, $user->rolename);
     $this->assertEquals($teacherrole->shortname, $user->roleshortname);
     $this->assertEquals($teacherrename->name, $user->rolecoursealias);
     $users = get_role_users($teacherrole->id, $coursecontext, true);
     $this->assertCount(2, $users);
     $users = get_role_users($teacherrole->id, $coursecontext, false, 'u.id, u.email, u.idnumber', 'u.idnumber', null, 1, 0, 10, 'u.deleted = 0');
 }
Пример #21
0
/**
 * Print a description of a course, suitable for browsing in a list.
 *
 * @param object $course the course object.
 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
 */
function print_course($course, $highlightterms = '')
{
    global $CFG, $USER, $DB, $OUTPUT;
    $context = get_context_instance(CONTEXT_COURSE, $course->id);
    // Rewrite file URLs so that they are correct
    $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
    echo html_writer::start_tag('div', array('class' => 'coursebox clearfix'));
    echo html_writer::start_tag('div', array('class' => 'info'));
    echo html_writer::start_tag('h3', array('class' => 'name'));
    $linkhref = new moodle_url('/course/view.php', array('id' => $course->id));
    $coursename = get_course_display_name_for_list($course);
    $linktext = highlight($highlightterms, format_string($coursename));
    $linkparams = array('title' => get_string('entercourse'));
    if (empty($course->visible)) {
        $linkparams['class'] = 'dimmed';
    }
    echo html_writer::link($linkhref, $linktext, $linkparams);
    echo html_writer::end_tag('h3');
    /// first find all roles that are supposed to be displayed
    if (!empty($CFG->coursecontact)) {
        $managerroles = explode(',', $CFG->coursecontact);
        $namesarray = array();
        $rusers = array();
        if (!isset($course->managers)) {
            $rusers = get_role_users($managerroles, $context, true, 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
                 r.name AS rolename, r.sortorder, r.id AS roleid', 'r.sortorder ASC, u.lastname ASC');
        } else {
            //  use the managers array if we have it for perf reasosn
            //  populate the datastructure like output of get_role_users();
            foreach ($course->managers as $manager) {
                $u = new stdClass();
                $u = $manager->user;
                $u->roleid = $manager->roleid;
                $u->rolename = $manager->rolename;
                $rusers[] = $u;
            }
        }
        /// Rename some of the role names if needed
        if (isset($context)) {
            $aliasnames = $DB->get_records('role_names', array('contextid' => $context->id), '', 'roleid,contextid,name');
        }
        $namesarray = array();
        $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
        foreach ($rusers as $ra) {
            if (isset($namesarray[$ra->id])) {
                //  only display a user once with the higest sortorder role
                continue;
            }
            if (isset($aliasnames[$ra->roleid])) {
                $ra->rolename = $aliasnames[$ra->roleid]->name;
            }
            $fullname = fullname($ra, $canviewfullnames);
            $namesarray[$ra->id] = format_string($ra->rolename) . ': ' . html_writer::link(new moodle_url('/user/view.php', array('id' => $ra->id, 'course' => SITEID)), $fullname);
        }
        if (!empty($namesarray)) {
            echo html_writer::start_tag('ul', array('class' => 'teachers'));
            foreach ($namesarray as $name) {
                echo html_writer::tag('li', $name);
            }
            echo html_writer::end_tag('ul');
        }
    }
    echo html_writer::end_tag('div');
    // End of info div
    echo html_writer::start_tag('div', array('class' => 'summary'));
    $options = new stdClass();
    $options->noclean = true;
    $options->para = false;
    $options->overflowdiv = true;
    if (!isset($course->summaryformat)) {
        $course->summaryformat = FORMAT_MOODLE;
    }
    echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
    if ($icons = enrol_get_course_info_icons($course)) {
        echo html_writer::start_tag('div', array('class' => 'enrolmenticons'));
        foreach ($icons as $icon) {
            echo $OUTPUT->render($icon);
        }
        echo html_writer::end_tag('div');
        // End of enrolmenticons div
    }
    echo html_writer::end_tag('div');
    // End of summary div
    echo html_writer::end_tag('div');
    // End of coursebox div
}
Пример #22
0
/**
 * Fetches users based on a supplied course and group.
 *
 * @param mixed $course the course to search for users in
 * @param mixed $group the group to search for users in
 * @return array of users
 * @uses $CFG
 */
function report_ncccscensus_get_users($course, $group = null)
{
    global $CFG;
    require_once $CFG->libdir . '/accesslib.php';
    $excludegroupmembers = false;
    if ($group === REPORT_NCCCSCENSUS_EXCLUDE_GROUP_MEMBERS) {
        $excludegroupmembers = true;
        $group = null;
        // Set group to null to retrieve all users, then filter out group members.
    }
    /* The use of $CFG->gradebookroles and get_role_users() was suggested here:     */
    /* https://tracker.remote-learner.net/browse/NCCCSDEV-19?focusedCommentId=94023 */
    $roles = explode(',', $CFG->gradebookroles);
    $context = context_course::instance($course);
    $users = array();
    foreach ($roles as $role) {
        $roleusers = get_role_users($role, $context, false, 'u.id, u.firstname, u.lastname', null, true, $group);
        foreach ($roleusers as $roleuser) {
            $users[] = $roleuser->id;
        }
    }
    $users = array_unique($users);
    // Filter out group members if any.
    if ($excludegroupmembers) {
        $groupusers = array();
        $groupdata = groups_get_course_data($course);
        foreach ($groupdata->groups as $groupobject) {
            foreach ($roles as $role) {
                $roleusers = get_role_users($role, $context, false, 'u.id', null, true, $groupobject->id);
                foreach ($roleusers as $roleuser) {
                    $groupusers[] = $roleuser->id;
                }
            }
        }
        $groupusers = array_unique($groupusers);
        $users = array_diff($users, $groupusers);
    }
    return $users;
}
Пример #23
0
/**
 * Returns subsytems admins, along with regular Moodle admins
 */
function get_early_warning_admins($subsystem)
{
    global $CFG;
    $roleid = $CFG->{'block_student_gradeviewer_' . $subsystem . '_admin'};
    $context = get_context_instance(CONTEXT_SYSTEM);
    $admins = get_role_users($roleid, $context);
    return get_admins() + $admins;
}
Пример #24
0
echo $OUTPUT->heading('<a href="view.php?id=' . $course->id . '">' . format_string($course->fullname) . '</a><br />(' . format_string($course->shortname, true, array('context' => $context)) . ')');
// print enrol info
if ($texts = enrol_get_course_description_texts($course)) {
    echo $OUTPUT->box_start('generalbox icons');
    echo implode($texts);
    echo $OUTPUT->box_end();
}
echo $OUTPUT->box_start('generalbox info');
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
echo format_text($course->summary, $course->summaryformat, array('overflowdiv' => true), $course->id);
if (!empty($CFG->coursecontact)) {
    $coursecontactroles = explode(',', $CFG->coursecontact);
    foreach ($coursecontactroles as $roleid) {
        $role = $DB->get_record('role', array('id' => $roleid));
        $roleid = (int) $roleid;
        if ($users = get_role_users($roleid, $context, true)) {
            foreach ($users as $teacher) {
                $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
                $namesarray[] = format_string(role_get_name($role, $context)) . ': <a href="' . $CFG->wwwroot . '/user/view.php?id=' . $teacher->id . '&amp;course=' . SITEID . '">' . $fullname . '</a>';
            }
        }
    }
    if (!empty($namesarray)) {
        echo "<ul class=\"teachers\">\n<li>";
        echo implode('</li><li>', $namesarray);
        echo "</li></ul>";
    }
}
// TODO: print some enrol icons
echo $OUTPUT->box_end();
echo "<br />";
Пример #25
0
 /**
  * Prints the message telling you were to get the enrolment key
  * appropriate for the prevailing circumstances
  * A bit clunky because I didn't want to change the standard strings
  */
 function print_enrolmentkeyfrom($course)
 {
     global $CFG;
     global $USER;
     $context = get_context_instance(CONTEXT_SYSTEM);
     $guest = has_capability('moodle/legacy:guest', $context, $USER->id, false);
     // if a keyholder role is defined we list teachers in that role (if any exist)
     $contactslisted = false;
     $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
     if (!empty($CFG->enrol_manual_keyholderrole)) {
         if ($contacts = get_role_users($CFG->enrol_manual_keyholderrole, get_context_instance(CONTEXT_COURSE, $course->id), true, '', 'u.lastname ASC', $canseehidden)) {
             // guest user has a slightly different message
             if ($guest) {
                 print_string('enrolmentkeyfromguest', '', ':<br />');
             } else {
                 print_string('enrolmentkeyfrom', '', ':<br />');
             }
             foreach ($contacts as $contact) {
                 $contactname = "<a href=\"../user/view.php?id={$contact->id}&course=" . SITEID . "\">" . fullname($contact) . "</a>.";
                 echo "{$contactname}<br />";
             }
             $contactslisted = true;
         }
     }
     // if no keyholder role is defined OR nobody is in that role we do this the 'old' way
     // (show the first person with update rights)
     if (!$contactslisted) {
         if ($teachers = get_users_by_capability(get_context_instance(CONTEXT_COURSE, $course->id), 'moodle/course:update', 'u.*', 'u.id ASC', 0, 1, '', '', false, true)) {
             $teacher = array_shift($teachers);
         }
         if (!empty($teacher)) {
             $teachername = "<a href=\"../user/view.php?id={$teacher->id}&course=" . SITEID . "\">" . fullname($teacher) . "</a>.";
         } else {
             $teachername = strtolower(get_string('defaultcourseteacher'));
             //get_string('yourteacher', '', $course->teacher);
         }
         // guest user has a slightly different message
         if ($guest) {
             print_string('enrolmentkeyfromguest', '', $teachername);
         } else {
             print_string('enrolmentkeyfrom', '', $teachername);
         }
     }
 }
 /**
  * Creates csv file and add it to the threadgroup for use case.
  *
  * @Given /^I login as any "([^"]*)" enrolled in course "([^"]*)"$/
  */
 public function i_login_as_any_enrolled_in_course($rolearchtype, $courseshortname)
 {
     global $DB, $CFG;
     if (!($id = $DB->get_field('course', 'id', array('shortname' => $courseshortname)))) {
         util::performance_exception('The specified course with shortname "' . $courseshortname . '" does not exist');
     }
     $coursecontext = \context_course::instance($id);
     if ($roles = get_archetype_roles($rolearchtype)) {
         $roles = array_keys($roles);
     }
     $roleid = $roles[0];
     $users = get_role_users($roleid, $coursecontext, false, 'u.id,u.username', 'u.id ASC');
     if (!$users) {
         util::performance_exception("Course without users with role: " . $rolearchtype);
     }
     $data = "";
     foreach ($users as $user) {
         $data .= $user->username . "," . $user->username . "," . $user->id . PHP_EOL;
     }
     $testplanfilename = $rolearchtype . '_' . behat_hooks::$featurefile . '.csv';
     $csvfile = util::get_final_testplan_path() . DIRECTORY_SEPARATOR . $testplanfilename;
     $testplanfilepath = "";
     if (isset($CFG->testplanfiles_dataroot)) {
         $testplanfilepath = $CFG->testplanfiles_dataroot . DIRECTORY_SEPARATOR;
     }
     file_put_contents($csvfile, $data);
     testplan_writer::create_csv_data($testplanfilepath, $testplanfilename, $rolearchtype);
     $firstuser = array_shift($users);
     return new Given('I log in as "' . $firstuser->username . '"');
 }
Пример #27
0
 // sync metacourse enrolments if needed
 if ($inmeta) {
     sync_metacourse($course);
 }
 // Get the names of role holders for roles with between 1 and MAX_USERS_TO_LIST_PER_ROLE users,
 // and so determine whether to show the extra column.
 $rolehodlercount = array();
 $rolehodlernames = array();
 $strmorethanten = get_string('morethan', 'role', MAX_USERS_TO_LIST_PER_ROLE);
 $showroleholders = false;
 foreach ($assignableroles as $roleid => $rolename) {
     $countusers = count_role_users($roleid, $context);
     $rolehodlercount[$roleid] = $countusers;
     $roleusers = '';
     if (0 < $countusers && $countusers <= MAX_USERS_TO_LIST_PER_ROLE) {
         $roleusers = get_role_users($roleid, $context, false, 'u.id, u.lastname, u.firstname');
         if (!empty($roleusers)) {
             $strroleusers = array();
             foreach ($roleusers as $user) {
                 $strroleusers[] = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '" >' . fullname($user) . '</a>';
             }
             $rolehodlernames[$roleid] = implode('<br />', $strroleusers);
             $showroleholders = true;
         }
     } else {
         if ($countusers > MAX_USERS_TO_LIST_PER_ROLE) {
             $rolehodlernames[$roleid] = '<a href="' . $baseurl . '&amp;roleid=' . $roleid . '">' . $strmorethanten . '</a>';
         } else {
             $rolehodlernames[$roleid] = '';
         }
     }
Пример #28
0
/**
 * This function will empty a course of user data.
 * It will retain the activities and the structure of the course.
 * @param object $data an object containing all the settings including courseid (without magic quotes)
 * @return array status array of array component, item, error
 */
function reset_course_userdata($data)
{
    global $CFG, $USER;
    require_once $CFG->libdir . '/gradelib.php';
    require_once $CFG->dirroot . '/group/lib.php';
    $data->courseid = $data->id;
    $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
    // calculate the time shift of dates
    if (!empty($data->reset_start_date)) {
        // time part of course startdate should be zero
        $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
    } else {
        $data->timeshift = 0;
    }
    // result array: component, item, error
    $status = array();
    // start the resetting
    $componentstr = get_string('general');
    // move the course start time
    if (!empty($data->reset_start_date) and $data->timeshift) {
        // change course start data
        set_field('course', 'startdate', $data->reset_start_date, 'id', $data->courseid);
        // update all course and group events - do not move activity events
        $updatesql = "UPDATE {$CFG->prefix}event\n                         SET timestart = timestart + ({$data->timeshift})\n                       WHERE courseid={$data->courseid} AND instance=0";
        execute_sql($updatesql, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
    }
    if (!empty($data->reset_logs)) {
        delete_records('log', 'course', $data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletelogs'), 'error' => false);
    }
    if (!empty($data->reset_events)) {
        delete_records('event', 'courseid', $data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
    }
    if (!empty($data->reset_notes)) {
        require_once $CFG->dirroot . '/notes/lib.php';
        note_delete_all($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
    }
    $componentstr = get_string('roles');
    if (!empty($data->reset_roles_overrides)) {
        $children = get_child_contexts($context);
        foreach ($children as $child) {
            delete_records('role_capabilities', 'contextid', $child->id);
        }
        delete_records('role_capabilities', 'contextid', $context->id);
        //force refresh for logged in users
        mark_context_dirty($context->path);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
    }
    if (!empty($data->reset_roles_local)) {
        $children = get_child_contexts($context);
        foreach ($children as $child) {
            role_unassign(0, 0, 0, $child->id);
        }
        //force refresh for logged in users
        mark_context_dirty($context->path);
        $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
    }
    // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
    $data->unenrolled = array();
    if (!empty($data->reset_roles)) {
        foreach ($data->reset_roles as $roleid) {
            if ($users = get_role_users($roleid, $context, false, 'u.id', 'u.id ASC')) {
                foreach ($users as $user) {
                    role_unassign($roleid, $user->id, 0, $context->id);
                    if (!has_capability('moodle/course:view', $context, $user->id)) {
                        $data->unenrolled[$user->id] = $user->id;
                    }
                }
            }
        }
    }
    if (!empty($data->unenrolled)) {
        $status[] = array('component' => $componentstr, 'item' => get_string('unenrol') . ' (' . count($data->unenrolled) . ')', 'error' => false);
    }
    $componentstr = get_string('groups');
    // remove all group members
    if (!empty($data->reset_groups_members)) {
        groups_delete_group_members($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
    }
    // remove all groups
    if (!empty($data->reset_groups_remove)) {
        groups_delete_groups($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
    }
    // remove all grouping members
    if (!empty($data->reset_groupings_members)) {
        groups_delete_groupings_groups($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
    }
    // remove all groupings
    if (!empty($data->reset_groupings_remove)) {
        groups_delete_groupings($data->courseid, false);
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
    }
    // Look in every instance of every module for data to delete
    $unsupported_mods = array();
    if ($allmods = get_records('modules')) {
        foreach ($allmods as $mod) {
            $modname = $mod->name;
            if (!count_records($modname, 'course', $data->courseid)) {
                continue;
                // skip mods with no instances
            }
            $modfile = $CFG->dirroot . '/mod/' . $modname . '/lib.php';
            $moddeleteuserdata = $modname . '_reset_userdata';
            // Function to delete user data
            if (file_exists($modfile)) {
                include_once $modfile;
                if (function_exists($moddeleteuserdata)) {
                    $modstatus = $moddeleteuserdata($data);
                    if (is_array($modstatus)) {
                        $status = array_merge($status, $modstatus);
                    } else {
                        debugging('Module ' . $modname . ' returned incorrect staus - must be an array!');
                    }
                } else {
                    $unsupported_mods[] = $mod;
                }
            } else {
                debugging('Missing lib.php in ' . $modname . ' module!');
            }
        }
    }
    // mention unsupported mods
    if (!empty($unsupported_mods)) {
        foreach ($unsupported_mods as $mod) {
            $status[] = array('component' => get_string('modulenameplural', $mod->name), 'item' => '', 'error' => get_string('resetnotimplemented'));
        }
    }
    $componentstr = get_string('gradebook', 'grades');
    // reset gradebook
    if (!empty($data->reset_gradebook_items)) {
        remove_course_grades($data->courseid, false);
        grade_grab_course_grades($data->courseid);
        grade_regrade_final_grades($data->courseid);
        $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
    } else {
        if (!empty($data->reset_gradebook_grades)) {
            grade_course_reset($data->courseid);
            $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
        }
    }
    return $status;
}
Пример #29
0
    }
    if ($course->password) {
        $strrequireskey = get_string('requireskey');
        echo "<div><img alt=\"\" class=\"icon key\" src=\"{$CFG->pixpath}/i/key.gif\" />&nbsp;{$strrequireskey}</div>";
    }
    print_box_end();
}
print_box_start('generalbox info');
echo filter_text(text_to_html($course->summary), $course->id);
if ($managerroles = get_config('', 'coursemanager')) {
    $coursemanagerroles = split(',', $managerroles);
    foreach ($coursemanagerroles as $roleid) {
        $role = get_record('role', 'id', $roleid);
        $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
        $roleid = (int) $roleid;
        if ($users = get_role_users($roleid, $context, true, '', 'u.lastname ASC', $canseehidden)) {
            foreach ($users as $teacher) {
                $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
                $namesarray[] = format_string($role->name) . ': <a href="' . $CFG->wwwroot . '/user/view.php?id=' . $teacher->id . '&amp;course=' . SITEID . '">' . $fullname . '</a>';
            }
        }
    }
    if (!empty($namesarray)) {
        echo "<ul class=\"teachers\">\n<li>";
        echo implode('</li><li>', $namesarray);
        echo "</li></ul>";
    }
}
require_once "{$CFG->dirroot}/enrol/enrol.class.php";
$enrol = enrolment_factory::factory($course->enrol);
echo $enrol->get_access_icons($course);
Пример #30
0
 /**
  * Test getting of role users.
  */
 public function test_get_role_users()
 {
     global $DB;
     $this->resetAfterTest();
     $systemcontext = context_system::instance();
     $studentrole = $DB->get_record('role', array('shortname' => 'student'), '*', MUST_EXIST);
     $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'), '*', MUST_EXIST);
     $course = $this->getDataGenerator()->create_course();
     $coursecontext = context_course::instance($course->id);
     $otherid = create_role('Other role', 'other', 'Some other role', '');
     $teacherrename = (object) array('roleid' => $teacherrole->id, 'name' => 'Učitel', 'contextid' => $coursecontext->id);
     $DB->insert_record('role_names', $teacherrename);
     $otherrename = (object) array('roleid' => $otherid, 'name' => 'Ostatní', 'contextid' => $coursecontext->id);
     $DB->insert_record('role_names', $otherrename);
     $user1 = $this->getDataGenerator()->create_user(array('firstname' => 'John', 'lastname' => 'Smith'));
     role_assign($teacherrole->id, $user1->id, $coursecontext->id);
     $user2 = $this->getDataGenerator()->create_user(array('firstname' => 'Jan', 'lastname' => 'Kovar'));
     role_assign($teacherrole->id, $user2->id, $systemcontext->id);
     $user3 = $this->getDataGenerator()->create_user();
     $this->getDataGenerator()->enrol_user($user3->id, $course->id, $teacherrole->id);
     $user4 = $this->getDataGenerator()->create_user();
     $this->getDataGenerator()->enrol_user($user4->id, $course->id, $studentrole->id);
     $group = $this->getDataGenerator()->create_group(array('courseid' => $course->id));
     groups_add_member($group, $user3);
     $users = get_role_users($teacherrole->id, $coursecontext);
     $this->assertCount(2, $users);
     $this->assertArrayHasKey($user1->id, $users);
     $this->assertEquals($users[$user1->id]->id, $user1->id);
     $this->assertEquals($users[$user1->id]->roleid, $teacherrole->id);
     $this->assertEquals($users[$user1->id]->rolename, $teacherrole->name);
     $this->assertEquals($users[$user1->id]->roleshortname, $teacherrole->shortname);
     $this->assertEquals($users[$user1->id]->rolecoursealias, $teacherrename->name);
     $this->assertArrayHasKey($user3->id, $users);
     $this->assertEquals($users[$user3->id]->id, $user3->id);
     $this->assertEquals($users[$user3->id]->roleid, $teacherrole->id);
     $this->assertEquals($users[$user3->id]->rolename, $teacherrole->name);
     $this->assertEquals($users[$user3->id]->roleshortname, $teacherrole->shortname);
     $this->assertEquals($users[$user3->id]->rolecoursealias, $teacherrename->name);
     $users = get_role_users($teacherrole->id, $coursecontext, true);
     $this->assertCount(3, $users);
     $users = get_role_users($teacherrole->id, $coursecontext, true, '', null, null, '', 2, 1);
     $this->assertCount(1, $users);
     $users = get_role_users($teacherrole->id, $coursecontext, false, 'u.id, u.email, u.idnumber', 'u.idnumber');
     $this->assertCount(2, $users);
     $this->assertArrayHasKey($user1->id, $users);
     $this->assertArrayHasKey($user3->id, $users);
     $users = get_role_users($teacherrole->id, $coursecontext, false, 'u.id, u.email, u.idnumber', 'u.idnumber', null, $group->id);
     $this->assertCount(1, $users);
     $this->assertArrayHasKey($user3->id, $users);
     $users = get_role_users($teacherrole->id, $coursecontext, true, 'u.id, u.email, u.idnumber, u.firstname', 'u.idnumber', null, '', '', '', 'u.firstname = :xfirstname', array('xfirstname' => 'John'));
     $this->assertCount(1, $users);
     $this->assertArrayHasKey($user1->id, $users);
 }