Ejemplo n.º 1
0
 /**
  * Add a member to the cohort if they are not alread in the cohort
  *
  * @param int $userid id from user table of user
  * @return void
  */
 public function add_member($userid)
 {
     if (!isset($this->members[$userid])) {
         cohort_add_member($this->cohort->id, $userid);
         $this->members[$userid] = $userid;
     }
 }
Ejemplo n.º 2
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/cohort/lib.php';
     require_once $CFG->dirroot . '/enrol/cohort/locallib.php';
     foreach ($this->arguments as $argument) {
         $this->expandOptionsManually(array($argument));
         $options = $this->expandedOptions;
         // Sanity Checks.
         // Check if cohorst exists.
         if (!($cohorts = $DB->get_records('cohort', array('name' => $argument)))) {
             echo "Cohort does not exist\n";
             exit(0);
         }
         // Check if enough arguments.
         if (empty($options['courseid']) && empty($options['userid'])) {
             echo "Not enough arguments, provide userid or courseid\n";
         }
         // Check if course exists.
         $course = '';
         if (!empty($options['courseid'])) {
             if (!($course = $DB->get_record('course', array('id' => $options['courseid'])))) {
                 echo "Course does not exist\n";
                 exit(0);
             }
         }
         // Check if user exists.
         if (!empty($options['userid'])) {
             if (!($user = $DB->get_record('user', array('id' => $options['userid'])))) {
                 echo "User does not exist\n";
                 exit(0);
             }
         }
         // Add cohort to course
         if (!empty($course)) {
             foreach ($cohorts as $cohort) {
                 // Check if cohort enrolment already exists
                 if ($cohortenrolment = $DB->get_record('enrol', array('customint1' => $cohort->id, 'courseid' => $options['courseid']))) {
                     echo " Notice: Cohort already enrolled into course\n";
                 } else {
                     $enrol = enrol_get_plugin('cohort');
                     $studentrole = $DB->get_record('role', array('shortname' => 'student'));
                     $enrol->add_instance($course, array('name' => $argument . '_sync', 'status' => 0, 'customint1' => $cohort->id, 'roleid' => $studentrole->id, 'customint2' => '0'));
                     echo "Cohort enrolled\n";
                 }
                 $this->enrol_cohort_sync($course->id);
             }
         }
         if (!empty($user)) {
             foreach ($cohorts as $cohort) {
                 cohort_add_member($cohort->id, $options['userid']);
                 echo "User enrolled\n";
                 if (!empty($course)) {
                     $this->enrol_cohort_sync($course->id);
                 }
             }
         }
     }
 }
 /**
  * @runInSeparateProcess
  */
 public function test_report()
 {
     $this->resetAfterTest(true);
     $user = $this->getDataGenerator()->create_user();
     $this->adduser($user->id);
     $this->setUser($user);
     $course = $this->getDataGenerator()->create_course();
     $cohort = $this->getDataGenerator()->create_cohort(array('idnumber' => 1234.56789));
     cohort_add_member($cohort->id, $user->id);
     G\addtermid('1234');
     $this->enroluserincourse($course, $cohort, 'teacher');
     $user2 = $this->getDataGenerator()->create_user();
     $this->adduser($user2->id);
     $user3 = $this->getDataGenerator()->create_user();
     $this->adduser($user3->id);
     $user4 = $this->getDataGenerator()->create_user();
     $this->adduser($user4->id);
     $cohort2 = $this->getDataGenerator()->create_cohort(array('idnumber' => 9876.54321));
     cohort_add_member($cohort2->id, $user2->id);
     cohort_add_member($cohort2->id, $user3->id);
     cohort_add_member($cohort2->id, $user4->id);
     G\addtermid('9876');
     $this->enroluserincourse($course, $cohort2, 'student');
     $year = date("Y");
     $sem = G\semOfDate(date("d"), date("m"));
     G\newassessment($user3->id, time(), 121, $sem, "Student");
     $students = G\studentsofcourse($course->id);
     $numofstudents = count($students);
     $numofstudentsdoneassessment = 0;
     if (count($students) > 0) {
         foreach ($students as $studentid) {
             if (G\doneassessment($studentid, $sem, $year)) {
                 $numofstudentsdoneassessment++;
             }
         }
     }
     $this->assertEquals(3, $numofstudents);
     $this->assertEquals(1, $numofstudentsdoneassessment);
 }
 /**
  * @runInSeparateProcess
  */
 public function test_student_courses()
 {
     $this->resetAfterTest(true);
     $user = $this->getDataGenerator()->create_user();
     $row = array();
     $row['user_id'] = $user->id;
     $row['email'] = null;
     $row['timestamp'] = time();
     G\addvaliduser($row);
     $this->setUser($user);
     $course = $this->getDataGenerator()->create_course();
     $cohort = $this->getDataGenerator()->create_cohort(array('idnumber' => 1234.56789));
     cohort_add_member($cohort->id, $user->id);
     G\addtermid('1234');
     $enrol = enrol_get_plugin('cohort');
     $instance = array();
     $instance['name'] = 'name';
     $instance['status'] = ENROL_INSTANCE_ENABLED;
     // Enable it.
     $instance['customint1'] = $cohort->id;
     // Used to store the cohort id.
     $instance['roleid'] = $enrol->get_config('roleid');
     // Default role for cohort enrol which is usually student.
     $instance['customint2'] = 0;
     // Optional group id.
     $enrol->add_instance($course, $instance);
     $trace = new null_progress_trace();
     enrol_cohort_sync($trace, $course->id);
     $trace->finished();
     $courses = G\coursesas($user->id, 'student');
     $courseids = array();
     foreach ($courses as $newcourse) {
         array_push($courseids, $newcourse->id);
     }
     $this->assertContains($course->id, $courseids);
 }
Ejemplo n.º 5
0
 public function __CreateUser($username, $password, $firstname, $lastname, $email, $city, $country, $store, $retailer, $lang, $regionkey, $jobtitle, $insertflag, $other)
 {
     global $CFG, $DB;
     $systemcontext = context_system::instance();
     require_once $CFG->dirroot . '/cohort/locallib.php';
     // cohort members added courses.
     $response = new CliniqueServiceResponce();
     $flag = true;
     $popupflag = true;
     $user_exits = array_values($DB->get_records_sql("SELECT count(*) as totaluser FROM {user} WHERE username='******'"));
     $user_email_exists = array_values($DB->get_records_sql("SELECT count(*) as totalemail FROM {user} WHERE email='{$email}'"));
     $regionkey_check = array_values($DB->get_records_sql("SELECT count(*) as Regkeyexists FROM {regionkey} WHERE regionkey='{$regionkey}' AND region='{$city}'"));
     $userDetails = new stdClass();
     // $password = "******";
     if ($user_exits[0]->totaluser > 0) {
         $response->response(true, 'msg', "username_exists");
         $flag = false;
         $popupflag = false;
         exit;
     }
     /*if($user_email_exists[0]->totalemail > 0){
     
                      $response->response(true, 'msg', "email_exists");
     				 $flag=false;
     				 $popupflag = false;
     				 exit;
     
     			}*/
     if ($regionkey_check['0']->regkeyexists == 0) {
         $response->response(true, 'msg', "regionkey_not_exists");
         $flag = false;
         $popupflag = false;
         exit;
     }
     if ($popupflag && $insertflag == 'false') {
         $response->response(false, 'msg', "show_popup");
         $flag = false;
         exit;
     }
     if ($flag && $insertflag == 'true') {
         $userDetails->auth = 'email';
         $userDetails->confirmed = '1';
         $userDetails->mnethostid = '1';
         $userDetails->descriptionformat = '1';
         $userDetails->descriptionformat = '1';
         $userDetails->username = $username;
         $password = base64_decode($password);
         $md5pass_val = array("id" => "md5");
         if (!empty($CFG->passwordsaltmain)) {
             $newpass = $password . $CFG->passwordsaltmain;
             $user_pass = array_values($DB->get_records_all_sql("SELECT md5('{$newpass}') as password", $md5pass_val));
             $userDetails->password = $user_pass[0]->password;
         } else {
             $userDetails->password = md5($password);
         }
         $userDetails->firstname = $firstname;
         $userDetails->lastname = $lastname;
         $userDetails->email = $email;
         $userDetails->city = $city;
         $userDetails->country = $country;
         if ($lang == 'zh_ct') {
             $userDetails->lang = 'zh_cn';
         } else {
             $userDetails->lang = $lang;
         }
         $userDetails->timecreated = time();
         $userDetails->timemodified = time();
         //$userDetails->store=$store;
         //$userDetails->retailer=$retailer;
         $userDetails->descriptionformat = '1';
         $lastinsertid = $DB->insert_record('user', $userDetails);
         $cohortid = array_values($DB->get_records_sql("SELECT id FROM {cohort} WHERE idnumber='{$lang}'"));
         $cohortDetails = new stdClass();
         $cohortDetails->cohortid = $cohortid[0]->id;
         $cohortDetails->userid = $lastinsertid;
         $cohortDetails->timeadded = time();
         // if($userDetails->lang == COUNTER_MANAGER_ISO) {
         // cohort_add_member(US_ENGLISH, $lastinsertid);
         // }
         cohort_add_member($cohortid[0]->id, $lastinsertid);
         //$DB->insert_record('cohort_members',$cohortDetails);
         if ($other) {
             $cascade_data = new stdClass();
             $get_country = $DB->get_record('country', array('country_code' => $country));
             $cascade_data->region = $city;
             $cascade_data->country = $get_country->country_name;
             $cascade_data->retailer = $retailer;
             $cascade_data->store = $store;
             $cascade_insert_id = $DB->insert_record('cascade_region', $cascade_data);
         }
         if ($store != '' && !empty($store)) {
             $storeId = array_values($DB->get_records_sql("SELECT id FROM {user_info_field} WHERE shortname='Store'"));
             //Store,
             $user_info_data->fieldid = $storeId['0']->id;
             $user_info_data->userid = $lastinsertid;
             $user_info_data->data = $store;
             $DB->insert_record('user_info_data', $user_info_data);
         }
         if ($retailer != '' && !empty($retailer)) {
             //Retailer
             $retailerId = array_values($DB->get_records_sql("SELECT id FROM {user_info_field} WHERE shortname='Retailer'"));
             //Retailer
             $user_info_data->fieldid = $retailerId['0']->id;
             $user_info_data->userid = $lastinsertid;
             $user_info_data->data = $retailer;
             $DB->insert_record('user_info_data', $user_info_data);
         }
         if ($city != '' && !empty($city)) {
             // Region insert query
             $regionId = array_values($DB->get_records_sql("SELECT id FROM {user_info_field} WHERE shortname='Region'"));
             //Region
             $user_info_data->fieldid = $regionId['0']->id;
             $user_info_data->userid = $lastinsertid;
             $user_info_data->data = $city;
             $DB->insert_record('user_info_data', $user_info_data);
         }
         if ($jobtitle != '' && !empty($jobtitle)) {
             // Region insert query
             $jobtitleId = array_values($DB->get_records_sql("SELECT id FROM {user_info_field} WHERE shortname='JobTitle'"));
             //JobTitle
             $user_info_data->fieldid = $jobtitleId['0']->id;
             $user_info_data->userid = $lastinsertid;
             $user_info_data->data = $jobtitle;
             $DB->insert_record('user_info_data', $user_info_data);
         } else {
             $jobtitleId = array_values($DB->get_records_sql("SELECT id FROM {user_info_field} WHERE shortname='JobTitle'"));
             //JobTitle
             $user_info_data->fieldid = $jobtitleId['0']->id;
             $user_info_data->userid = $lastinsertid;
             $user_info_data->data = 0;
             $DB->insert_record('user_info_data', $user_info_data);
         }
         if ($lastinsertid) {
             $response->response(false, 'msg', "Added user successfully");
         } else {
             $response->response(true, 'msg', "Error in creating user");
         }
     }
     /* if(!empty($responseArray)){
     			 $response->response(false, 'done', $responseArray);
     		 } else{
     			$response->response(true, 'msg', "No records");
     		 }*/
 }
Ejemplo n.º 6
0
 private function process_cohort_membership_node($membershipnode, $xpath, $subtractive = 0)
 {
     global $DB, $CFG;
     $members = $xpath->evaluate("member", $membershipnode);
     $idnumber = $xpath->evaluate("sourcedid/id", $membershipnode)->item(0);
     if ($idnumber) {
         $ship = new stdClass();
         $ship->coursecode = $idnumber->nodeValue;
         if ($ship->courseid = $DB->get_field('cohort', 'id', array('idnumber' => $ship->coursecode))) {
             $cohortrec = $DB->get_fieldset_select('cohort_members', 'userid', 'cohortid=' . $ship->courseid);
             $curlist = array_flip($cohortrec);
             foreach ($members as $mmember) {
                 $midnumber = new stdClass();
                 $midnumber = $xpath->evaluate("sourcedid/id", $mmember)->item(0);
                 if ($midnumber) {
                     $member = new stdClass();
                     $member->idnumber = $midnumber->nodeValue;
                     $userid = $DB->get_field('user', 'id', array('idnumber' => $member->idnumber));
                     $latestlist[$userid] = $userid;
                     if (!isset($curlist[$userid])) {
                         if ($userid != 0 && $userid != '') {
                             cohort_add_member($ship->courseid, $userid);
                         }
                     }
                 }
             }
             if ($subtractive == 1) {
                 foreach ($cohortrec as $curmember) {
                     if (!isset($latestlist[$curmember])) {
                         cohort_remove_member($ship->courseid, $curmember);
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 7
0
 public function test_cohort_get_available_cohorts()
 {
     global $DB;
     $this->resetAfterTest();
     $category1 = $this->getDataGenerator()->create_category();
     $category2 = $this->getDataGenerator()->create_category();
     $course1 = $this->getDataGenerator()->create_course(array('category' => $category1->id));
     $course2 = $this->getDataGenerator()->create_course(array('category' => $category2->id));
     $category1ctx = context_coursecat::instance($category1->id);
     $category2ctx = context_coursecat::instance($category2->id);
     $course1ctx = context_course::instance($course1->id);
     $course2ctx = context_course::instance($course2->id);
     $systemctx = context_system::instance();
     $cohort1 = $this->getDataGenerator()->create_cohort(array('contextid' => $category1ctx->id, 'name' => 'aaagrrryyy', 'idnumber' => '', 'description' => ''));
     $cohort2 = $this->getDataGenerator()->create_cohort(array('contextid' => $category1ctx->id, 'name' => 'bbb', 'idnumber' => '', 'description' => 'yyybrrr', 'visible' => 0));
     $cohort3 = $this->getDataGenerator()->create_cohort(array('contextid' => $category2ctx->id, 'name' => 'ccc', 'idnumber' => 'xxarrrghyyy', 'description' => 'po_us'));
     $cohort4 = $this->getDataGenerator()->create_cohort(array('contextid' => $systemctx->id, 'name' => 'ddd'));
     $cohort5 = $this->getDataGenerator()->create_cohort(array('contextid' => $systemctx->id, 'visible' => 0, 'name' => 'eee'));
     /*
     Structure of generated course categories, courses and cohort:
     
     system
       -cohort4 (visible, has 3 members)
       -cohort5 (not visible, no members)
       category1
         -cohort1 (visible, no members)
         -cohort2 (not visible, has 1 member)
         course1
       category2
         -cohort3 (visible, has 2 member)
         course2
     
     In this test we call cohort_get_available_cohorts() for users with different roles
     and with different paramteres ($withmembers, $search, $offset, $limit) to make sure we go
     through all possible options of SQL query.
     */
     // Admin can see visible and invisible cohorts defined in above contexts.
     $this->setAdminUser();
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 0, 0, '');
     $this->assertEquals(array($cohort1->id, $cohort2->id, $cohort4->id, $cohort5->id), array_keys($result));
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 0, 2, '');
     $this->assertEquals(array($cohort1->id, $cohort2->id), array_keys($result));
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 1, 2, '');
     $this->assertEquals(array($cohort2->id, $cohort4->id), array_keys($result));
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 0, 100, 'yyy');
     $this->assertEquals(array($cohort1->id, $cohort2->id), array_keys($result));
     $result = cohort_get_available_cohorts($course2ctx, COHORT_ALL, 0, 0, '');
     $this->assertEquals(array($cohort3->id, $cohort4->id, $cohort5->id), array_keys($result));
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_MEMBERS_ONLY);
     $this->assertEmpty($result);
     $result = cohort_get_available_cohorts($course2ctx, COHORT_WITH_MEMBERS_ONLY);
     $this->assertEmpty($result);
     // Get list of available cohorts as a teacher in the course.
     $user1 = $this->getDataGenerator()->create_user();
     $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
     role_assign($teacherrole->id, $user1->id, $course1ctx->id);
     role_assign($teacherrole->id, $user1->id, $course2ctx->id);
     $this->setUser($user1);
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 0, 0, '');
     $this->assertEquals(array($cohort1->id, $cohort4->id), array_keys($result));
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 0, 1, '');
     $this->assertEquals(array($cohort1->id), array_keys($result));
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 1, 1, '');
     $this->assertEquals(array($cohort4->id), array_keys($result));
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 0, 100, 'yyy');
     $this->assertEquals(array($cohort1->id), array_keys($result));
     $result = cohort_get_available_cohorts($course2ctx, COHORT_ALL, 0, 0, '');
     $this->assertEquals(array($cohort3->id, $cohort4->id), array_keys($result));
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_MEMBERS_ONLY);
     $this->assertEmpty($result);
     // Now add members to cohorts.
     $user2 = $this->getDataGenerator()->create_user();
     $user3 = $this->getDataGenerator()->create_user();
     $user4 = $this->getDataGenerator()->create_user();
     $user5 = $this->getDataGenerator()->create_user();
     $user6 = $this->getDataGenerator()->create_user();
     cohort_add_member($cohort2->id, $user3->id);
     cohort_add_member($cohort3->id, $user2->id);
     cohort_add_member($cohort3->id, $user3->id);
     cohort_add_member($cohort4->id, $user4->id);
     cohort_add_member($cohort4->id, $user5->id);
     cohort_add_member($cohort4->id, $user6->id);
     // Check filtering non-empty cohorts as admin.
     $this->setAdminUser();
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_MEMBERS_ONLY, 0, 0, '');
     $this->assertEquals(array($cohort2->id, $cohort4->id), array_keys($result));
     $this->assertEquals(1, $result[$cohort2->id]->memberscnt);
     $this->assertEquals(3, $result[$cohort4->id]->memberscnt);
     $result = cohort_get_available_cohorts($course2ctx, COHORT_WITH_MEMBERS_ONLY, 0, 0, '');
     $this->assertEquals(array($cohort3->id, $cohort4->id), array_keys($result));
     $this->assertEquals(2, $result[$cohort3->id]->memberscnt);
     $this->assertEquals(3, $result[$cohort4->id]->memberscnt);
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_MEMBERS_ONLY, 0, 0, 'yyy');
     $this->assertEquals(array($cohort2->id), array_keys($result));
     $this->assertEquals(1, $result[$cohort2->id]->memberscnt);
     // Check filtering non-empty cohorts as teacher.
     $this->setUser($user1);
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_MEMBERS_ONLY, 0, 0, '');
     $this->assertEquals(array($cohort4->id), array_keys($result));
     $this->assertEquals(3, $result[$cohort4->id]->memberscnt);
     $result = cohort_get_available_cohorts($course2ctx, COHORT_WITH_MEMBERS_ONLY, 0, 0, '');
     $this->assertEquals(array($cohort3->id, $cohort4->id), array_keys($result));
     $this->assertEquals(2, $result[$cohort3->id]->memberscnt);
     $this->assertEquals(3, $result[$cohort4->id]->memberscnt);
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_MEMBERS_ONLY, 0, 0, 'yyy');
     $this->assertEmpty($result);
     // Enrol users.
     $studentrole = $DB->get_record('role', array('shortname' => 'student'));
     $this->getDataGenerator()->enrol_user($user2->id, $course1->id, $studentrole->id);
     $this->getDataGenerator()->enrol_user($user3->id, $course1->id, $studentrole->id);
     $this->getDataGenerator()->enrol_user($user5->id, $course1->id, $studentrole->id);
     $this->getDataGenerator()->enrol_user($user6->id, $course1->id, $studentrole->id);
     $this->getDataGenerator()->enrol_user($user3->id, $course2->id, $studentrole->id);
     $this->getDataGenerator()->enrol_user($user4->id, $course2->id, $studentrole->id);
     $this->getDataGenerator()->enrol_user($user5->id, $course2->id, $studentrole->id);
     $this->getDataGenerator()->enrol_user($user6->id, $course2->id, $studentrole->id);
     // Check cohorts with enrolments as admin.
     $this->setAdminUser();
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_ENROLLED_MEMBERS_ONLY, 0, 0, '');
     $this->assertEquals(array($cohort2->id, $cohort4->id), array_keys($result));
     $this->assertEquals(1, $result[$cohort2->id]->enrolledcnt);
     $this->assertEquals(2, $result[$cohort4->id]->enrolledcnt);
     $this->assertEquals(1, $result[$cohort2->id]->memberscnt);
     $this->assertEquals(3, $result[$cohort4->id]->memberscnt);
     $result = cohort_get_available_cohorts($course2ctx, COHORT_WITH_ENROLLED_MEMBERS_ONLY, 0, 0, '');
     $this->assertEquals(array($cohort3->id, $cohort4->id), array_keys($result));
     $this->assertEquals(1, $result[$cohort3->id]->enrolledcnt);
     $this->assertEquals(3, $result[$cohort4->id]->enrolledcnt);
     $this->assertEquals(2, $result[$cohort3->id]->memberscnt);
     $this->assertEquals(3, $result[$cohort4->id]->memberscnt);
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_ENROLLED_MEMBERS_ONLY, 0, 0, 'yyy');
     $this->assertEquals(array($cohort2->id), array_keys($result));
     $this->assertEquals(1, $result[$cohort2->id]->enrolledcnt);
     $this->assertEquals(1, $result[$cohort2->id]->memberscnt);
     $result = cohort_get_available_cohorts($course1ctx, COHORT_WITH_NOTENROLLED_MEMBERS_ONLY, 0, 0, '');
     $this->assertEquals(array($cohort4->id), array_keys($result));
     $this->assertEquals(2, $result[$cohort4->id]->enrolledcnt);
     $this->assertEquals(3, $result[$cohort4->id]->memberscnt);
     // Assign user1 additional 'manager' role in the category context. He can now see hidden cohort in category1
     // but still can not see hidden category in system.
     $managerrole = $DB->get_record('role', array('shortname' => 'manager'));
     role_assign($managerrole->id, $user1->id, context_coursecat::instance($category1->id));
     $this->setUser($user1);
     $result = cohort_get_available_cohorts($course1ctx, COHORT_ALL, 0, 0, '');
     $this->assertEquals(array($cohort1->id, $cohort2->id, $cohort4->id), array_keys($result));
 }
Ejemplo n.º 8
0
 /**
  * cron synchronization script
  *
  * @param int $do_updates true to update existing accounts
  *
  * @return int       
  */
 function sync_users($do_updates = false)
 {
     global $CFG, $DB;
     // process users in Moodle that no longer exist in Drupal
     $remote_user = $this->config->remote_user;
     $remote_pw = $this->config->remote_pw;
     $base_url = $this->config->host_uri;
     $apiObj = new RemoteAPI($base_url);
     // Required for authentication, and all other operations:
     $ret = $apiObj->Login($remote_user, $remote_pw, true);
     if ($ret->info['http_code'] == 404) {
         die("ERROR: Login service unreachable!\n");
     }
     if ($ret->info['http_code'] == 401) {
         die("ERROR: Login failed - check username and password!\n");
     } elseif ($ret->info['http_code'] !== 200) {
         $error = "ERROR: Login to drupal failed with http code " . $ret->info['http_code'];
         if (!empty($ret->error)) {
             $error .= PHP_EOL . $ret->error . PHP_EOL;
         }
         die($error);
     }
     // list external users since last update
     $vid = isset($this->config->last_vid) ? $this->config->last_vid : 0;
     $pagesize = $this->config->pagesize;
     $page = 0;
     $drupal_users = $apiObj->Index('user', "?vid={$vid},page={$page},pagesize={$pagesize}");
     if (is_null($drupal_users) || empty($drupal_users)) {
         die("ERROR: Problems trying to get index of users!\n");
     }
     // sync users in Drupal with users in Moodle (adding users if needed)
     print_string('auth_drupalservicesuserstoupdate', 'auth_drupalservices', count($drupal_users));
     foreach ($drupal_users as $drupal_user_info) {
         // get the full user object rather than the prototype from the index service
         // merge the listing and the full value because if the user is blocked, a full user will not be retrieved
         $drupal_user = (array) $drupal_user_info + (array) $apiObj->Index("user/{$drupal_user_info->uid}");
         // recast drupaluser as an object
         $drupal_user = (object) $drupal_user;
         // the drupal services module strips off the mail attribute if the user requested is not
         // either the user requesting, or a user with administer users permission.
         // luckily the updates service has the value, so we have to copy it over.
         $drupal_user->mail = $drupal_user_info->mail;
         if ($drupal_user_info->uid < 1) {
             //No anon
             print "Skipping anon user - uid {$drupal_user->uid}\n";
             continue;
         }
         print_string('auth_drupalservicesupdateuser', 'auth_drupalservices', array($drupal_user->name . '(' . $drupal_user->uid . ')'));
         $user = $this->create_update_user($drupal_user);
         if (empty($user)) {
             // Something went wrong while creating the user
             print_error('auth_drupalservicescreateaccount', 'auth_drupalservices', array($drupal_user->name));
             continue;
             //Next user
         }
     }
     // now that all the latest updates have been imported, store the revision point we are at.
     set_config('last_vid', $drupal_user->vid, 'auth_drupalservices');
     // Now do cohorts
     if ($this->config->cohorts != 0) {
         $cohort_view = $this->config->cohort_view;
         print "Updating cohorts using services view - {$cohort_view}\n";
         $context = context_system::instance();
         //$processed_cohorts_list = array();
         $drupal_cohorts = $apiObj->Index($cohort_view);
         if (is_null($drupal_cohorts)) {
             print "ERROR: Error retreiving cohorts!\n";
         } else {
             // OK First lets create any Moodle cohorts that are in drupal.
             foreach ($drupal_cohorts as $drupal_cohort) {
                 if ($drupal_cohort->cohort_name == '') {
                     continue;
                     // We don't want an empty cohort name
                 }
                 $drupal_cohort_list[] = $drupal_cohort->cohort_name;
                 if (!$this->cohort_exists($drupal_cohort->cohort_name)) {
                     $newcohort = new stdClass();
                     $newcohort->name = $drupal_cohort->cohort_name;
                     $newcohort->idnumber = $drupal_cohort->cohort_id;
                     $newcohort->description = $drupal_cohort->cohort_description;
                     $newcohort->contextid = $context->id;
                     $newcohort->component = 'auth_drupalservices';
                     $cid = cohort_add_cohort($newcohort);
                     print "Cohort {$drupal_cohort->cohort_name} ({$cid}) created!\n";
                 }
             }
             // Next lets delete any Moodle cohorts that are not in drupal.
             // Now create a unique array
             $drupal_cohort_list = array_unique($drupal_cohort_list);
             //print_r($drupal_cohort_list);
             $moodle_cohorts = $this->moodle_cohorts();
             //print_r($moodle_cohorts);
             foreach ($moodle_cohorts as $moodle_cohort) {
                 if (array_search($moodle_cohort->name, $drupal_cohort_list) === false) {
                     print "{$moodle_cohort->name} not in drupal - deleteing\n";
                     cohort_delete_cohort($moodle_cohort);
                 }
                 $moodle_cohorts_list[$moodle_cohort->id] = $moodle_cohort->name;
             }
             // Cool. Now lets go through each user and add them to cohorts.
             // arrays to use? $userlist - list of uids.
             // $drupal_cohorts - view. $drupal_cohorts_list. Moodle lists.
             foreach ($userlist as $uid) {
                 $drupal_user_cohort_list = array();
                 //print "$uid\n";
                 $user = $DB->get_record('user', array('idnumber' => $uid, 'mnethostid' => $CFG->mnet_localhost_id));
                 // Get array of cohort names this user belongs to.
                 $drupal_user_cohorts = $this->drupal_user_cohorts($uid, $drupal_cohorts);
                 foreach ($drupal_user_cohorts as $drupal_user_cohort) {
                     //get the cohort id frm the moodle list.
                     $cid = array_search($drupal_user_cohort->cohort_name, $moodle_cohorts_list);
                     //print "$cid\n";
                     if (!$DB->record_exists('cohort_members', array('cohortid' => $cid, 'userid' => $user->id))) {
                         cohort_add_member($cid, $user->id);
                         print "Added {$user->username} ({$user->id}) to cohort {$drupal_user_cohort->cohort_name}\n";
                     }
                     // Create a list of enrolled cohorts to use later.
                     $drupal_user_cohort_list[] = $cid;
                 }
                 // Cool. now get this users list of moodle cohorts and compare
                 // with drupal. remove from moodle if needed.
                 $moodle_user_cohorts = $this->moodle_user_cohorts($user);
                 //print_r($moodle_user_cohorts);
                 foreach ($moodle_user_cohorts as $moodle_user_cohort) {
                     if (array_search($moodle_user_cohort->cid, $drupal_user_cohort_list) === false) {
                         cohort_remove_member($moodle_user_cohort->cid, $user->id);
                         print "Removed {$user->username} ({$user->id}) from cohort {$moodle_user_cohort->name}\n";
                     }
                 }
             }
         }
     }
     // End of cohorts
     //LOGOUT
     if (get_config('auth_drupalservices', 'call_logout_service')) {
         $ret = $apiObj->Logout();
         if (is_null($ret)) {
             print "ERROR logging out!\n";
         } else {
             print "Logged out from drupal services\n";
         }
     }
 }
Ejemplo n.º 9
0
    $user->fullname = fullname($user, true);
    $user->country = @$countries[$user->country];
    unset($user->firstname);
    unset($user->lastname);
    $users[$key] = $user;
}
unset($countries);
$mform = new user_bulk_cohortadd_form(null, $cohorts);
if (empty($users) or $mform->is_cancelled()) {
    redirect(new moodle_url('/admin/user/user_bulk.php'));
} else {
    if ($data = $mform->get_data()) {
        // process request
        foreach ($users as $user) {
            if (!$DB->record_exists('cohort_members', array('cohortid' => $data->cohort, 'userid' => $user->id))) {
                cohort_add_member($data->cohort, $user->id);
            }
        }
        redirect(new moodle_url('/admin/user/user_bulk.php'));
    }
}
// Need to sort by date
function sort_compare($a, $b)
{
    global $sort, $dir;
    if ($sort == 'lastaccess') {
        $rez = $b->lastaccess - $a->lastaccess;
    } else {
        $rez = strcasecmp(@$a->{$sort}, @$b->{$sort});
    }
    return $dir == 'desc' ? -$rez : $rez;
Ejemplo n.º 10
0
 function add_cohort_member($username, $cohort_id)
 {
     global $CFG, $DB;
     $username = utf8_decode($username);
     $username = strtolower($username);
     $conditions = array('username' => $username);
     $user = $DB->get_record('user', $conditions);
     if (!$user) {
         return 0;
     }
     $conditions = array('userid' => $user->id, 'cohortid' => $cohort_id);
     $member = $DB->get_record('cohort_members', $conditions);
     if ($member) {
         return 0;
     }
     cohort_add_member($cohort_id, $user->id);
     return 1;
 }
Ejemplo n.º 11
0
 public function test_show_enrolme_link()
 {
     global $DB, $CFG;
     $this->resetAfterTest();
     $this->preventResetByRollback();
     // Messaging does not like transactions...
     /** @var $selfplugin enrol_self_plugin */
     $selfplugin = enrol_get_plugin('self');
     $user1 = $this->getDataGenerator()->create_user();
     $user2 = $this->getDataGenerator()->create_user();
     $studentrole = $DB->get_record('role', array('shortname' => 'student'));
     $this->assertNotEmpty($studentrole);
     $course1 = $this->getDataGenerator()->create_course();
     $course2 = $this->getDataGenerator()->create_course();
     $course3 = $this->getDataGenerator()->create_course();
     $course4 = $this->getDataGenerator()->create_course();
     $course5 = $this->getDataGenerator()->create_course();
     $course6 = $this->getDataGenerator()->create_course();
     $course7 = $this->getDataGenerator()->create_course();
     $course8 = $this->getDataGenerator()->create_course();
     $course9 = $this->getDataGenerator()->create_course();
     $course10 = $this->getDataGenerator()->create_course();
     $course11 = $this->getDataGenerator()->create_course();
     $cohort1 = $this->getDataGenerator()->create_cohort();
     $cohort2 = $this->getDataGenerator()->create_cohort();
     // New enrolments are allowed and enrolment instance is enabled.
     $instance1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance1->customint6 = 1;
     $DB->update_record('enrol', $instance1);
     $selfplugin->update_status($instance1, ENROL_INSTANCE_ENABLED);
     // New enrolments are not allowed, but enrolment instance is enabled.
     $instance2 = $DB->get_record('enrol', array('courseid' => $course2->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance2->customint6 = 0;
     $DB->update_record('enrol', $instance2);
     $selfplugin->update_status($instance2, ENROL_INSTANCE_ENABLED);
     // New enrolments are allowed , but enrolment instance is disabled.
     $instance3 = $DB->get_record('enrol', array('courseid' => $course3->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance3->customint6 = 1;
     $DB->update_record('enrol', $instance3);
     $selfplugin->update_status($instance3, ENROL_INSTANCE_DISABLED);
     // New enrolments are not allowed and enrolment instance is disabled.
     $instance4 = $DB->get_record('enrol', array('courseid' => $course4->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance4->customint6 = 0;
     $DB->update_record('enrol', $instance4);
     $selfplugin->update_status($instance4, ENROL_INSTANCE_DISABLED);
     // Cohort member test.
     $instance5 = $DB->get_record('enrol', array('courseid' => $course5->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance5->customint6 = 1;
     $instance5->customint5 = $cohort1->id;
     $DB->update_record('enrol', $instance1);
     $selfplugin->update_status($instance5, ENROL_INSTANCE_ENABLED);
     $id = $selfplugin->add_instance($course5, $selfplugin->get_instance_defaults());
     $instance6 = $DB->get_record('enrol', array('id' => $id), '*', MUST_EXIST);
     $instance6->customint6 = 1;
     $instance6->customint5 = $cohort2->id;
     $DB->update_record('enrol', $instance1);
     $selfplugin->update_status($instance6, ENROL_INSTANCE_ENABLED);
     // Enrol start date is in future.
     $instance7 = $DB->get_record('enrol', array('courseid' => $course6->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance7->customint6 = 1;
     $instance7->enrolstartdate = time() + 60;
     $DB->update_record('enrol', $instance7);
     $selfplugin->update_status($instance7, ENROL_INSTANCE_ENABLED);
     // Enrol start date is in past.
     $instance8 = $DB->get_record('enrol', array('courseid' => $course7->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance8->customint6 = 1;
     $instance8->enrolstartdate = time() - 60;
     $DB->update_record('enrol', $instance8);
     $selfplugin->update_status($instance8, ENROL_INSTANCE_ENABLED);
     // Enrol end date is in future.
     $instance9 = $DB->get_record('enrol', array('courseid' => $course8->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance9->customint6 = 1;
     $instance9->enrolenddate = time() + 60;
     $DB->update_record('enrol', $instance9);
     $selfplugin->update_status($instance9, ENROL_INSTANCE_ENABLED);
     // Enrol end date is in past.
     $instance10 = $DB->get_record('enrol', array('courseid' => $course9->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance10->customint6 = 1;
     $instance10->enrolenddate = time() - 60;
     $DB->update_record('enrol', $instance10);
     $selfplugin->update_status($instance10, ENROL_INSTANCE_ENABLED);
     // Maximum enrolments reached.
     $instance11 = $DB->get_record('enrol', array('courseid' => $course10->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance11->customint6 = 1;
     $instance11->customint3 = 1;
     $DB->update_record('enrol', $instance11);
     $selfplugin->update_status($instance11, ENROL_INSTANCE_ENABLED);
     $selfplugin->enrol_user($instance11, $user2->id, $studentrole->id);
     // Maximum enrolments not reached.
     $instance12 = $DB->get_record('enrol', array('courseid' => $course11->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance12->customint6 = 1;
     $instance12->customint3 = 1;
     $DB->update_record('enrol', $instance12);
     $selfplugin->update_status($instance12, ENROL_INSTANCE_ENABLED);
     $this->setUser($user1);
     $this->assertTrue($selfplugin->show_enrolme_link($instance1));
     $this->assertFalse($selfplugin->show_enrolme_link($instance2));
     $this->assertFalse($selfplugin->show_enrolme_link($instance3));
     $this->assertFalse($selfplugin->show_enrolme_link($instance4));
     $this->assertFalse($selfplugin->show_enrolme_link($instance7));
     $this->assertTrue($selfplugin->show_enrolme_link($instance8));
     $this->assertTrue($selfplugin->show_enrolme_link($instance9));
     $this->assertFalse($selfplugin->show_enrolme_link($instance10));
     $this->assertFalse($selfplugin->show_enrolme_link($instance11));
     $this->assertTrue($selfplugin->show_enrolme_link($instance12));
     require_once "{$CFG->dirroot}/cohort/lib.php";
     cohort_add_member($cohort1->id, $user1->id);
     $this->assertTrue($selfplugin->show_enrolme_link($instance5));
     $this->assertFalse($selfplugin->show_enrolme_link($instance6));
 }
Ejemplo n.º 12
0
 public function test_sync_all_cohort_roles()
 {
     $this->setAdminUser();
     $params = (object) array('userid' => $this->userassignto->id, 'roleid' => $this->roleid, 'cohortid' => $this->cohort->id);
     $result = api::create_cohort_role_assignment($params);
     // Verify roles are assigned when users enter the cohort.
     $sync = api::sync_all_cohort_roles();
     $rolesadded = array(array('useridassignedto' => $this->userassignto->id, 'useridassignedover' => $this->userassignover->id, 'roleid' => $this->roleid));
     $rolesremoved = array();
     $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved);
     $this->assertEquals($sync, $expected);
     // Verify roles are removed when users leave the cohort.
     cohort_remove_member($this->cohort->id, $this->userassignover->id);
     $sync = api::sync_all_cohort_roles();
     $rolesadded = array();
     $rolesremoved = array(array('useridassignedto' => $this->userassignto->id, 'useridassignedover' => $this->userassignover->id, 'roleid' => $this->roleid));
     $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved);
     $this->assertEquals($sync, $expected);
     // Verify roles assigned by any other component are not removed.
     $usercontext = context_user::instance($this->userassignover->id);
     role_assign($this->roleid, $this->userassignto->id, $usercontext->id);
     $sync = api::sync_all_cohort_roles();
     $rolesadded = array();
     $rolesremoved = array();
     $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved);
     $this->assertEquals($sync, $expected);
     // Remove manual role assignment.
     role_unassign($this->roleid, $this->userassignto->id, $usercontext->id);
     // Add someone to the cohort again...
     cohort_add_member($this->cohort->id, $this->userassignover->id);
     $sync = api::sync_all_cohort_roles();
     $rolesadded = array(array('useridassignedto' => $this->userassignto->id, 'useridassignedover' => $this->userassignover->id, 'roleid' => $this->roleid));
     $rolesremoved = array();
     $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved);
     $this->assertEquals($sync, $expected);
     // Verify no fatal errors when a cohort is deleted.
     cohort_delete_cohort($this->cohort);
     $sync = api::sync_all_cohort_roles();
     $rolesadded = array();
     $rolesremoved = array(array('useridassignedto' => $this->userassignto->id, 'useridassignedover' => $this->userassignover->id, 'roleid' => $this->roleid));
     $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved);
     $this->assertEquals($sync, $expected);
 }
Ejemplo n.º 13
0
        $cohort->description = get_string('cohort_synchronized_with_group', 'local_ldap', $groupname);
        //print_r($cohort);
        $cohortid = cohort_add_cohort($cohort);
        print "creating cohort " . $group . PHP_EOL;
    } else {
        $cohortid = $cohort->id;
        $ldap_members = $plugin->ldap_get_group_members($groupname);
    }
    if ($CFG->debug_ldap_groupes) {
        pp_print_object("members of LDAP group {$groupname} known to Moodle", $ldap_members);
    }
    $cohort_members = $plugin->get_cohort_members($cohortid);
    if ($CFG->debug_ldap_groupes) {
        pp_print_object("current members of cohort {$groupname}", $cohort_members);
    }
    foreach ($cohort_members as $userid => $user) {
        if (!isset($ldap_members[$userid])) {
            cohort_remove_member($cohortid, $userid);
            print "removing " . $user->username . " from cohort " . $groupname . PHP_EOL;
        }
    }
    foreach ($ldap_members as $userid => $username) {
        if (!$plugin->cohort_is_member($cohortid, $userid)) {
            cohort_add_member($cohortid, $userid);
            print "adding " . $username . " to cohort " . $groupname . PHP_EOL;
        }
    }
    //break;
}
$difftime = microtime_diff($starttime, microtime());
print "Execution took " . $difftime . " seconds" . PHP_EOL;
Ejemplo n.º 14
0
function bulk_batch_enroll_existingstudents($cir, $data){
    
    
    global $CFG,$DB,$USER;
    require_once ($CFG->dirroot . '/group/lib.php');
    $returnurl = new moodle_url('/local/batches/bulk_enroll.php');
    $STD_FIELDS = array('userid', 'serviceid');

    $PRF_FIELDS = array();
   
    $result = '';
    
    $roleid = $data->roleassign;
    $useridfield = $data->firstcolumn;

    $enrollablecount = 0;
    $createdgroupscount = 0;
    $createdgroupingscount = 0;
    $createdgroups = '';
    $createdgroupings = '';
    
    $filecolumns = uu_validate_admission_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
    $upt = new uu_progress_tracker();
    $plugin = enrol_get_plugin('manual');
    // init csv import helper
    $cir->init();

    $linenum = 1;
    loop:
    while ($line = $cir->next()) {
    $result=''; $existsmail=0;
    
    $upt->flush();
    $linenum++;
    $existuser = new stdClass();
    // add fields to admission object
    foreach ($line as $keynum => $value) {
        if (!isset($filecolumns[$keynum])) {
            // this should not happen
            continue;
        }
        $key = $filecolumns[$keynum];
	
        $existuser->$key = $value;
    }
     $existuser->linenum = $linenum;
        $batchid= $data->batchid;
        

	if(empty($batchid)){	    
	    echo '<div class="alert alert-error">'.get_string('batchempty', 'local_batches'). '</div>';
            continue;	
	}
	
	if(empty($existuser->serviceid)){
	     echo '<div class="alert alert-error">'.get_string('provideserviceid', 'local_batches'). '</div>';
            continue;	 
	    
	}
	
	if(empty($existuser->userid)){
	     echo '<div class="alert alert-error">'.get_string('provideuserid', 'local_batches'). '</div>';
            continue;	 	    
	}
        
	if($existuser->userid){
	    if(!$DB->record_exists('local_userdata',array('userid'=>$existuser->userid))){
	    echo '<div class="alert alert-error">'.get_string('provideuserid', 'local_batches'). '</div>';
            continue;
		
	    }
	    
	    
	}
	
	
            
        if($DB->record_exists('cohort_members',array('userid'=>$existuser->userid, 'cohortid'=>$batchid))) {
        echo '<div class="alert alert-error">'.get_string('im:already_in', 'local_mass_enroll', fullname($user)). '</div>';

        } else {
               cohort_add_member($batchid, $existuser->userid);
	}    
    
    }// end of while   
} // end of function
Ejemplo n.º 15
0
 function sync_cohorts($cohorts, $userid)
 {
     global $DB;
     try {
         $queryparams = array($userid);
         $pattern = '/\\d{4}.\\d{5}/is';
         preg_match_all($pattern, str_replace(':', '.', $cohorts), $matches);
         list($insql, $inparams) = $DB->get_in_or_equal($matches[0]);
         $params = array_merge($queryparams, $inparams);
         $cohortsnotenroled = $DB->get_records_sql("select id from {cohort} where idnumber not in (select c.idnumber from {user} u, {cohort} c, {cohort_members} cm where u.id=?" . " and u.id=cm.userid and cm.cohortid=c.id ) and idnumber {$insql}", $params);
         foreach ($cohortsnotenroled as $cohort) {
             cohort_add_member($cohort->id, $userid);
         }
     } catch (moodle_exception $e) {
         error_log('Error in sync_cohorts for user ' . $userid);
         continue;
     }
 }
Ejemplo n.º 16
0
 /**
  * Add cohort members
  *
  * @param array $members of arrays with keys userid, cohortid
  * @since Moodle 2.5
  */
 public static function add_cohort_members($members)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . "/cohort/lib.php";
     $params = self::validate_parameters(self::add_cohort_members_parameters(), array('members' => $members));
     $transaction = $DB->start_delegated_transaction();
     $warnings = array();
     foreach ($params['members'] as $member) {
         // Cohort parameters.
         $cohorttype = $member['cohorttype'];
         $cohortparam = array($cohorttype['type'] => $cohorttype['value']);
         // User parameters.
         $usertype = $member['usertype'];
         $userparam = array($usertype['type'] => $usertype['value']);
         try {
             // Check parameters.
             if ($cohorttype['type'] != 'id' && $cohorttype['type'] != 'idnumber') {
                 $warning = array();
                 $warning['warningcode'] = '1';
                 $warning['message'] = 'invalid parameter: cohortype=' . $cohorttype['type'];
                 $warnings[] = $warning;
                 continue;
             }
             if ($usertype['type'] != 'id' && $usertype['type'] != 'username') {
                 $warning = array();
                 $warning['warningcode'] = '1';
                 $warning['message'] = 'invalid parameter: usertype=' . $usertype['type'];
                 $warnings[] = $warning;
                 continue;
             }
             // Extract parameters.
             if (!($cohortid = $DB->get_field('cohort', 'id', $cohortparam))) {
                 $warning = array();
                 $warning['warningcode'] = '2';
                 $warning['message'] = 'cohort ' . $cohorttype['type'] . '=' . $cohorttype['value'] . ' not exists';
                 $warnings[] = $warning;
                 continue;
             }
             if (!($userid = $DB->get_field('user', 'id', array_merge($userparam, array('deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id))))) {
                 $warning = array();
                 $warning['warningcode'] = '2';
                 $warning['message'] = 'user ' . $usertype['type'] . '=' . $usertype['value'] . ' not exists';
                 $warnings[] = $warning;
                 continue;
             }
             if ($DB->record_exists('cohort_members', array('cohortid' => $cohortid, 'userid' => $userid))) {
                 $warning = array();
                 $warning['warningcode'] = '3';
                 $warning['message'] = 'record already exists: cohort(' . $cohorttype['type'] . '=' . $cohorttype['value'] . ' ' . $usertype['type'] . '=' . $usertype['value'] . ')';
                 $warnings[] = $warning;
                 continue;
             }
             $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
             $context = context::instance_by_id($cohort->contextid, MUST_EXIST);
             if ($context->contextlevel != CONTEXT_COURSECAT and $context->contextlevel != CONTEXT_SYSTEM) {
                 $warning = array();
                 $warning['warningcode'] = '1';
                 $warning['message'] = 'Invalid context: ' . $context->contextlevel;
                 $warnings[] = $warning;
                 continue;
             }
             self::validate_context($context);
         } catch (Exception $e) {
             throw new moodle_exception('Error', 'cohort', '', $e->getMessage());
         }
         if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:assign'), $context)) {
             throw new required_capability_exception($context, 'moodle/cohort:assign', 'nopermissions', '');
         }
         cohort_add_member($cohortid, $userid);
     }
     $transaction->allow_commit();
     // Return.
     $result = array();
     $result['warnings'] = $warnings;
     return $result;
 }
Ejemplo n.º 17
0
 if (!empty($CFG->gdversion) and empty($USER->newadminuser)) {
     useredit_update_picture($usernew, $userform, $filemanageroptions);
 }
 // update mail bounces
 useredit_update_bounces($user, $usernew);
 // update forum track preference
 useredit_update_trackforums($user, $usernew);
 // save custom profile fields data
 profile_save_data($usernew);
 // reload from db
 $usernew = $DB->get_record('user', array('id' => $usernew->id));
 //if($rolename == 'subadmin') {
 //Add member to cohort
 $cohortDetails = $DB->get_record("cohort", array('idnumber' => $usernew->lang));
 //var_dump($cohortDetails->id);exit;
 cohort_add_member($cohortDetails->id, $usernew->id);
 //}
 // if($usernew->lang == COUNTER_MANAGER_ISO) {
 // cohort_add_member(US_ENGLISH, $usernew->id);
 // }
 if ($usernew->lang != $userold->lang) {
     $cohortRemove = $DB->get_record("cohort", array('idnumber' => $userold->lang));
     cohort_remove_member($cohortRemove->id, $usernew->id);
 }
 // trigger events
 if ($usercreated) {
     events_trigger('user_created', $usernew);
 } else {
     events_trigger('user_updated', $usernew);
 }
 if ($user->id == $USER->id) {
Ejemplo n.º 18
0
/**
 * Claim a coupon
 *
 * @param string $code coupon submission code
 */
function claim_coupon_confirm($code)
{
    global $CFG, $DB, $USER;
    // Because we're outside course context we've got to include groups library manually.
    require_once $CFG->dirroot . '/group/lib.php';
    require_once $CFG->dirroot . '/cohort/lib.php';
    $role = $DB->get_record('role', array('shortname' => 'student'));
    $coupon = $DB->get_record('block_coupon', array('submission_code' => $code));
    $couponcourses = $DB->get_records('block_coupon_courses', array('couponid' => $coupon->id));
    // We'll handle coupon_cohorts.
    if (empty($couponcourses)) {
        $couponcohorts = $DB->get_records('block_coupon_cohorts', array('couponid' => $coupon->id));
        if (count($couponcohorts) == 0) {
            throw new exception('error:missing_cohort');
        }
        // Add user to cohort.
        foreach ($couponcohorts as $couponcohort) {
            if (!$DB->get_record('cohort', array('id' => $couponcohort->cohortid))) {
                throw new exception('error:missing_cohort');
            }
            cohort_add_member($couponcohort->cohortid, $USER->id);
        }
        // Now execute the cohort sync.
        $result = self::enrol_cohort_sync();
        // If result = 0 it went ok. (lol!).
        if ($result === 1) {
            throw new exception('error:cohort_sync');
        } else {
            if ($result === 2) {
                throw new exception('error:plugin_disabled');
            }
        }
        // Otherwise we'll handle based on courses.
    } else {
        // Set enrolment period.
        $endenrolment = 0;
        if (!is_null($coupon->enrolperiod) && $coupon->enrolperiod > 0) {
            $endenrolment = strtotime("+ {$coupon->enrolperiod} days");
        }
        foreach ($couponcourses as $couponcourse) {
            // Make sure we only enrol if its not enrolled yet.
            $context = \context_course::instance($couponcourse->courseid);
            if (is_null($context) || $context === false) {
                throw new exception('error:course-not-found');
            }
            if (is_enrolled($context, $USER->id)) {
                continue;
            }
            // Now we can enrol.
            if (!enrol_try_internal_enrol($couponcourse->courseid, $USER->id, $role->id, time(), $endenrolment)) {
                throw new exception('error:unable_to_enrol');
            }
            // Mark the context for cache refresh.
            $context->mark_dirty();
            remove_temp_course_roles($context);
        }
        // And add user to groups.
        $coupongroups = $DB->get_records('block_coupon_groups', array('couponid' => $coupon->id));
        if (!empty($coupongroups)) {
            foreach ($coupongroups as $coupongroup) {
                // Check if the group exists.
                if (!$DB->get_record('groups', array('id' => $coupongroup->groupid))) {
                    throw new exception('error:missing_group');
                }
                // Add user if its not a member yet.
                if (!groups_is_member($coupongroup->groupid, $USER->id)) {
                    groups_add_member($coupongroup->groupid, $USER->id);
                }
            }
        }
    }
    // And finally update the coupon record.
    $coupon->userid = $USER->id;
    $coupon->timemodified = time();
    $DB->update_record('block_coupon', $coupon);
    // Trigger event.
    $event = \block_coupon\event\coupon_used::create(array('objectid' => $coupon->id, 'relateduserid' => $USER->id, 'context' => \context_user::instance($USER->id)));
    $event->add_record_snapshot('block_coupon', $coupon);
    $event->trigger();
    //return (empty($coupon->redirect_url)) ? $CFG->wwwroot . "/my" : $coupon->redirect_url;
}
Ejemplo n.º 19
0
 /**
  * Post authentication hook.
  * This method is called from authenticate_user_login() for all enabled auth plugins.
  *
  * @param object $user user object, later used for $USER
  * @param string $username (with system magic quotes)
  * @param string $password plain text password (with system magic quotes)
  */
 function user_authenticated_hook(&$user, $username, $password)
 {
     global $DB, $SESSION;
     $context = context_system::instance();
     $uid = $user->id;
     // Ignore users from don't_touch list
     $ignore = explode(",", $this->config->donttouchusers);
     if (!empty($ignore) and array_search($username, $ignore) !== false) {
         $SESSION->mcautoenrolled = TRUE;
         return true;
     }
     // Ignore guests
     if ($uid < 2) {
         $SESSION->mcautoenrolled = TRUE;
         return true;
     }
     // ********************** Get COHORTS data
     $clause = array('contextid' => $context->id);
     if ($this->config->enableunenrol == 1) {
         $clause['component'] = self::COMPONENT_NAME;
     }
     $cohorts = $DB->get_records('cohort', $clause);
     $cohorts_list = array();
     foreach ($cohorts as $cohort) {
         $cid = $cohort->id;
         $cname = format_string($cohort->name);
         $cohorts_list[$cid] = $cname;
     }
     // Get advanced user data
     profile_load_data($user);
     profile_load_custom_fields($user);
     $user_profile_data = mcae_prepare_profile_data($user, $this->config->secondrule_fld);
     // Additional values for email
     list($email_username, $email_domain) = explode("@", $user_profile_data['email']);
     // email root domain
     $email_domain_array = explode('.', $email_domain);
     if (count($email_domain_array) > 2) {
         $email_rootdomain = $email_domain_array[count($email_domain_array) - 2] . '.' . $email_domain_array[count($email_domain_array) - 1];
     } else {
         $email_rootdomain = $email_domain;
     }
     $user_profile_data['email'] = array('full' => $user_profile_data['email'], 'username' => $email_username, 'domain' => $email_domain, 'rootdomain' => $email_rootdomain);
     // Delimiter
     $delimiter = $this->config->delim;
     $delim = strtr($delimiter, array('CR+LF' => chr(13) . chr(10), 'CR' => chr(13), 'LF' => chr(10)));
     // Calculate a cohort names for user
     $replacements_tpl = $this->config->replace_arr;
     $replacements = array();
     if (!empty($replacements_tpl)) {
         $replacements_pre = explode($delim, $replacements_tpl);
         foreach ($replacements_pre as $rap) {
             list($key, $val) = explode("|", $rap);
             $replacements[$key] = $val;
         }
     }
     // Generate cohorts array
     $main_rule = $this->config->mainrule_fld;
     $templates_tpl = array();
     $templates = array();
     if (!empty($main_rule)) {
         $templates_tpl = explode($delim, $main_rule);
     } else {
         $SESSION->mcautoenrolled = TRUE;
         return;
         //Empty mainrule
     }
     // Find %split function
     foreach ($templates_tpl as $item) {
         if (preg_match('/(?<full>%split\\((?<fld>\\w*)\\|(?<delim>.{1,5})\\))/', $item, $split_params)) {
             // Split!
             $splitted = explode($split_params['delim'], $user_profile_data[$split_params['fld']]);
             foreach ($splitted as $key => $val) {
                 $user_profile_data[$split_params['fld'] . "_{$key}"] = $val;
                 $templates[] = strtr($item, array("{$split_params['full']}" => "{{ {$split_params['fld']}_{$key} }}"));
             }
         } else {
             $templates[] = $item;
         }
     }
     $processed = array();
     // Process templates with Mustache
     foreach ($templates as $cohort) {
         $cohortname = $this->mustache->render($cohort, $user_profile_data);
         $cohortname = !empty($replacements) ? strtr($cohortname, $replacements) : $cohortname;
         if ($cohortname == '') {
             continue;
             // We don't want an empty cohort name
         }
         $cid = array_search($cohortname, $cohorts_list);
         if ($cid !== false) {
             if (!$DB->record_exists('cohort_members', array('cohortid' => $cid, 'userid' => $user->id))) {
                 cohort_add_member($cid, $user->id);
             }
         } else {
             // Cohort not exist so create a new one
             $newcohort = new stdClass();
             $newcohort->name = $cohortname;
             $newcohort->description = "created " . date("d-m-Y");
             $newcohort->contextid = $context->id;
             if ($this->config->enableunenrol == 1) {
                 $newcohort->component = "auth_mcae";
             }
             $cid = cohort_add_cohort($newcohort);
             cohort_add_member($cid, $user->id);
             // Prevent creation new cohorts with same names
             $cohorts_list[$cid] = $cohortname;
         }
         $processed[] = $cid;
     }
     $SESSION->mcautoenrolled = TRUE;
     //Unenrol user
     if ($this->config->enableunenrol == 1) {
         //List of cohorts where this user enrolled
         $sql = "SELECT c.id AS cid FROM {cohort} c JOIN {cohort_members} cm ON cm.cohortid = c.id WHERE c.component = 'auth_mcae' AND cm.userid = {$uid}";
         $enrolledcohorts = $DB->get_records_sql($sql);
         foreach ($enrolledcohorts as $ec) {
             if (array_search($ec->cid, $processed) === false) {
                 cohort_remove_member($ec->cid, $uid);
             }
         }
     }
 }
Ejemplo n.º 20
0
 /**
  * Test the plan created event using template_cohort.
  *
  */
 public function test_plan_created_using_templatecohort()
 {
     $this->resetAfterTest(true);
     $this->setAdminUser();
     $dg = $this->getDataGenerator();
     $lpg = $this->getDataGenerator()->get_plugin_generator('core_competency');
     $user1 = $dg->create_user();
     $user2 = $dg->create_user();
     $c1 = $dg->create_cohort();
     // Add 2 users to the cohort.
     cohort_add_member($c1->id, $user1->id);
     cohort_add_member($c1->id, $user2->id);
     $t1 = $lpg->create_template();
     $tc = $lpg->create_template_cohort(array('templateid' => $t1->get_id(), 'cohortid' => $c1->id));
     // Trigger and capture the event.
     $sink = $this->redirectEvents();
     api::create_plans_from_template_cohort($t1->get_id(), $c1->id);
     // Get our event event.
     $plans = core_competency\plan::get_records(array('templateid' => $t1->get_id()), 'id');
     $events = $sink->get_events();
     $this->assertCount(2, $events);
     $this->assertCount(2, $plans);
     $event = $events[0];
     $plan = $plans[0];
     // Check that the event data is valid.
     $this->assertInstanceOf('\\core\\event\\competency_plan_created', $event);
     $this->assertEquals($plan->get_id(), $event->objectid);
     $this->assertEquals($plan->get_context()->id, $event->contextid);
     $event = $events[1];
     $plan = $plans[1];
     $this->assertInstanceOf('\\core\\event\\competency_plan_created', $event);
     $this->assertEquals($plan->get_id(), $event->objectid);
     $this->assertEquals($plan->get_context()->id, $event->contextid);
     $this->assertEventContextNotUsed($event);
     $this->assertDebuggingNotCalled();
 }
Ejemplo n.º 21
0
 public function test_cohort_get_visible_list()
 {
     global $DB;
     $this->resetAfterTest();
     $category1 = $this->getDataGenerator()->create_category();
     $category2 = $this->getDataGenerator()->create_category();
     $course1 = $this->getDataGenerator()->create_course(array('category' => $category1->id));
     $course2 = $this->getDataGenerator()->create_course(array('category' => $category2->id));
     $course3 = $this->getDataGenerator()->create_course();
     $cohort1 = $this->getDataGenerator()->create_cohort(array('contextid' => context_coursecat::instance($category1->id)->id));
     $cohort2 = $this->getDataGenerator()->create_cohort(array('contextid' => context_coursecat::instance($category2->id)->id));
     $cohort3 = $this->getDataGenerator()->create_cohort(array('contextid' => context_system::instance()->id));
     $cohort4 = $this->getDataGenerator()->create_cohort(array('contextid' => context_system::instance()->id));
     $user1 = $this->getDataGenerator()->create_user();
     $user2 = $this->getDataGenerator()->create_user();
     $user3 = $this->getDataGenerator()->create_user();
     $user4 = $this->getDataGenerator()->create_user();
     $user5 = $this->getDataGenerator()->create_user();
     $manualenrol = enrol_get_plugin('manual');
     $enrol1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'manual'));
     $enrol2 = $DB->get_record('enrol', array('courseid' => $course2->id, 'enrol' => 'manual'));
     $manualenrol->enrol_user($enrol1, $user1->id);
     $manualenrol->enrol_user($enrol1, $user3->id);
     $manualenrol->enrol_user($enrol1, $user4->id);
     $manualenrol->enrol_user($enrol2, $user2->id);
     cohort_add_member($cohort1->id, $user1->id);
     cohort_add_member($cohort3->id, $user1->id);
     cohort_add_member($cohort1->id, $user3->id);
     cohort_add_member($cohort2->id, $user2->id);
     $list = cohort_get_visible_list($course1);
     $this->assertEquals(2, count($list));
     $this->assertNotEmpty($list[$cohort1->id]);
     $this->assertRegExp('/\\(2\\)$/', $list[$cohort1->id]);
     $this->assertNotEmpty($list[$cohort3->id]);
     $this->assertRegExp('/\\(1\\)$/', $list[$cohort3->id]);
     $list = cohort_get_visible_list($course1, false);
     $this->assertEquals(3, count($list));
     $this->assertNotEmpty($list[$cohort1->id]);
     $this->assertRegExp('/\\(2\\)$/', $list[$cohort1->id]);
     $this->assertNotEmpty($list[$cohort3->id]);
     $this->assertRegExp('/\\(1\\)$/', $list[$cohort3->id]);
     $this->assertNotEmpty($list[$cohort4->id]);
     $this->assertRegExp('/[^\\)]$/', $list[$cohort4->id]);
     $list = cohort_get_visible_list($course2);
     $this->assertEquals(1, count($list));
     $this->assertNotEmpty($list[$cohort2->id]);
     $this->assertRegExp('/\\(1\\)$/', $list[$cohort2->id]);
     $list = cohort_get_visible_list($course2, false);
     $this->assertEquals(3, count($list));
     $this->assertNotEmpty($list[$cohort2->id]);
     $this->assertRegExp('/\\(1\\)$/', $list[$cohort2->id]);
     $this->assertNotEmpty($list[$cohort3->id]);
     $this->assertRegExp('/[^\\)]$/', $list[$cohort3->id]);
     $this->assertNotEmpty($list[$cohort4->id]);
     $this->assertRegExp('/[^\\)]$/', $list[$cohort4->id]);
     $list = cohort_get_visible_list($course3);
     $this->assertEquals(0, count($list));
     $list = cohort_get_visible_list($course3, false);
     $this->assertEquals(2, count($list));
     $this->assertNotEmpty($list[$cohort3->id]);
     $this->assertRegExp('/[^\\)]$/', $list[$cohort3->id]);
     $this->assertNotEmpty($list[$cohort4->id]);
     $this->assertRegExp('/[^\\)]$/', $list[$cohort4->id]);
 }
Ejemplo n.º 22
0
 public function test_sync_plans_from_cohorts_with_passed_duedate()
 {
     global $DB;
     $this->resetAfterTest(true);
     $this->setAdminUser();
     $dg = $this->getDataGenerator();
     $lpg = $dg->get_plugin_generator('core_competency');
     $user1 = $dg->create_user();
     $user2 = $dg->create_user();
     $cohort = $dg->create_cohort();
     $tpl = $lpg->create_template(array('duedate' => time() + 1000));
     $templatecohort = api::create_template_cohort($tpl->get_id(), $cohort->id);
     $task = \core\task\manager::get_scheduled_task('\\core\\task\\sync_plans_from_template_cohorts_task');
     // Add 1 user to the cohort.
     cohort_add_member($cohort->id, $user1->id);
     // Creating plans from template cohort.
     $task->execute();
     $this->assertEquals(1, \core_competency\plan::count_records());
     // Now add another user, but this time the template will be expired.
     cohort_add_member($cohort->id, $user2->id);
     $record = $tpl->to_record();
     $record->duedate = time() - 10000;
     $DB->update_record(\core_competency\template::TABLE, $record);
     $tpl->read();
     $task->execute();
     $this->assertEquals(1, \core_competency\plan::count_records());
     // Still only one plan.
     // Pretend it wasn't expired.
     $tpl->set_duedate(time() + 100);
     $tpl->update();
     $task->execute();
     $this->assertEquals(2, \core_competency\plan::count_records());
     // Now there is two.
 }
Ejemplo n.º 23
0
 public function test_sync_all_courses()
 {
     global $DB;
     $this->resetAfterTest();
     $trace = new null_progress_trace();
     // Setup a few courses and categories.
     $cohortplugin = enrol_get_plugin('cohort');
     $manualplugin = enrol_get_plugin('manual');
     $studentrole = $DB->get_record('role', array('shortname' => 'student'));
     $this->assertNotEmpty($studentrole);
     $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
     $this->assertNotEmpty($teacherrole);
     $managerrole = $DB->get_record('role', array('shortname' => 'manager'));
     $this->assertNotEmpty($managerrole);
     $cat1 = $this->getDataGenerator()->create_category();
     $cat2 = $this->getDataGenerator()->create_category();
     $course1 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
     $course2 = $this->getDataGenerator()->create_course(array('category' => $cat1->id));
     $course3 = $this->getDataGenerator()->create_course(array('category' => $cat2->id));
     $course4 = $this->getDataGenerator()->create_course(array('category' => $cat2->id));
     $maninstance1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'manual'), '*', MUST_EXIST);
     $user1 = $this->getDataGenerator()->create_user();
     $user2 = $this->getDataGenerator()->create_user();
     $user3 = $this->getDataGenerator()->create_user();
     $user4 = $this->getDataGenerator()->create_user();
     $cohort1 = $this->getDataGenerator()->create_cohort(array('contextid' => context_coursecat::instance($cat1->id)->id));
     $cohort2 = $this->getDataGenerator()->create_cohort(array('contextid' => context_coursecat::instance($cat2->id)->id));
     $cohort3 = $this->getDataGenerator()->create_cohort();
     $this->disable_plugin();
     // Prevents event sync.
     $manualplugin->enrol_user($maninstance1, $user4->id, $teacherrole->id);
     $manualplugin->enrol_user($maninstance1, $user3->id, $managerrole->id);
     $this->assertEquals(2, $DB->count_records('role_assignments', array()));
     $this->assertEquals(2, $DB->count_records('user_enrolments', array()));
     $id = $cohortplugin->add_instance($course1, array('customint1' => $cohort1->id, 'roleid' => $studentrole->id));
     $cohortinstance1 = $DB->get_record('enrol', array('id' => $id));
     $id = $cohortplugin->add_instance($course1, array('customint1' => $cohort2->id, 'roleid' => $teacherrole->id));
     $cohortinstance2 = $DB->get_record('enrol', array('id' => $id));
     $id = $cohortplugin->add_instance($course2, array('customint1' => $cohort2->id, 'roleid' => $studentrole->id));
     $cohortinstance3 = $DB->get_record('enrol', array('id' => $id));
     cohort_add_member($cohort1->id, $user1->id);
     cohort_add_member($cohort1->id, $user2->id);
     cohort_add_member($cohort1->id, $user4->id);
     cohort_add_member($cohort2->id, $user3->id);
     cohort_add_member($cohort3->id, $user3->id);
     $this->assertEquals(2, $DB->count_records('role_assignments', array()));
     $this->assertEquals(2, $DB->count_records('user_enrolments', array()));
     // Test sync of one course only.
     enrol_cohort_sync($trace, null);
     $this->assertEquals(2, $DB->count_records('role_assignments', array()));
     $this->assertEquals(2, $DB->count_records('user_enrolments', array()));
     $this->enable_plugin();
     enrol_cohort_sync($trace, null);
     $this->assertEquals(7, $DB->count_records('user_enrolments', array()));
     $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance1->id, 'userid' => $user1->id)));
     $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance1->id, 'userid' => $user2->id)));
     $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance1->id, 'userid' => $user4->id)));
     $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance2->id, 'userid' => $user3->id)));
     $this->assertEquals(7, $DB->count_records('role_assignments', array()));
     $this->assertTrue($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user1->id, 'roleid' => $studentrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $this->assertTrue($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user2->id, 'roleid' => $studentrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $this->assertTrue($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user4->id, 'roleid' => $studentrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $this->assertTrue($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user3->id, 'roleid' => $teacherrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance2->id)));
     $cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
     $DB->delete_records('cohort_members', array('cohortid' => $cohort2->id, 'userid' => $user3->id));
     // Use low level DB api to prevent events!
     enrol_cohort_sync($trace, $course1->id);
     $this->assertEquals(7, $DB->count_records('user_enrolments', array()));
     $this->assertEquals(6, $DB->count_records('role_assignments', array()));
     $this->assertFalse($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user3->id, 'roleid' => $teacherrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance2->id)));
     $cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
     $DB->delete_records('cohort_members', array('cohortid' => $cohort1->id, 'userid' => $user1->id));
     // Use low level DB api to prevent events!
     enrol_cohort_sync($trace, $course1->id);
     $this->assertEquals(5, $DB->count_records('user_enrolments', array()));
     $this->assertFalse($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance2->id, 'userid' => $user3->id)));
     $this->assertFalse($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance1->id, 'userid' => $user1->id)));
     $this->assertEquals(5, $DB->count_records('role_assignments', array()));
     $this->assertFalse($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user3->id, 'roleid' => $teacherrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance2->id)));
     $this->assertFalse($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user1->id, 'roleid' => $studentrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES);
     $DB->delete_records('cohort_members', array('cohortid' => $cohort1->id));
     // Use low level DB api to prevent events!
     $DB->delete_records('cohort', array('id' => $cohort1->id));
     // Use low level DB api to prevent events!
     enrol_cohort_sync($trace, $course1->id);
     $this->assertEquals(5, $DB->count_records('user_enrolments', array()));
     $this->assertEquals(3, $DB->count_records('role_assignments', array()));
     $cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
     enrol_cohort_sync($trace, $course1->id);
     $this->assertEquals(3, $DB->count_records('user_enrolments', array()));
     $this->assertEquals(3, $DB->count_records('role_assignments', array()));
     // Test group sync.
     $this->disable_plugin();
     // No event sync
     // Trigger sync to remove extra role assignments.
     enrol_cohort_sync($trace, $course1->id);
     $this->assertEquals(2, $DB->count_records('role_assignments', array()));
     $id = groups_create_group((object) array('name' => 'Group 1', 'courseid' => $course1->id));
     $group1 = $DB->get_record('groups', array('id' => $id), '*', MUST_EXIST);
     $id = groups_create_group((object) array('name' => 'Group 2', 'courseid' => $course1->id));
     $group2 = $DB->get_record('groups', array('id' => $id), '*', MUST_EXIST);
     $id = groups_create_group((object) array('name' => 'Group 2', 'courseid' => $course2->id));
     $group3 = $DB->get_record('groups', array('id' => $id), '*', MUST_EXIST);
     $cohort1 = $this->getDataGenerator()->create_cohort(array('contextid' => context_coursecat::instance($cat1->id)->id));
     $id = $cohortplugin->add_instance($course1, array('customint1' => $cohort1->id, 'roleid' => $studentrole->id, 'customint2' => $group1->id));
     $cohortinstance1 = $DB->get_record('enrol', array('id' => $id));
     $this->assertTrue(groups_add_member($group1, $user4));
     $this->assertTrue(groups_add_member($group2, $user4));
     $this->assertEquals(3, $DB->count_records('user_enrolments', array()));
     $this->assertEquals(2, $DB->count_records('role_assignments', array()));
     $this->assertFalse(groups_is_member($group1->id, $user1->id));
     cohort_add_member($cohort1->id, $user1->id);
     cohort_add_member($cohort1->id, $user4->id);
     cohort_add_member($cohort2->id, $user4->id);
     cohort_add_member($cohort2->id, $user3->id);
     $this->enable_plugin();
     enrol_cohort_sync($trace, null);
     $this->assertEquals(8, $DB->count_records('user_enrolments', array()));
     $this->assertEquals(8, $DB->count_records('role_assignments', array()));
     $this->assertTrue(groups_is_member($group1->id, $user1->id));
     $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $group1->id, 'userid' => $user1->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $this->assertTrue(is_enrolled(context_course::instance($course1->id), $user4));
     $this->assertTrue(groups_is_member($group1->id, $user4->id));
     $this->assertFalse($DB->record_exists('groups_members', array('groupid' => $group1->id, 'userid' => $user4->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $this->assertTrue(is_enrolled(context_course::instance($course2->id), $user3));
     $this->assertFalse(groups_is_member($group3->id, $user3->id));
     $cohortinstance1->customint2 = $group2->id;
     $DB->update_record('enrol', $cohortinstance1);
     $cohortinstance3->customint2 = $group3->id;
     $DB->update_record('enrol', $cohortinstance3);
     enrol_cohort_sync($trace, null);
     $this->assertFalse(groups_is_member($group1->id, $user1->id));
     $this->assertTrue(groups_is_member($group2->id, $user1->id));
     $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $group2->id, 'userid' => $user1->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $this->assertTrue(groups_is_member($group1->id, $user4->id));
     $this->assertTrue(groups_is_member($group2->id, $user4->id));
     $this->assertFalse($DB->record_exists('groups_members', array('groupid' => $group1->id, 'userid' => $user4->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $this->assertFalse($DB->record_exists('groups_members', array('groupid' => $group2->id, 'userid' => $user4->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id)));
     $this->assertTrue(groups_is_member($group3->id, $user3->id));
     $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $group3->id, 'userid' => $user3->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance3->id)));
     cohort_remove_member($cohort1->id, $user1->id);
     $this->assertFalse(groups_is_member($group1->id, $user1->id));
     cohort_remove_member($cohort1->id, $user4->id);
     $this->assertTrue(groups_is_member($group1->id, $user4->id));
     $this->assertTrue(groups_is_member($group2->id, $user4->id));
 }
Ejemplo n.º 24
0
     if (!($user = get_complete_user_data('username', $username))) {
         print_error('cannotfinduser', '', '', s($username));
     }
     if (!$user->suspended) {
         complete_user_login($user);
         \core\session\manager::apply_concurrent_login_limit($user->id, session_id());
         if (!empty($SESSION->wantsurl)) {
             // Send them where they were going.
             $goto = $SESSION->wantsurl;
             unset($SESSION->wantsurl);
             redirect($goto);
         }
     }
     $emaildomain = substr(strrchr(trim($user->email), "@"), 1);
     if ($domain = $DB->get_field('auth_whia_domain', 'cohortid', array('name' => $emaildomain))) {
         cohort_add_member($domain->cohortid, $user->id);
     }
     $PAGE->navbar->add(get_string("confirmed"));
     $PAGE->set_title(get_string("confirmed"));
     $PAGE->set_heading($COURSE->fullname);
     echo $OUTPUT->header();
     echo $OUTPUT->box_start('generalbox centerpara boxwidthnormal boxaligncenter');
     echo "<h3>" . get_string("thanks") . ", " . fullname($USER) . "</h3>\n";
     echo "<p>" . get_string("confirmed") . "</p>\n";
     echo $OUTPUT->single_button("{$CFG->wwwroot}/course/", get_string('courses'));
     echo $OUTPUT->box_end();
     echo $OUTPUT->footer();
     exit;
 } else {
     print_error('invalidconfirmdata');
 }
Ejemplo n.º 25
0
    function inner_functionality_assignexistinguser_tobatch($userid, $batchid){
        global $DB,$CFG, $USER, $OUTPUT;
           $batchmapinfo = $DB->get_record('local_batch_map', array('batchid' => $batchid));
           $batchprogramlevel = $DB->get_record('local_program', array('id' => $batchmapinfo->programid));
        
                            $userdatainfo = $DB->get_records('local_userdata', array('userid' => $userid));
                    foreach($userdatainfo as $record)
                        $userdata= $record;
                        
                    $userprogram = $DB->get_record('local_program', array('id' => $userdata->programid));
                    $length =sizeof($userdatainfo);           

                    //------- comparing program level exists batch  and new batch--------------
                    //-------and also checking  already student exists in two batches not to assign more than that
                    if (($userprogram->programlevel < $batchprogramlevel->programlevel)  || ($length<2)) { 
                        $userdatatemp = $userdata;
                        $userdatatemp->schoolid = $batchmapinfo->schoolid;
                        $userdatatemp->programid = $batchmapinfo->programid;
                        $userdatatemp->curriculumid = $batchmapinfo->curriculumid;
                        $userdatatemp->batchid = $batchmapinfo->batchid;
                        $userdatatemp->serviceid= $batchprogramlevel->shortname.$userid;

                        // before  inserting checking already assigned to same batch or not
                        if (!$DB->record_exists('local_userdata', array('schoolid'=>$batchmapinfo->schoolid ,'programid'=>$batchmapinfo->programid,'userid'=>$userid ))) {

                            $insertedid = $DB->insert_record('local_userdata', $userdatatemp);
                            cohort_add_member($batchid, $userid);
                            if ($insertedid)
                                echo $OUTPUT->notification(get_string('success_assign_student', 'local_batches'), 'notifysuccess');
                        } else
                            echo $OUTPUT->notification(get_string('cannotassign', 'local_batches'), 'notifyproblem');
                    } else {
                        // need show error  
                        echo $OUTPUT->notification(get_string('cannotassign', 'local_batches'), 'notifyproblem');
                    }
        
        
        
        
        
        
        
    }// end of function
Ejemplo n.º 26
0
 public function test_show_enrolme_link()
 {
     global $DB, $CFG;
     $this->resetAfterTest();
     $this->preventResetByRollback();
     // Messaging does not like transactions...
     /** @var $selfplugin enrol_self_plugin */
     $selfplugin = enrol_get_plugin('self');
     $user1 = $this->getDataGenerator()->create_user();
     $course1 = $this->getDataGenerator()->create_course();
     $course2 = $this->getDataGenerator()->create_course();
     $course3 = $this->getDataGenerator()->create_course();
     $course4 = $this->getDataGenerator()->create_course();
     $course5 = $this->getDataGenerator()->create_course();
     $cohort1 = $this->getDataGenerator()->create_cohort();
     $cohort2 = $this->getDataGenerator()->create_cohort();
     $instance1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance1->customint6 = 1;
     $DB->update_record('enrol', $instance1);
     $selfplugin->update_status($instance1, ENROL_INSTANCE_ENABLED);
     $instance2 = $DB->get_record('enrol', array('courseid' => $course2->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance2->customint6 = 0;
     $DB->update_record('enrol', $instance2);
     $selfplugin->update_status($instance2, ENROL_INSTANCE_ENABLED);
     $instance3 = $DB->get_record('enrol', array('courseid' => $course3->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance3->customint6 = 1;
     $DB->update_record('enrol', $instance3);
     $selfplugin->update_status($instance3, ENROL_INSTANCE_DISABLED);
     $instance4 = $DB->get_record('enrol', array('courseid' => $course4->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance4->customint6 = 0;
     $DB->update_record('enrol', $instance4);
     $selfplugin->update_status($instance4, ENROL_INSTANCE_DISABLED);
     $instance5 = $DB->get_record('enrol', array('courseid' => $course5->id, 'enrol' => 'self'), '*', MUST_EXIST);
     $instance5->customint6 = 1;
     $instance5->customint5 = $cohort1->id;
     $DB->update_record('enrol', $instance1);
     $selfplugin->update_status($instance5, ENROL_INSTANCE_ENABLED);
     $id = $selfplugin->add_instance($course5, $selfplugin->get_instance_defaults());
     $instance6 = $DB->get_record('enrol', array('id' => $id), '*', MUST_EXIST);
     $instance6->customint6 = 1;
     $instance6->customint5 = $cohort2->id;
     $DB->update_record('enrol', $instance1);
     $selfplugin->update_status($instance6, ENROL_INSTANCE_ENABLED);
     $this->setUser($user1);
     $this->assertTrue($selfplugin->show_enrolme_link($instance1));
     $this->assertFalse($selfplugin->show_enrolme_link($instance2));
     $this->assertFalse($selfplugin->show_enrolme_link($instance3));
     $this->assertFalse($selfplugin->show_enrolme_link($instance4));
     require_once "{$CFG->dirroot}/cohort/lib.php";
     cohort_add_member($cohort1->id, $user1->id);
     $this->assertTrue($selfplugin->show_enrolme_link($instance5));
     $this->assertFalse($selfplugin->show_enrolme_link($instance6));
 }
Ejemplo n.º 27
0
 /**
  * Adds members to cohorts
  *
  * @param array $data
  * @return void
  */
 protected function process_cohort_member($data) {
     cohort_add_member($data['cohortid'], $data['userid']);
 }
 /**
  * Adds an user to a cohort.
  *
  * @return void.
  */
 protected function add_to_cohort()
 {
     global $DB;
     $cohorts = array();
     // Cohort is not a standard or profile field, it is not saved in the
     // finaldata.
     foreach ($this->rawdata as $field => $value) {
         if (!preg_match('/^cohort\\d+$/', $field)) {
             continue;
         }
         $addcohort = $value;
         if (!isset($cohorts[$addcohort])) {
             if (is_number($addcohort)) {
                 $cohort = $DB->get_record('cohort', array('id' => $addcohort));
             } else {
                 $cohort = $DB->get_record('cohort', array('idnumber' => $addcohort));
                 // Creating cohort.
                 if (empty($cohort)) {
                     try {
                         $cohortid = cohort_add_cohort((object) array('idnumber' => $addcohort, 'name' => $addcohort, 'contextid' => context_system::instance()->id));
                     } catch (Exception $e) {
                         $this->error($e->errorcode, new lang_string($e->errorcode, 'tool_uploadusercli'));
                         return false;
                     }
                     $cohort = $DB->get_record('cohort', array('id' => $cohortid));
                 }
             }
             if (empty($cohort)) {
                 $this->set_status("unknowncohort", new lang_string('unknowncohort', 'core_cohort', $cohort));
             } else {
                 if (!empty($cohort->component)) {
                     // Cohorts synced with external sources need not be modified
                     $cohorts[$addcohort] = get_string('external', 'core_cohort');
                 } else {
                     $cohorts[$addcohort] = $cohort;
                 }
             }
         }
         if (is_object($cohorts[$addcohort])) {
             $cohort = $cohorts[$addcohort];
             if (!$DB->record_exists('cohort_members', array('cohortid' => $cohort->id, 'userid' => $this->finaldata->id))) {
                 try {
                     cohort_add_member($cohort->id, $this->finaldata->id);
                 } catch (Exception $e) {
                     $this->error($e->getMessage(), new lang_string($e->getMessage(), 'tool_uploadusercli'));
                     return false;
                 }
                 $this->set_status('cohortcreated', new lang_string('cohortcreated', 'tool_uploadusercli'));
             } else {
                 $this->set_status('cohortnotcreatederror', new lang_string('cohortnotcreatederror', 'tool_uploadusercli'));
             }
         }
     }
     return true;
 }
Ejemplo n.º 29
0
             }
             if (empty($cohort)) {
                 $cohorts[$addcohort] = get_string('unknowncohort', 'core_cohort', s($addcohort));
             } else {
                 if (!empty($cohort->component)) {
                     // cohorts synchronised with external sources must not be modified!
                     $cohorts[$addcohort] = get_string('external', 'core_cohort');
                 } else {
                     $cohorts[$addcohort] = $cohort;
                 }
             }
         }
         if (is_object($cohorts[$addcohort])) {
             $cohort = $cohorts[$addcohort];
             if (!$DB->record_exists('cohort_members', array('cohortid' => $cohort->id, 'userid' => $user->id))) {
                 cohort_add_member($cohort->id, $user->id);
                 // we might add special column later, for now let's abuse enrolments
                 $upt->track('enrolments', get_string('useradded', 'core_cohort', s($cohort->name)));
             }
         } else {
             // error message
             $upt->track('enrolments', $cohorts[$addcohort], 'error');
         }
     }
 }
 // find course enrolments, groups, roles/types and enrol periods
 // this is again a special case, we always do this for any updated or created users
 foreach ($filecolumns as $column) {
     if (!preg_match('/^course\\d+$/', $column)) {
         continue;
     }
Ejemplo n.º 30
0
 /**
  * Validate that the version 1 plugin deletes appropriate associations when
  * deleting a user
  */
 public function test_version1importdeleteuserdeletesassociations()
 {
     global $CFG, $DB;
     set_config('siteadmins', 0);
     // New config settings needed for course format refactoring in 2.4.
     set_config('numsections', 15, 'moodlecourse');
     set_config('hiddensections', 0, 'moodlecourse');
     set_config('coursedisplay', 1, 'moodlecourse');
     require_once $CFG->dirroot . '/cohort/lib.php';
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/group/lib.php';
     require_once $CFG->dirroot . '/lib/enrollib.php';
     require_once $CFG->dirroot . '/lib/gradelib.php';
     // Create our test user, and determine their userid.
     $this->run_core_user_import(array());
     $userid = (int) $DB->get_field('user', 'id', array('username' => 'rlipusername', 'mnethostid' => $CFG->mnet_localhost_id));
     // Create cohort.
     $cohort = new stdClass();
     $cohort->name = 'testcohort';
     $cohort->contextid = context_system::instance()->id;
     $cohortid = cohort_add_cohort($cohort);
     // Add the user to the cohort.
     cohort_add_member($cohortid, $userid);
     // Create a course category - there is no API for doing this.
     $category = new stdClass();
     $category->name = 'testcategory';
     $category->id = $DB->insert_record('course_categories', $category);
     // Create a course.
     set_config('defaultenrol', 1, 'enrol_manual');
     set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual');
     $course = new stdClass();
     $course->category = $category->id;
     $course->fullname = 'testfullname';
     $course = create_course($course);
     // Create a grade.
     $gradeitem = new grade_item(array('courseid' => $course->id, 'itemtype' => 'manual', 'itemname' => 'testitem'), false);
     $gradeitem->insert();
     $gradegrade = new grade_grade(array('itemid' => $gradeitem->id, 'userid' => $userid), false);
     $gradegrade->insert();
     // Send the user an unprocessed message.
     set_config('noemailever', true);
     // Set up a user tag.
     tag_set('user', $userid, array('testtag'));
     // Create a new course-level role.
     $roleid = create_role('testrole', 'testrole', 'testrole');
     set_role_contextlevels($roleid, array(CONTEXT_COURSE));
     // Enrol the user in the course with the new role.
     enrol_try_internal_enrol($course->id, $userid, $roleid);
     // Create a group.
     $group = new stdClass();
     $group->name = 'testgroup';
     $group->courseid = $course->id;
     $groupid = groups_create_group($group);
     // Add the user to the group.
     groups_add_member($groupid, $userid);
     set_user_preference('testname', 'testvalue', $userid);
     // Create profile field data - don't both with the API here because it's a bit unwieldy.
     $userinfodata = new stdClass();
     $userinfodata->fieldid = 1;
     $userinfodata->data = 'bogus';
     $userinfodata->userid = $userid;
     $DB->insert_record('user_info_data', $userinfodata);
     // There is no easily accessible API for doing this.
     $lastaccess = new stdClass();
     $lastaccess->userid = $userid;
     $lastaccess->courseid = $course->id;
     $DB->insert_record('user_lastaccess', $lastaccess);
     $data = array('action' => 'delete', 'username' => 'rlipusername');
     $this->run_core_user_import($data, false);
     // Assert data condition after delete.
     $this->assertEquals($DB->count_records('message_read', array('useridto' => $userid)), 0);
     $this->assertEquals($DB->count_records('grade_grades'), 0);
     $this->assertEquals($DB->count_records('tag_instance'), 0);
     $this->assertEquals($DB->count_records('cohort_members'), 0);
     $this->assertEquals($DB->count_records('user_enrolments'), 0);
     $this->assertEquals($DB->count_records('role_assignments'), 0);
     $this->assertEquals($DB->count_records('groups_members'), 0);
     $this->assertEquals($DB->count_records('user_preferences'), 0);
     $this->assertEquals($DB->count_records('user_info_data'), 0);
     $this->assertEquals($DB->count_records('user_lastaccess'), 0);
 }