public function test_build() { $fm = mr_fixture_manager::instance(); $userid = $fm->get('user')->get('id'); $roleid = $fm->get('role')->get('id'); $context = context_course::instance($fm->get('course')->get('id')); $this->assertFalse(user_has_role_assignment($userid, $roleid, $context->id)); $this->assertFalse(is_enrolled($context, $fm->get('user')->get_results())); $enrollment = new mr_fixture_enrollment($fm->get('course'), $fm->get('user'), enrol_get_plugin('manual'), $fm->get('role')); $enrollment->build(); $this->assertTrue(user_has_role_assignment($userid, $roleid, $context->id)); $this->assertTrue(is_enrolled($context, $fm->get('user')->get_results())); }
public function test_destroy() { $fm = mr_fixture_manager::instance(); $userid = $fm->get('user')->get('id'); $roleid = $fm->get('role')->get('id'); $contextid = context_course::instance($fm->get('course')->get('id'))->id; $this->assertFalse(user_has_role_assignment($userid, $roleid, $contextid)); $ra = new mr_fixture_role_assignment($fm->get('role'), $fm->get('user'), $fm->get('course')); $ra->build(); $this->assertTrue(user_has_role_assignment($userid, $roleid, $contextid)); $ra->destroy(); $this->assertFalse(user_has_role_assignment($userid, $roleid, $contextid)); }
function theme_mmcmonkwearmouth_get_user_role($id) { //Requires a setting save to change these in database for news. $roles = ["teacher" => 20, "staff" => 21, "parent" => 22, "student" => 19, "governor" => 23]; $admins = get_admins(); foreach ($admins as $admin) { if ($id == $admin->id) { return "admin"; } } foreach ($roles as $roleTitle => $roleNumber) { if (user_has_role_assignment($id, $roleNumber)) { return $roleTitle; } } }
/** * Create EQUELLA single sign on token for current user * * @return string */ function equella_getssotoken($course = null) { global $USER, $CFG, $COURSE; if (empty($course)) { $course = $COURSE; } $context_sys = context_system::instance(); $context_cc = null; if (!empty($course->category) && is_int($course->category)) { $context_cc = context_coursecat::instance($course->category); } $context_c = context_course::instance($course->id); // roles are ordered by shortname $editingroles = get_all_editing_roles(); foreach ($editingroles as $role) { $hassystemrole = false; if (!empty($context_sys)) { $hassystemrole = user_has_role_assignment($USER->id, $role->id, $context_sys->id); } $hascategoryrole = false; if (!empty($context_cc)) { $hascategoryrole = user_has_role_assignment($USER->id, $role->id, $context_cc->id); } $hascourserole = false; if (!empty($context_c)) { $hascourserole = user_has_role_assignment($USER->id, $role->id, $context_c->id); } if ($hassystemrole || $hascategoryrole || $hascourserole) { // see if the user has a role that is linked to an equella role $shareid = $CFG->{"equella_{$role->shortname}_shareid"}; if (!empty($shareid)) { return equella_getssotoken_raw($USER->username, $shareid, $CFG->{"equella_{$role->shortname}_sharedsecret"}); } } } // no roles found, use the default shareid and secret $shareid = $CFG->equella_shareid; if (!empty($shareid)) { return equella_getssotoken_raw($USER->username, $shareid, $CFG->equella_sharedsecret); } }
public function get_content() { global $DB, $USER, $CFG; if ($this->content !== null) { return $this->content; } if (user_has_role_assignment($USER->id, 5)) { $config = get_config('domoscio'); $count = $this->count_tests($config); if (count($count) > 1) { $plural = "s"; } else { $plural = ""; } $this->content = new stdClass(); $this->content->text = '<span class="badge badge-important" style="font-size:18px">' . count($count) . '</span>' . get_string('text2', 'block_domoscio_reminder') . $plural . get_string('text3', 'block_domoscio_reminder'); if (!empty($count)) { $this->content->footer = "<a href=" . $CFG->wwwroot . "/mod/domoscio/index.php>Let's go !</a>"; } } return $this->content; }
/** * Generate equella sso token * * @param string $readwrite * @return string */ private function getssotoken($readwrite = 'read') { global $USER; if (empty($USER->username)) { return false; } if ($readwrite == 'write') { foreach (self::get_all_editing_roles() as $role) { if (user_has_role_assignment($USER->id, $role->id, $this->context->id)) { // See if the user has a role that is linked to an equella role. $shareid = $this->get_option("equella_{$role->shortname}_shareid"); if (!empty($shareid)) { return $this->getssotoken_raw($USER->username, $shareid, $this->get_option("equella_{$role->shortname}_sharedsecret")); } } } } // If we are only reading, use the unadorned shareid and secret. $shareid = $this->get_option('equella_shareid'); if (!empty($shareid)) { return $this->getssotoken_raw($USER->username, $shareid, $this->get_option('equella_sharedsecret')); } }
/** * Verify if the user is a student * * @param int * @param int * @return bool */ function is_student($userid) { return user_has_role_assignment($userid, 5); }
/** * Enrol the user, add him to groups and assign him roles. * * @return bool false if an error occured */ protected function add_to_egr() { global $DB; foreach ($this->rawdata as $field => $value) { if (preg_match('/^sysrole\\d+$/', $field)) { $removing = false; if (!empty($value)) { $sysrolename = $value; // Removing sysrole. if ($sysrolename[0] == '-') { $removing = true; $sysrolename = substr($sysrolename, 1); } // System roles lookup. $sysrolecache = uu_allowed_sysroles_cache(); if (array_key_exists($sysrolename, $sysrolecache)) { $sysroleid = $sysrolecache[$sysrolename]->id; } else { $this->set_status('unknownrole', new lang_string('unknownrole', 'error', s($sysrolename))); continue; } $isassigned = user_has_role_assignment($this->finaldata->id, $sysroleid, SYSCONTEXTID); if ($removing) { if ($isassigned) { role_unassign($sysroleid, $this->finaldata->id, SYSCONTEXTID); } } else { if (!$isassigned) { role_assign($sysroleid, $this->finaldata->id, SYSCONTEXTID); } } } } else { if (preg_match('/^course\\d+$/', $field)) { // Course number. $i = substr($field, 6); $shortname = $value; $course = $DB->get_record('course', array('shortname' => $shortname)); $course->groups = NULL; if (!$course) { $this->set_status('unknowncourse', new lang_string('unknowncourse', 'error', s($shortname))); continue; } $courseid = $course->id; $coursecontext = context_course::instance($courseid); $roles = uu_allowed_roles_cache(); // TODO: manualcache if ($instances = enrol_get_instances($courseid, false)) { foreach ($instances as $instance) { if ($instance->enrol === 'manual') { $coursecache = $instance; break; } } } // Checking if manual enrol is enabled. If it's not, no // enrolment is done. if (enrol_is_enabled('manual')) { $manual = enrol_get_plugin('manual'); } else { $manual = NULL; } if ($courseid == SITEID) { if (!empty($this->rawdata['role' . $i])) { $rolename = $this->rawdata['role' . $i]; if (array_key_exists($rolename, $roles)) { $roleid = $roles[$rolename]->id; } else { $this->set_status('unknownrole', new lang_string('unknownrole', 'error', s($rolename))); continue; } role_assign($roleid, $this->finaldata->id, context_course::instance($courseid)); } } else { if ($manual) { $roleid = false; if (!empty($this->rawdata['role' . $i])) { $rolename = $this->rawdata['role' . $i]; if (array_key_exists($rolename, $roles)) { $roleid = $roles[$rolename]->id; } else { $this->set_status('unknownrole', new lang_string('unknownrole', 'error', s($rolename))); continue; } } else { if (!empty($this->rawdata['type' . $i])) { // If no role, find "old" enrolment type. $addtype = $this->rawdata['type' . $i]; if ($addtype < 1 or $addtype > 3) { $this->set_status('typeerror', new lang_string('typeerror', 'tool_uploadusercli')); continue; } else { $roleid = $this->rawdata['type' . $i]; } } else { // No role specified, use default course role. $roleid = $coursecache->roleid; } } if ($roleid) { // Find duration and/or enrol status. $timeend = 0; $status = NULL; if (isset($this->rawdata['enrolstatus' . $i])) { $enrolstatus = $this->rawdata['enrolstatus' . $i]; if ($enrolstatus == '') { // Do nothing } else { if ($enrolstatus === (string) ENROL_USER_ACTIVE) { $status = ENROL_USER_ACTIVE; } else { if ($enrolstatus === (string) ENROL_USER_SUSPENDED) { $status = ENROL_USER_SUSPENDED; } else { $this->set_status('unknownenrolstatus', new lang_string('unknownenrolstatus', 'tool_uploadusercli')); } } } } if ($this->do === self::DO_UPDATE) { $now = $this->finaldata->timemodified; } else { $now = $this->finaldata->timecreated; } if (!empty($this->rawdata['enrolperiod' . $i])) { // Duration, in seconds. $duration = (int) $this->rawdata['enrolperiod' . $i] * 60 * 60 * 24; if ($duration > 0) { $timeend = $now + $duration; } } else { if ($coursecache->enrolperiod > 0) { $timeend = $now + $coursecache->enrolperiod; } } try { $manual->enrol_user($coursecache, $this->finaldata->id, $roleid, $now, $timeend, $status); } catch (Exception $e) { $this->error('usernotenrollederror', new lang_string('usernotenrollederror', 'tool_uploadusercli')); return false; } } } } // Add to group. if (isset($this->rawdata['group' . $i])) { $groupname = isset($this->rawdata['group' . $i]); } if (!empty($groupname)) { // Enrol into course before adding to group. if (!is_enrolled($coursecontext, $this->finaldata->id)) { $this->error('usernotenrollederror', new lang_string('usernotenrollederror', '', $groupname, 'error')); return false; } $course->groups = array(); $groups = groups_get_all_groups($courseid); if ($groups) { foreach ($groups as $gid => $group) { $course->groups[$gid] = new stdClass(); $course->groups[$gid]->id = $gid; $course->groups[$gid]->name = $group->name; if (!is_numeric($group->name)) { $course->groups[$group->name] = new stdClass(); $course->groups[$group->name]->id = $gid; $course->groups[$group->name]->name = $group->name; } } } // Does the group exist? if (!array_key_exists($groupname, $course->groups)) { // Create it. $newgroupdata = new stdClass(); $newgroupdata->name = $groupname; $newgroupdata->courseid = $course->id; $newgroupdata->description = ''; $gid = groups_create_group($newgroupdata); if ($gid) { $course->groups[$groupname] = new stdClass(); $course->groups[$groupname]->id = $gid; $course->groups[$groupname]->name = $newgroupname->name; } else { $this->error('unknowngroup', new lang_string('unknowngroup', 'error', s($groupname))); return false; } } $gid = $course->groups[$groupname]->id; $gname = $course->groups[$groupname]->name; try { groups_add_member($gid, $this->finaldata->id); } catch (moodle_exception $e) { $this - error('addedtogroupnot', new lang_string('addedtogroupnot', '', s($gname), 'error')); return false; } } } } } return true; }
function equella_is_instructor($user, $cm, $courseid) { global $CFG, $DB; $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); $context_sys = context_system::instance(); $context_cc = null; if (!empty($course->category)) { $context_cc = context_coursecat::instance($course->category); } $context_c = context_course::instance($courseid); // roles are ordered by shortname $editingroles = get_all_editing_roles(); $isinstructor = false; foreach ($editingroles as $role) { $hassystemrole = user_has_role_assignment($user->id, $role->id, $context_sys->id); $hascategoryrole = false; if (!empty($context_cc)) { $hascategoryrole = user_has_role_assignment($user->id, $role->id, $context_cc->id); } $hascourserole = user_has_role_assignment($user->id, $role->id, $context_c->id); if ($hassystemrole || $hascategoryrole || $hascourserole) { return true; } } return false; }
$roles = get_user_roles($context, $USER->id, true); $participants = $streamline->participants; if ($streamline->participants == null || $streamline->participants == "[]") { //The room that is being used comes from a previous version $moderator = has_capability('mod/streamline:moderate', $context); } else { $moderator = bigbluebuttonbn_is_moderator($userID, $roles, $participants); } $administrator = has_capability('moodle/category:manage', $context); //104.155.215.138 $ipaddress = trim($CFG->ServerURLforBigBlueButton); $variable2 = substr($ipaddress, 0, strpos($ipaddress, "b")); $variable = trim(trim($variable2), '/') . '/'; $moodle_dir = $CFG->wwwroot; //Determine if user is the teacher $teacher_role = user_has_role_assignment($USER->id, 3); if ($teacher_role == 1) { $teacher = true; } else { $teacher = false; } //Determine if the meeting has ended based on on the 'meetingended' field in the DB if ($streamline->meetingended == 1) { $meetingEnded = true; } else { $meetingEnded = false; } ?> <link rel="stylesheet" type="text/css" href="streamline.css">
public function get_content() { global $DB, $USER; $this->content = new stdClass(); $this->content->text = ''; $this->content->footer = ''; if (user_has_role_assignment($USER->id, 5)) { $eventsarray = content_unlock_generate_events_list(); $us = $DB->get_records('content_unlock_system', array('deleted' => 0, 'blockinstanceid' => $this->instance->id)); if (!empty($us)) { $unlocklist = ''; $course = $DB->get_record('course', array('id' => $this->page->course->id)); $info = get_fast_modinfo($course); foreach ($us as $unlocksystem) { $sql = "SELECT *\n\t\t\t\t\t\t\tFROM {content_unlock_log} c\n\t\t\t\t\t\t\t\tINNER JOIN {logstore_standard_log} l ON c.logid = l.id\n\t\t\t\t\t\t\tWHERE l.userid = :userid\n\t\t\t\t\t\t\t\tAND c.unlocksystemid = :unlocksystemid"; $params['userid'] = $USER->id; $params['unlocksystemid'] = $unlocksystem->id; $unlocked_content = $DB->record_exists_sql($sql, $params); if ($unlocked_content) { continue; } $ccm = get_course_and_cm_from_cmid($unlocksystem->coursemoduleid); if ($this->page->course->id != $ccm[0]->id) { continue; } if (!(content_unlock_satisfies_conditions($unlocksystem->restrictions, $this->page->course->id, $USER->id) && (in_array($unlocksystem->conditions, self::$resource_events) || content_unlock_satisfies_block_conditions($unlocksystem, $this->page->course->id, $USER->id)))) { continue; } $cm = $info->get_cm($unlocksystem->coursemoduleid); $eventdescription = is_null($unlocksystem->eventdescription) ? $eventsarray[$unlocksystem->conditions] : $unlocksystem->eventdescription; $unlocklist = $unlocklist . '<li>' . $cm->name . ' (' . get_string('modulename', $cm->modname) . ') por ' . (in_array($unlocksystem->conditions, self::$resource_events) ? content_unlock_get_block_conditions_text($unlocksystem) : $eventdescription) . '</li>'; } if (strlen($unlocklist) > 0) { $this->content->text = '<p>Você pode desbloquear:<ul>' . $unlocklist . '</ul></p>'; } } if (isset($this->config)) { $lastunlocksnumber = isset($this->config->lastunlocksnumber) ? $this->config->lastunlocksnumber : 1; } else { $lastunlocksnumber = 0; } if ($lastunlocksnumber > 0) { $sql = "SELECT c.id as id, s.coursemoduleid as coursemoduleid, s.eventdescription as eventdescription, s.conditions as conditions, s.connective as connective\n\t\t\t\t\tFROM\n\t\t\t\t\t\t{content_unlock_log} c\n\t\t\t\t\tINNER JOIN {logstore_standard_log} l ON c.logid = l.id\n\t\t\t\t\tINNER JOIN {content_unlock_system} s ON c.unlocksystemid = s.id\n\t\t\t\t\tWHERE l.userid = :userid\n\t\t\t\t\t\tAND l.courseid = :courseid\n\t\t\t\t\t\tAND s.blockinstanceid = :blockinstanceid\n\t\t\t\t\tORDER BY c.id DESC"; $params['userid'] = $USER->id; $params['courseid'] = $this->page->course->id; $params['blockinstanceid'] = $this->instance->id; $lastunlocks = $DB->get_records_sql($sql, $params, 0, $lastunlocksnumber); if (!empty($lastunlocks)) { $lastunlockslist = ''; foreach ($lastunlocks as $lu) { $ccm = get_course_and_cm_from_cmid($lu->coursemoduleid); $course = $DB->get_record('course', array('id' => $ccm[0]->id)); $info = get_fast_modinfo($course); $cm = $info->get_cm($lu->coursemoduleid); $eventdescription = is_null($lu->eventdescription) ? $eventsarray[$lu->conditions] : $lu->eventdescription; $lastunlockslist = $lastunlockslist . '<li>' . $cm->name . ' (' . get_string('modulename', $cm->modname) . ') por ' . (in_array($lu->conditions, self::$resource_events) ? content_unlock_get_block_conditions_text($lu) : $eventdescription) . '</li>'; } $this->content->text = $this->content->text . '<p>Você desbloqueou recentemente:<ul>' . $lastunlockslist . '</ul></p>'; } } } return $this->content; }
require_login($course); $completion = new completion_info($course); $trackeduser = $user ? $user : $USER->id; if (!$completion->is_enabled()) { throw new moodle_exception('completionnotenabled', 'completion'); } else { if (!$completion->is_tracked_user($trackeduser)) { throw new moodle_exception('nottracked', 'completion'); } } if ($user && $rolec) { require_sesskey(); completion_criteria::factory(array('id' => $rolec, 'criteriatype' => COMPLETION_CRITERIA_TYPE_ROLE)); //TODO: this is dumb, because it does not fetch the data?!?! $criteria = completion_criteria_role::fetch(array('id' => $rolec)); if ($criteria and user_has_role_assignment($USER->id, $criteria->role, $context->id)) { $criteria_completions = $completion->get_completions($user, COMPLETION_CRITERIA_TYPE_ROLE); foreach ($criteria_completions as $criteria_completion) { if ($criteria_completion->criteriaid == $rolec) { $criteria->complete($criteria_completion); break; } } } // Return to previous page $referer = clean_param($_SERVER['HTTP_REFERER'], PARAM_LOCALURL); if (!empty($referer)) { redirect($referer); } else { redirect('view.php?id=' . $course->id); }
/** * process the mass enrolment * @param csv_import_reader $cir an import reader created by caller * @param Object $course a course record from table mdl_course * @param Object $context course context instance * @param Object $data data from a moodleform * @return string log of operations */ function mass_enroll($cir, $course, $context, $data) { global $CFG,$DB; require_once ($CFG->dirroot . '/group/lib.php'); $result = ''; $courseid=$course->id; $roleid = $data->roleassign; $useridfield = $data->firstcolumn; $enrollablecount = 0; $createdgroupscount = 0; $createdgroupingscount = 0; $createdgroups = ''; $createdgroupings = ''; $plugin = enrol_get_plugin('manual'); //Moodle 2.x enrolment and role assignment are different // make sure couse DO have a manual enrolment plugin instance in that course //that we are going to use (only one instance is allowed @see enrol/manual/lib.php get_new_instance) // thus call to get_record is safe $instance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'manual')); if (empty($instance)) { // Only add an enrol instance to the course if non-existent $enrolid = $plugin->add_instance($course); $instance = $DB->get_record('enrol', array('id' => $enrolid)); } // init csv import helper $cir->init(); while ($fields = $cir->next()) { $a = new StdClass(); if (empty ($fields)) continue; // print_r($fields); // $enrollablecount++; // continue; // 1rst column = id Moodle (idnumber,username or email) // get rid on eventual double quotes unfortunately not done by Moodle CSV importer $fields[0]= str_replace('"', '', trim($fields[0])); if (!$user = $DB->get_record('user', array($useridfield => $fields[0]))) { $result .= '<div class="alert alert-error">'.get_string('im:user_unknown', 'local_mass_enroll', $fields[0] ). '</div>'; continue; } if(!$DB->record_exists_sql("select id from {local_userdata} where costcenterid=$course->costcenter AND userid=$user->id")){ $costcentername = $DB->get_field('local_costcenter','fullname',array('id'=>$course->costcenter)); $cs_object = new stdClass(); $cs_object->csname = $costcentername; $cs_object->user = fullname($user); $result .= '<div class="alert alert-error">'.get_string('im:user_notcostcenter', 'local_mass_enroll',$cs_object ). '</div>'; continue; } //already enroled ? if (user_has_role_assignment($user->id, $roleid, $context->id)) { $result .= '<div class="alert alert-error">'.get_string('im:already_in', 'local_mass_enroll', fullname($user)). '</div>'; } else { //TODO take care of timestart/timeend in course settings // done in rev 1.1 $timestart = time(); // remove time part from the timestamp and keep only the date part $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0); if ($instance->enrolperiod) { $timeend = $timestart + $instance->enrolperiod; } else { $timeend = 0; } // not anymore so easy in Moodle 2.x // if (!role_assign($roleid, $user->id, null, $context->id, $timestart, $timeend, 0, 'flatfile')) { // $result .= get_string('im:error_in', 'local_mass_enroll', fullname($user)) . ""; // continue; //} // // Enrol the user with this plugin instance (unfortunately return void, no more status ) $plugin->enrol_user($instance, $user->id,$roleid,$timestart,$timeend); $result .= '<div class="alert alert-success">'.get_string('im:enrolled_ok', 'local_mass_enroll', fullname($user)).'</div>'; $enrollablecount++; } $group = str_replace('"','',trim($fields[1])); // 2nd column ? if (empty ($group)) { $result .= ""; continue; // no group for this one } // create group if needed if (!($gid = mass_enroll_group_exists($group, $courseid))) { if ($data->creategroups) { if (!($gid = mass_enroll_add_group($group, $courseid))) { $a->group = $group; $a->courseid = $courseid; $result .= '<div class="alert alert-error">'.get_string('im:error_addg', 'local_mass_enroll', $a) . '</div>'; continue; } $createdgroupscount++; $createdgroups .= " $group"; } else { $result .= '<div class="alert alert-error">'.get_string('im:error_g_unknown', 'local_mass_enroll', $group) . '</div>'; continue; } } // if groupings are enabled on the site (should be ?) // if ($CFG->enablegroupings) { // not anymore in Moodle 2.x if (!($gpid = mass_enroll_grouping_exists($group, $courseid))) { if ($data->creategroupings) { if (!($gpid = mass_enroll_add_grouping($group, $courseid))) { $a->group = $group; $a->courseid = $courseid; $result .= '<div class="alert alert-error">'.get_string('im:error_add_grp', 'local_mass_enroll', $a) . '</div>'; continue; } $createdgroupingscount++; $createdgroupings .= " $group"; } else { // don't complains, // just do the enrolment to group } } // if grouping existed or has just been created if ($gpid && !(mass_enroll_group_in_grouping($gid, $gpid))) { if (!(mass_enroll_add_group_grouping($gid, $gpid))) { $a->group = $group; $result .= '<div class="alert alert-error">'.get_string('im:error_add_g_grp', 'local_mass_enroll', $a) . '</div>'; continue; } } //} // finally add to group if needed if (!groups_is_member($gid, $user->id)) { $ok = groups_add_member($gid, $user->id); if ($ok) { $result .= '<div class="alert alert-success">'.get_string('im:and_added_g', 'local_mass_enroll', $group) . '</div>'; } else { $result .= '<div class="alert alert-error">'.get_string('im:error_adding_u_g', 'local_mass_enroll', $group) . '</div>'; } } else { $result .= '<div class="alert alert-notice">'.get_string('im:already_in_g', 'local_mass_enroll', $group) . '</div>'; } } $result .= '<br />'; //recap final $result .= get_string('im:stats_i', 'local_mass_enroll', $enrollablecount) . ""; $a->nb = $createdgroupscount; if(!isset($createdgroups) || empty($createdgroups)||$createdgroups='') $a->what = '-'; else $a->what = $createdgroups; $result .= get_string('im:stats_g', 'local_mass_enroll', $a) . ""; $a->nb = $createdgroupingscount; if(!isset($createdgroupings) || empty($createdgroupings)||$createdgroupings='') $a->what = '-'; else $a->what = $createdgroupings; $result .= get_string('im:stats_grp', 'local_mass_enroll', $a) . ""; return $result; }
<?php global $CFG, $DB, $OUTPUT, $HStuList, $StuList, $course; $a1 = user_has_role_assignment($USER->id, 1); $a2 = user_has_role_assignment($USER->id, 2); $a3 = user_has_role_assignment($USER->id, 3); $a4 = user_has_role_assignment($USER->id, 4); $sadmin = is_siteadmin(); //echo $a1.','.$a2.','.$a3.','.$a4.','.$sadmin.'</br> ---'; if ($a2 == 1 || $a3 == 1 || $a4 == 1 || $sadmin == 1) { $sql = "SELECT u.username\n\t\t\tFROM mdl_role_assignments ra, mdl_user u, mdl_course c, mdl_context cxt\n\t\t\tWHERE ra.userid = u.id\n\t\t\tAND ra.contextid = cxt.id\n\t\t\tAND cxt.contextlevel =50\n\t\t\tAND cxt.instanceid = c.id\n\t\t\tAND c.shortname = ?\n\t\t\tAND (roleid = 5 OR roleid = 3 )"; $p = $DB->get_records_sql($sql, array($course->shortname)); foreach ($p as $k => $v) { foreach ($v as $r => $o) { $Sval = bin2hex($o); $HStuList .= $Sval . ','; $StuList .= $o . ','; } } $HStuList .= '-'; $StuList .= '-'; // echo '<html><body onload="myFunction()"></body></html>'; // echo 'List of H students :'.$HStuList; // echo '</br>'; // echo 'List of students :'.$StuList; // echo '</br>'; // echo 'name: '.$course->shortname; }
} } // Group members if ($canseemembers) { if ($members = groups_get_members($group->id)) { $membernames = array(); foreach ($members as $member) { $pic = $OUTPUT->user_picture($member, array('courseid' => $course->id)); if ($member->id == $USER->id) { $membernames[] = '<span class="me">' . $pic . ' ' . fullname($member, $viewfullnames) . '</span>'; } else { $membernames[] = $pic . ' <a href="' . $CFG->wwwroot . '/user/view.php?id=' . $member->id . '&course=' . $course->id . '">' . fullname($member, $viewfullnames) . '</a>'; } } // Show assigned teacher, if exists, when enabled or when user is non-assigned teacher if ($groupselect->showassignedteacher or user_has_role_assignment($USER->id, $ASSIGNROLE, context_course::instance($course->id)->id)) { $teacherid = null; foreach ($assigned_relation as $r) { if ($r->groupid === $group->id) { $teacherid = $r->id; break; } } if ($teacherid) { $teacher = null; foreach ($assigned_teachers as $a) { if ($a->id === $teacherid) { $teacher = $a; $break; } }
function tao_create_lp($data, $author, $creatorroleid, $createtemplate = 0, $preferences = array()) { global $CFG; if (empty($data)) { error("invalid call to tao_create_lp"); } // get course template if (!($course = get_record('course', 'id', $data->course_template))) { error('Invalid course id'); } // get a handle on the most recent backup for the selected course $wdir = "/backupdata"; $fullpath = $CFG->dataroot . "/" . $course->id . $wdir; $dirlist = array(); $filelist = array(); if (!is_dir($fullpath)) { error("No templates for selected course"); } $directory = opendir($fullpath); // Find all files while (false !== ($file = readdir($directory))) { if ($file == "." || $file == "..") { continue; } if (strchr($file, ".") != ".zip") { continue; } if (is_dir($fullpath . "/" . $file)) { $dirlist[] = $file; } else { $filelist[] = $file; } } closedir($directory); asort($filelist); // get the last file $file = array_pop($filelist); $fullpathtofile = "{$fullpath}/{$file}"; if (!$file) { error("No templates for selected course"); } // attempt to create the new course if (!($newcourse = create_course($data))) { print_error('coursenotcreated'); } $context = get_context_instance(CONTEXT_COURSE, $newcourse->id); $sitecontext = get_context_instance(CONTEXT_COURSE, SITEID); // assign our initial user - note this means automatic assigning by the backup should be skipped, which is based // the on the manage:activities role being present role_assign($creatorroleid, $author->id, 0, $context->id); if ($data->learning_path_mode == LEARNING_PATH_MODE_RAFL) { //now set role override for PT users to prevent them from being able to add blocks and activities. $ptroleid = get_field('role', 'id', 'shortname', ROLE_PT); $ispt = user_has_role_assignment($author->id, $ptroleid, $sitecontext->id); if ($ispt) { //prevent from being able to change the structure of the pages. assign_capability('format/learning:manageactivities', CAP_PREVENT, $creatorroleid, $context->id); } } // create default the TAO Course (LP) Forum /// ** load this in template instead? ** local_create_forum($newcourse->id, SEPARATEGROUPS, get_string('defaultforumname', 'local'), get_string('defaultforumintro', 'local')); // create default the TAO Course (LP) Wiki /// ** load this in template instead? ** local_create_wiki($newcourse->id, SEPARATEGROUPS, get_string('defaultwikiname', 'local'), get_string('defaultwikisummary', 'local')); if (!$createtemplate) { // set course status if (!tao_update_course_status(COURSE_STATUS_NOTSUBMITTED, "Created new learning path from template", $newcourse)) { error('could not update status'); } } //set up preferences for pasign to backup_file_silently $preferences['course_format'] = 1; if ($data->learning_path_mode == LEARNING_PATH_MODE_STANDARD) { // load the backup data into course //TODO some way of validating this import_backup_file_silently($fullpathtofile, $newcourse->id, false, false, $preferences, RESTORETO_CURRENT_DELETING); // if valid // set course status if (!tao_update_course_status(COURSE_STATUS_NOTSUBMITTED, "Created new learning path from template", $newcourse)) { error('could not update status'); } // ensure we can use the course right after creating it // this means trigger a reload of accessinfo... mark_context_dirty($context->path); $author->raflmode = 0; // Redirect to course page return $newcourse->id; } elseif ($data->learning_path_mode == LEARNING_PATH_MODE_RAFL) { //set pref to not restore pages for all RAFL imports: $preferences['nopages'] = 1; // load the template, but leave out actual content pages - they are created by rafl structure. // note: we must do this before adding the new pages otherwise this process will remove them import_backup_file_silently($fullpathtofile, $newcourse->id, false, false, $preferences); // todo do a non-fatal check for rafl module, and give a friendly message if not found require_once $CFG->dirroot . '/mod/rafl/lib.php'; require_once $CFG->dirroot . '/mod/rafl/locallib.php'; require_once $CFG->dirroot . '/course/format/learning/lib.php'; require_once $CFG->dirroot . '/course/format/learning/pagelib.php'; $rafl = new localLibRafl(); $pageid = $newcourse->id; // pageid is actually courseid in the blockinstance context. i know! $pagetype = 'course-view'; // first create the summary page $page = new stdClass(); $page->nameone = get_string('lpsummarypagetitle', 'local'); $page->nametwo = get_string('lpsummarypagetitle', 'local'); $page->courseid = $newcourse->id; $page->display = 1; $page->showbuttons = 3; $summarypageid = insert_record('format_page', $page); // add the standard blocks for a summary page $instanceid = tao_add_learningpath_block('tao_learning_path_summary', $pageid, $pagetype, "Learning Stations"); if (!empty($instanceid)) { tao_add_learningpath_pageitem($summarypageid, $instanceid); } // now the station pages $items = $rafl->get_lp_item_structure(0); // todo don't hardcode this parameter foreach ($items as $item) { // check for existing station/pie, if not there insert as a format_page $sql = "SELECT id FROM {$CFG->prefix}format_page WHERE courseid = {$newcourse->id} AND rafl_item = {$item->question_item_id}"; $exists = get_records_sql($sql); if (empty($exists)) { // add the format page $page = new stdClass(); $page->nameone = $item->title; $page->nametwo = $item->title; $page->courseid = $newcourse->id; $page->display = 1; $page->showbuttons = 3; $page->parent = $summarypageid; $page->rafl_item = $item->question_item_id; $formatpageid = insert_record('format_page', $page); // add the title block $instanceid = tao_add_learningpath_block('html', $pageid, $pagetype, '', '<h1>' . $item->title . '</h1>'); if (!empty($instanceid)) { tao_add_learningpath_pageitem($formatpageid, $instanceid); } } } // now add the question blocks $country_item_id = $rafl->get_rafl_item_id_by_country('uk'); $items = $rafl->get_lp_item_structure($country_item_id); // todo find a better way to pass this parameter foreach ($items as $item) { // db integrity - at least check for existing station/pie $sql = "SELECT id FROM {$CFG->prefix}format_page WHERE courseid = {$newcourse->id} AND rafl_item = {$item->pie_item_id}"; $formatpage = get_record_sql($sql); if (!empty($formatpage)) { // insert question as a block and format_page item on this page $instanceid = tao_add_learningpath_block('tao_lp_qa', $pageid, $pagetype, $item->title); // create a new page item that links to the instance if (!empty($instanceid)) { tao_add_learningpath_pageitem($formatpage->id, $instanceid, $item->question_item_id); } } else { debugging("pie {$item->pie_item_id} is not in the database"); } } // add the rafl module to the course $mod = new object(); $mod->course = $newcourse->id; $mod->name = 'RAFL Authoring Module'; $mod->intro = 'RAFL Authoring Module'; $instanceid = rafl_add_instance($mod); if (!($module = get_record("modules", "name", 'rafl'))) { error("This module type doesn't exist"); } if (!($cs = get_record("course_sections", "section", 0, "course", $newcourse->id))) { error("This course section doesn't exist"); } $cm->section = 0; //$cs->id; $cm->course = $newcourse->id; $cm->module = $module->id; $cm->modulename = $module->name; $cm->instance = $instanceid; // connect to course if (!($cm->coursemodule = add_course_module($cm))) { error("Could not add a new course module"); } $sectionid = add_mod_to_section($cm); set_field("course_modules", "section", $sectionid, "id", $cm->coursemodule); // create rafl_share $rafl->create_share($newcourse->id, $author->id); // if valid // set course status if (!tao_update_course_status(COURSE_STATUS_NOTSUBMITTED, "Created new learning path from RAFL module", $newcourse)) { error('could not update status'); } // ensure we can use the course right after creating it // this means trigger a reload of accessinfo... mark_context_dirty($context->path); $author->raflmode = 1; rebuild_course_cache($newcourse->id); // redirect to participants page return $newcourse->id; } else { error("invalid authoring mode"); } }
$dir = optional_param('dir', 'ASC', PARAM_ALPHA); $page = optional_param('page', 0, PARAM_INT); $perpage = optional_param('perpage', 30, PARAM_INT); // how many per page if (!($COURSE = get_record('course', 'id', $courseid))) { error('Invalid course idnumber'); } if (!empty($groupid) && !($group = get_record('groups', 'id', $groupid, 'courseid', $courseid))) { error('Invalid group id'); } require_login(); $ptrole = get_record('role', 'shortname', ROLE_PT); $mtrole = get_record('role', 'shortname', ROLE_MT); $sitecontext = get_context_instance(CONTEXT_COURSE, SITEID); $ispt = user_has_role_assignment($USER->id, $ptrole->id, $sitecontext->id); $ismt = user_has_role_assignment($USER->id, $mtrole->id, $sitecontext->id); print_header_simple($strheading, $strheading, build_navigation($strheading)); if ($action == 'joingroup') { if ($COURSE->groupmode == '1') { //if groupmode for this course is set to seperate. $groups = groups_get_all_groups($COURSE->id, $USER->id); if (empty($groups)) { //if user isn't in a Group - display invites and add group stuff. echo tao_show_user_invites($USER->id, $COURSE->id); echo tao_new_group_form($COURSE->id); print_footer(); exit; } else { notify(get_string('alreadyinagroup', 'block_tao_team_groups')); print_continue($CFG->wwwroot . "/course/view.php?id={$COURSE->id}"); print_footer();
protected static function is_student($userid) { return user_has_role_assignment($userid, 5); }
/** * Given an object containing all the necessary data, * (defined by the form in mod_form.php) this function * will create a new instance and return the id number * of the new instance. * * @param object $adobeconnect An object from the form in mod_form.php * @return int The id of the newly inserted adobeconnect record */ function adobeconnect_add_instance($adobeconnect) { global $COURSE, $USER, $DB; $adobeconnect->timecreated = time(); $adobeconnect->meeturl = adobeconnect_clean_meet_url($adobeconnect->meeturl); $return = false; $meeting = new stdClass(); // Assign the current user with the Adobe Presenter role $context = get_context_instance(CONTEXT_COURSE, $adobeconnect->course); if (!has_capability('mod/adobeconnect:meetinghost', $context, $USER->id, false)) { $param = array('shortname' => 'adobeconnecthost'); $roleid = $DB->get_field('role', 'id', $param); if (role_assign($roleid, $USER->id, $context->id, 'mod_adobeconnect')) { //DEBUG } else { echo 'role assignment failed'; die; } } $recid = $DB->insert_record('adobeconnect', $adobeconnect); if (empty($recid)) { return false; } $aconnect = aconnect_login(); $meetfldscoid = aconnect_get_folder($aconnect, 'my-meetings'); $meeting = clone $adobeconnect; if (0 != $adobeconnect->groupmode) { // Allow for multiple groups // get all groups for the course $crsgroups = groups_get_all_groups($COURSE->id); if (empty($crsgroups)) { return 0; } require_once dirname(dirname(dirname(__FILE__))) . '/group/lib.php'; // Create the meeting for each group foreach ($crsgroups as $crsgroup) { // The teacher role if they don't already have one and // Assign them to each group if (!groups_is_member($crsgroup->id, $USER->id)) { $param = array('shortname' => 'editingteacher'); $roleid = $DB->get_field('role', 'id', $param); if (!user_has_role_assignment($USER->id, $roleid, $context->id)) { role_assign($roleid, $USER->id, $context->id, 'mod_adobeconnect'); } groups_add_member($crsgroup->id, $USER->id); } $meeting->name = $adobeconnect->name . '_' . $crsgroup->name; if (!empty($adobeconnect->meeturl)) { $meeting->meeturl = adobeconnect_clean_meet_url($adobeconnect->meeturl . '_' . $crsgroup->name); } if (!($meetingscoid = aconnect_create_meeting($aconnect, $meeting, $meetfldscoid))) { debugging('error creating meeting', DEBUG_DEVELOPER); } // Update permissions for meeting if (empty($adobeconnect->meetingpublic)) { aconnect_update_meeting_perm($aconnect, $meetingscoid, ADOBE_MEETPERM_PRIVATE); } else { aconnect_update_meeting_perm($aconnect, $meetingscoid, ADOBE_MEETPERM_PUBLIC); } // Insert record to activity instance in meeting_groups table $record = new stdClass(); $record->instanceid = $recid; $record->meetingscoid = $meetingscoid; $record->groupid = $crsgroup->id; $record->id = $DB->insert_record('adobeconnect_meeting_groups', $record); // Add event to calendar $event = new stdClass(); $event->name = $meeting->name; $event->description = format_module_intro('adobeconnect', $adobeconnect, $adobeconnect->coursemodule); $event->courseid = $adobeconnect->course; $event->groupid = $crsgroup->id; $event->userid = 0; $event->instance = $recid; $event->eventtype = 'group'; $event->timestart = $adobeconnect->starttime; $event->timeduration = $adobeconnect->endtime - $adobeconnect->starttime; $event->visible = 1; $event->modulename = 'adobeconnect'; calendar_event::create($event); } } else { // no groups support $meetingscoid = aconnect_create_meeting($aconnect, $meeting, $meetfldscoid); // Update permissions for meeting if (empty($adobeconnect->meetingpublic)) { aconnect_update_meeting_perm($aconnect, $meetingscoid, ADOBE_MEETPERM_PRIVATE); } else { aconnect_update_meeting_perm($aconnect, $meetingscoid, ADOBE_MEETPERM_PUBLIC); } // Insert record to activity instance in meeting_groups table $record = new stdClass(); $record->instanceid = $recid; $record->meetingscoid = $meetingscoid; $record->groupid = 0; $record->id = $DB->insert_record('adobeconnect_meeting_groups', $record); // Add event to calendar $event = new stdClass(); $event->name = $meeting->name; $event->description = format_module_intro('adobeconnect', $adobeconnect, $adobeconnect->coursemodule); $event->courseid = $adobeconnect->course; $event->groupid = 0; $event->userid = 0; $event->instance = $recid; $event->eventtype = 'course'; $event->timestart = $adobeconnect->starttime; $event->timeduration = $adobeconnect->endtime - $adobeconnect->starttime; $event->visible = 1; $event->modulename = 'adobeconnect'; calendar_event::create($event); } // If no meeting URL was submitted, // update meeting URL for activity with server assigned URL if (empty($adobeconnect->meeturl) and 0 == $adobeconnect->groupmode) { $filter = array('filter-sco-id' => $meetingscoid); $meeting = aconnect_meeting_exists($aconnect, $meetfldscoid, $filter); if (!empty($meeting)) { $meeting = current($meeting); $record = new stdClass(); $record->id = $recid; $record->meeturl = trim($meeting->url, '/'); $DB->update_record('adobeconnect', $record); } } aconnect_logout($aconnect); return $recid; }
function jbxl_has_role($uid, $cntxt, $rolename) { global $DB; if (!$cntxt) { return false; } if (!is_object($cntxt)) { $cntxt = jbxl_get_course_context($cntxt); } $roles = $DB->get_records('role', array('archetype' => $rolename), 'id', 'id'); foreach ($roles as $role) { $ret = user_has_role_assignment($uid, $role->id, $cntxt->id); if ($ret) { return $ret; } } return false; }
$usrgroups = $usrgroups[0]; // Just want groups and not groupings // If separate groups is enabled, check if the user is a part of the selected group if (0 != $cm->groupmode) { if (false !== array_search($groupid, $usrgroups)) { $usrcanjoin = true; } } $context = get_context_instance(CONTEXT_COURSE, $cm->course); // Make sure the user has a role in the course $crsroles = get_roles_used_in_context($context); if (empty($crsroles)) { $crsroles = array(); } foreach ($crsroles as $roleid => $crsrole) { if (user_has_role_assignment($usrobj->id, $roleid, $context->id)) { $usrcanjoin = true; } } // user has to be in a group if ($usrcanjoin and confirm_sesskey($sesskey)) { $usrprincipal = 0; $validuser = true; $groupobj = groups_get_group($groupid); // Get the meeting sco-id $param = array('instanceid' => $cm->instance, 'groupid' => $groupid); $meetingscoid = $DB->get_field('adobeconnect_meeting_groups', 'meetingscoid', $param); $aconnect = aconnect_login(); // Check if the meeting still exists on the Adobe server $meetfldscoid = aconnect_get_folder($aconnect, 'my-meetings'); $filter = array('filter-sco-id' => $meetingscoid);
error("That's an invalid course id"); exit; } echo "<br> Context id is {$context->id}"; if (!($user = get_record('user', 'username', $username))) { echo 'The username ' . $username . ' is invalid'; error("That's an invalid username"); exit; } echo "<br> User is {$user->firstname} {$user->lastname}"; // If user wasn't enrolled, enrol now. Ignore otherwise. if ($role = get_record('role', 'name', 'Student')) { // if (($role = get_default_course_role($course))) { echo "<br> The role description is {$role->description}"; echo "<br> Calling user_has_role_assignment(\$user->id, \$role->id, \$context->id) with user_has_role_assignment({$user->id}, {$role->id}, {$context->id})"; if (!user_has_role_assignment($user->id, $role->id, $context->id)) { echo "<br> User is not enroled in this course"; if (!enrol_into_course($course, $user, 'manual')) { print_error('couldnotassignrole'); echo "<br> User could NOT be enrolled into the course"; error("User could NOT be enrolled into the course"); exit; } echo "<br> User was just enrolled into the course"; // force a refresh of mycourses unset($user->mycourses); if (!empty($SESSION->wantsurl)) { $destination = $SESSION->wantsurl; unset($SESSION->wantsurl); } else { $destination = "{$CFG->wwwroot}/course/view.php?id={$course->id}";
/// extra praxe action /// if (!is_null($praxeaction)) { require_once $CFG->dirroot . '/mod/praxe/praxeaction.php'; } /// rights to all actions in this module /// if (has_capability('mod/praxe:manageallincourse', $context) || has_capability('mod/praxe:assignselftoinspection', $context)) { $viewrole = 'EDITTEACHER'; $role_title = get_string('teacher', 'praxe'); /// rights to create or manage own record of praxe - for students /// } else { if (has_capability('mod/praxe:editownrecord', $context)) { $viewrole = 'STUDENT'; $role_title = get_string('student', 'praxe'); } else { foreach (get_roles_used_in_context($context) as $role) { if (user_has_role_assignment($USER->id, $role->id, $context->id)) { if ($role->shortname == 'extheadmaster') { $viewrole = 'HEADM'; $role_title = get_string('headmaster', 'praxe'); } else { if ($role->shortname == 'extteacher') { $viewrole = 'EXTTEACHER'; $role_title = get_string('extteacher', 'praxe'); } } break; } } } } $post_form = optional_param('post_form', null, PARAM_ALPHAEXT);
$reciproleid = required_param('reciprole', PARAM_INT); $cap = required_param('cap', PARAM_ALPHA); $unassign = optional_param('unassign', false, PARAM_INT); $sitecontext = get_context_instance(CONTEXT_COURSE, SITEID); $usercontext = get_context_instance(CONTEXT_USER, $userto); $returnurl = $CFG->wwwroot . '/user/view.php?id=' . $userto; if (!($assignrole = get_record('role', 'id', $roleid))) { print_error('unknownrole', 'error', $returnurl, $roleid); } if (!($reciprole = get_record('role', 'id', $reciproleid))) { print_error('unknownrole', 'error', $returnurl, $reciproleid); } if (!confirm_sesskey()) { print_error('confirmsesskeybad', 'error', $returnurl); } $exists = user_has_role_assignment($USER->id, $assignrole->id, $usercontext->id); $canassign = has_capability('moodle/local:canassign' . $cap, $sitecontext); $isassignable = has_capability('moodle/local:isassignable' . $cap, $sitecontext, $userto, false); $assignedstr = get_string('roleassigned', 'local', $reciprole->name); $assignedshortstr = get_string('roleassignedshort', 'local'); $unassignedstr = get_string('roleunassigned', 'local', $reciprole->name); $unassignedshortstr = get_string('roleunassignedshort', 'local'); if ($exists) { if (!$unassign) { print_error('alreadyassigned', 'local', $returnurl, $reciprole->name); } // fine , we've been asked to unassign it. // don't bother checking the capabilities since we're removing it. if (!role_unassign($assignrole->id, $USER->id, 0, $usercontext->id)) { print_error('couldnotunassignrole', 'local', $returnurl); }
function authorize_process_csv($filename) { global $CFG, $SITE, $DB; $plugin = enrol_get_plugin('authorize'); /// We need these fields $myfields = array('Transaction ID', 'Transaction Status', 'Transaction Type', 'Settlement Amount', 'Settlement Currency', 'Settlement Date/Time', 'Authorization Amount', 'Authorization Currency', 'Submit Date/Time', 'Reference Transaction ID', 'Total Amount', 'Currency', 'Invoice Number', 'Customer ID'); /// Open the file and get first line $handle = fopen($filename, "r"); if (!$handle) { print_error('cannotopencsv'); } $firstline = fgetcsv($handle, 8192, ","); $numfields = count($firstline); if ($numfields != 49 && $numfields != 70) { @fclose($handle); print_error('csvinvalidcolsnum'); } /// Re-sort fields $csvfields = array(); foreach ($myfields as $myfield) { $csvindex = array_search($myfield, $firstline); if ($csvindex === false) { $csvfields = array(); break; } $csvfields[$myfield] = $csvindex; } if (empty($csvfields)) { @fclose($handle); print_error('csvinvalidcols'); } /// Read lines $sendem = array(); $ignoredlines = ''; $imported = 0; $updated = 0; $ignored = 0; while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) { if (count($data) != $numfields) { $ignored++; // ignore empty lines continue; } $transid = $data[$csvfields['Transaction ID']]; $transtype = $data[$csvfields['Transaction Type']]; $transstatus = $data[$csvfields['Transaction Status']]; $reftransid = $data[$csvfields['Reference Transaction ID']]; $settlementdate = strtotime($data[$csvfields['Settlement Date/Time']]); if ($transstatus == 'Approved Review' || $transstatus == 'Review Failed') { if ($order = $DB->get_record('enrol_authorize', array('transid' => $transid))) { $order->status = $transstatus == 'Approved Review' ? AN_STATUS_APPROVEDREVIEW : AN_STATUS_REVIEWFAILED; $DB->update_record('enrol_authorize', $order); $updated++; // Updated order status } continue; } if (!empty($reftransid) && is_numeric($reftransid) && 'Settled Successfully' == $transstatus && 'Credit' == $transtype) { if ($order = $DB->get_record('enrol_authorize', array('transid' => $reftransid))) { if (AN_METHOD_ECHECK == $order->paymentmethod) { $refund = $DB->get_record('enrol_authorize_refunds', array('transid' => $transid)); if ($refund) { $refund->status = AN_STATUS_CREDIT; $refund->settletime = $settlementdate; $DB->update_record('enrol_authorize_refunds', $refund); $updated++; } else { $ignored++; $ignoredlines .= $reftransid . ": Not our business(Reference Transaction ID)\n"; } } } else { $ignored++; $ignoredlines .= $reftransid . ": Not our business(Transaction ID)\n"; } continue; } if (!($transstatus == 'Settled Successfully' && $transtype == 'Authorization w/ Auto Capture')) { $ignored++; $ignoredlines .= $transid . ": Not settled\n"; continue; } // TransactionId must match $order = $DB->get_record('enrol_authorize', array('transid' => $transid)); if (!$order) { $ignored++; $ignoredlines .= $transid . ": Not our business\n"; continue; } // Authorized/Captured and Settled $order->status = AN_STATUS_AUTHCAPTURE; $order->settletime = $settlementdate; $DB->update_record('enrol_authorize', $order); $updated++; // Updated order status and settlement date if ($order->paymentmethod != AN_METHOD_ECHECK) { $ignored++; $ignoredlines .= $transid . ": The method must be echeck\n"; continue; } // Get course and context $course = $DB->get_record('course', array('id' => $order->courseid)); if (!$course) { $ignored++; $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n"; continue; } $coursecontext = context_course::instance($course->id, IGNORE_MISSING); if (!$coursecontext) { $ignored++; $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n"; continue; } // Get user $user = $DB->get_record('user', array('id' => $order->userid)); if (!$user) { $ignored++; $ignoredlines .= $transid . ": Could not find this user: "******"\n"; continue; } // If user wasn't enrolled, enrol now. Ignore otherwise. Because admin user might submit this file again. if ($role = get_default_course_role($course)) { if (!user_has_role_assignment($user->id, $role->id, $coursecontext->id)) { $timestart = $timeend = 0; if ($course->enrolperiod) { $timestart = time(); $timeend = $timestart + $course->enrolperiod; } // Enrol user $pinstance = $DB->get_record('enrol', array('id' => $order->instanceid)); $plugin->enrol_user($pinstance, $user->id, $pinstance->roleid, $timestart, $timeend); $imported++; if ($plugin->get_config('enrol_mailstudents')) { $sendem[] = $order->id; } } } } fclose($handle); /// Send email to admin if (!empty($ignoredlines)) { $admin = get_admin(); $eventdata = new stdClass(); $eventdata->modulename = 'moodle'; $eventdata->component = 'enrol_authorize'; $eventdata->name = 'authorize_enrolment'; $eventdata->userfrom = $admin; $eventdata->userto = $admin; $eventdata->subject = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID))) . ': Authorize.net CSV ERROR LOG'; $eventdata->fullmessage = $ignoredlines; $eventdata->fullmessageformat = FORMAT_PLAIN; $eventdata->fullmessagehtml = ''; $eventdata->smallmessage = ''; message_send($eventdata); } /// Send welcome messages to users if (!empty($sendem)) { send_welcome_messages($sendem); } /// Show result notice("<b>Done...</b><br />Imported: {$imported}<br />Updated: {$updated}<br />Ignored: {$ignored}"); }
/** * * Takes an instructor unassignment and deletes the appropriate * Moodle course role assignments * * @param stdClass $eventdata The appropriate local_elisprogram_cls_nstrct record * @return bool always returns true */ function pm_notify_instructor_unassigned_handler($eventdata) { global $CFG, $DB; require_once elispm::lib('data/user.class.php'); // make sure users in some roles are identified as course managers if (empty($CFG->coursecontact)) { return true; } // create the curriculum administration class try { if (!($pmclass = new pmclass($eventdata->classid))) { return true; } } catch (dml_missing_record_exception $e) { // record does not exists, so no need to sync return true; } // ensure that the class is tied to a Moodle course $moodlecourseid = $pmclass->get_moodle_course_id(); if (empty($moodlecourseid)) { return true; } // retrieve the context for the Moodle course $coursecontext = context_course::instance($moodlecourseid); if (!$coursecontext) { return true; } // make sure the Moodle course is not tied to other curriculum administration classes if ($DB->count_records(classmoodlecourse::TABLE, array('moodlecourseid' => $moodlecourseid)) != 1) { return true; } // Retrieve the Moodle user $cmuser = new user(); $cmuser->id = $eventdata->userid; $instructor = $cmuser->get_moodleuser(); if (!$instructor) { return true; } // Go through all applicable roles to see if we can remove them from the Moodle side of things $roleids = explode(',', $CFG->coursecontact); $course = new stdClass(); $course->id = $coursecontext->instanceid; // Loop through each of the course contact roles, check if they have the role assignment, unenroll them and remove it foreach ($roleids as $roleid) { $hasroleassignment = user_has_role_assignment($instructor->id, $roleid, $coursecontext->id); if ($hasroleassignment) { // This method unenrolls and removes all of the user's roles from the course @see role_unassign_all() $plugin = enrol_get_plugin('elis'); $enrolinstance = $plugin->get_or_create_instance($course); $plugin->unenrol_user($enrolinstance, $instructor->id); } } return true; }
} else { $removing = false; } if (array_key_exists($sysrolename, $sysrolecache)) { $sysroleid = $sysrolecache[$sysrolename]->id; } else { $upt->track('enrolments', get_string('unknownrole', 'error', s($sysrolename)), 'error'); continue; } if ($removing) { if (user_has_role_assignment($user->id, $sysroleid, SYSCONTEXTID)) { role_unassign($sysroleid, $user->id, SYSCONTEXTID); $upt->track('enrolments', get_string('unassignedsysrole', 'tool_uploaduser', $sysrolecache[$sysroleid]->name)); } } else { if (!user_has_role_assignment($user->id, $sysroleid, SYSCONTEXTID)) { role_assign($sysroleid, $user->id, SYSCONTEXTID); $upt->track('enrolments', get_string('assignedsysrole', 'tool_uploaduser', $sysrolecache[$sysroleid]->name)); } } } continue; } if (!preg_match('/^course\\d+$/', $column)) { continue; } $i = substr($column, 6); if (empty($user->{'course' . $i})) { continue; } $shortname = $user->{'course' . $i};
/** * Constructor. Sets local copies of user preferences and initialises grade_tree. * @param int $userid * @param object $gpr grade plugin return tracking object * @param string $context */ public function __construct($userid, $gpr, $context) { global $CFG, $COURSE, $DB; parent::__construct($COURSE->id, $gpr, $context); // Get the user (for full name). $this->user = $DB->get_record('user', array('id' => $userid)); // Load the user's courses. $this->courses = enrol_get_users_courses($this->user->id, false, 'id, shortname, showgrades'); $this->showrank = array(); $this->showrank['any'] = false; $this->showtotalsifcontainhidden = array(); $this->studentcourseids = array(); $this->teachercourses = array(); $roleids = explode(',', get_config('moodle', 'gradebookroles')); if ($this->courses) { foreach ($this->courses as $course) { $this->showrank[$course->id] = grade_get_setting($course->id, 'report_overview_showrank', !empty($CFG->grade_report_overview_showrank)); if ($this->showrank[$course->id]) { $this->showrank['any'] = true; } $this->showtotalsifcontainhidden[$course->id] = grade_get_setting($course->id, 'report_overview_showtotalsifcontainhidden', $CFG->grade_report_overview_showtotalsifcontainhidden); $coursecontext = context_course::instance($course->id); foreach ($roleids as $roleid) { if (user_has_role_assignment($userid, $roleid, $coursecontext->id)) { $this->studentcourseids[$course->id] = $course->id; // We only need to check if one of the roleids has been assigned. break; } } if (has_capability('moodle/grade:viewall', $coursecontext, $userid)) { $this->teachercourses[$course->id] = $course; } } } // base url for sorting by first/last name $this->baseurl = $CFG->wwwroot . '/grade/overview/index.php?id=' . $userid; $this->pbarurl = $this->baseurl; $this->setup_table(); }
* @copyright 2010 Remote-Learner.net * @author Hubert Chathi <*****@*****.**> * @author Olav Jordan <*****@*****.**> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once(dirname(__FILE__) . '/../config.php'); require_once($CFG->dirroot . '/my/lib.php'); require_once($CFG->dirroot . '/tag/lib.php'); require_once($CFG->dirroot . '/user/profile/lib.php'); require_once($CFG->libdir.'/filelib.php'); global $CFG, $PGAE; /******************* BY ANUSHA ************************ FOR HIDING LEFT SIDE NAVIGATION *********************/ $context = context_course::instance($COURSE->id); if (user_has_role_assignment($USER->id,5) ) { $PAGE->requires->css('/student/custom.css'); } $userid = optional_param('id', 0, PARAM_INT); $edit = optional_param('edit', null, PARAM_BOOL); // Turn editing on and off. $reset = optional_param('reset', null, PARAM_BOOL); $PAGE->set_url('/user/profile.php', array('id' => $userid)); if (!empty($CFG->forceloginforprofiles)) { require_login(); if (isguestuser()) { $PAGE->set_context(context_system::instance()); echo $OUTPUT->header(); echo $OUTPUT->confirm(get_string('guestcantaccessprofiles', 'error'), get_login_url(),
function authorize_process_csv($filename) { global $CFG, $SITE; /// We need these fields $myfields = array('Transaction ID', 'Transaction Status', 'Transaction Type', 'Settlement Amount', 'Settlement Currency', 'Settlement Date/Time', 'Authorization Amount', 'Authorization Currency', 'Submit Date/Time', 'Reference Transaction ID', 'Total Amount', 'Currency', 'Invoice Number', 'Customer ID'); /// Open the file and get first line $handle = fopen($filename, "r"); if (!$handle) { error('CANNOT OPEN CSV FILE'); } $firstline = fgetcsv($handle, 8192, ","); $numfields = count($firstline); if ($numfields != 49 && $numfields != 70) { @fclose($handle); error('INVALID CSV FILE; Each line must include 49 or 70 fields'); } /// Re-sort fields $csvfields = array(); foreach ($myfields as $myfield) { $csvindex = array_search($myfield, $firstline); if ($csvindex === false) { $csvfields = array(); break; } $csvfields[$myfield] = $csvindex; } if (empty($csvfields)) { @fclose($handle); error("<b>INVALID CSV FILE:</b> First line must include 'Header Fields' and\n the file must be type of <br />'Expanded Fields/Comma Separated'<br />or<br />\n 'Expanded Fields with CAVV Result Code/Comma Separated'"); } /// Read lines $sendem = array(); $ignoredlines = ''; $imported = 0; $updated = 0; $ignored = 0; while (($data = fgetcsv($handle, 8192, ",")) !== FALSE) { if (count($data) != $numfields) { $ignored++; // ignore empty lines continue; } $transid = $data[$csvfields['Transaction ID']]; $transtype = $data[$csvfields['Transaction Type']]; $transstatus = $data[$csvfields['Transaction Status']]; $reftransid = $data[$csvfields['Reference Transaction ID']]; $settlementdate = strtotime($data[$csvfields['Settlement Date/Time']]); if ($transstatus == 'Approved Review' || $transstatus == 'Review Failed') { if ($order = get_record('enrol_authorize', 'transid', $transid)) { $order->status = $transstatus == 'Approved Review' ? AN_STATUS_APPROVEDREVIEW : AN_STATUS_REVIEWFAILED; update_record('enrol_authorize', $order); $updated++; // Updated order status } continue; } if (!empty($reftransid) && is_numeric($reftransid) && 'Settled Successfully' == $transstatus && 'Credit' == $transtype) { if ($order = get_record('enrol_authorize', 'transid', $reftransid)) { if (AN_METHOD_ECHECK == $order->paymentmethod) { $refund = get_record('enrol_authorize_refunds', 'transid', $transid); if ($refund) { $refund->status = AN_STATUS_CREDIT; $refund->settletime = $settlementdate; update_record('enrol_authorize_refunds', $refund); $updated++; } else { $ignored++; $ignoredlines .= $reftransid . ": Not our business(Reference Transaction ID)\n"; } } } else { $ignored++; $ignoredlines .= $reftransid . ": Not our business(Transaction ID)\n"; } continue; } if (!($transstatus == 'Settled Successfully' && $transtype == 'Authorization w/ Auto Capture')) { $ignored++; $ignoredlines .= $transid . ": Not settled\n"; continue; } // TransactionId must match $order = get_record('enrol_authorize', 'transid', $transid); if (!$order) { $ignored++; $ignoredlines .= $transid . ": Not our business\n"; continue; } // Authorized/Captured and Settled $order->status = AN_STATUS_AUTHCAPTURE; $order->settletime = $settlementdate; update_record('enrol_authorize', $order); $updated++; // Updated order status and settlement date if ($order->paymentmethod != AN_METHOD_ECHECK) { $ignored++; $ignoredlines .= $transid . ": The method must be echeck\n"; continue; } // Get course and context $course = get_record('course', 'id', $order->courseid); if (!$course) { $ignored++; $ignoredlines .= $transid . ": Could not find this course: " . $order->courseid . "\n"; continue; } $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); if (!$coursecontext) { $ignored++; $ignoredlines .= $transid . ": Could not find course context: " . $order->courseid . "\n"; continue; } // Get user $user = get_record('user', 'id', $order->userid); if (!$user) { $ignored++; $ignoredlines .= $transid . ": Could not find this user: "******"\n"; continue; } // If user wasn't enrolled, enrol now. Ignore otherwise. Because admin user might submit this file again. if ($role = get_default_course_role($course)) { if (!user_has_role_assignment($user->id, $role->id, $coursecontext->id)) { $timestart = $timeend = 0; if ($course->enrolperiod) { $timestart = time(); $timeend = $timestart + $course->enrolperiod; } if (role_assign($role->id, $user->id, 0, $coursecontext->id, $timestart, $timeend, 0, 'authorize')) { $imported++; if (!empty($CFG->enrol_mailstudents)) { $sendem[] = $order->id; } } else { $ignoredlines .= $transid . ": Error while trying to enrol " . fullname($user) . " in '{$course->fullname}' \n"; } } } } fclose($handle); /// Send email to admin if (!empty($ignoredlines)) { $admin = get_admin(); email_to_user($admin, $admin, "{$SITE->fullname}: Authorize.net CSV ERROR LOG", $ignoredlines); } /// Send welcome messages to users if (!empty($sendem)) { send_welcome_messages($sendem); } /// Show result notice("<b>Done...</b><br />Imported: {$imported}<br />Updated: {$updated}<br />Ignored: {$ignored}"); }