public function test_cohort_update_cohort()
 {
     global $DB;
     $this->resetAfterTest();
     $cohort = new stdClass();
     $cohort->contextid = context_system::instance()->id;
     $cohort->name = 'test cohort';
     $cohort->idnumber = 'testid';
     $cohort->description = 'test cohort desc';
     $cohort->descriptionformat = FORMAT_HTML;
     $id = cohort_add_cohort($cohort);
     $this->assertNotEmpty($id);
     $DB->set_field('cohort', 'timecreated', $cohort->timecreated - 10, array('id' => $id));
     $DB->set_field('cohort', 'timemodified', $cohort->timemodified - 10, array('id' => $id));
     $cohort = $DB->get_record('cohort', array('id' => $id));
     $cohort->name = 'test cohort 2';
     cohort_update_cohort($cohort);
     $newcohort = $DB->get_record('cohort', array('id' => $id));
     $this->assertSame($cohort->contextid, $newcohort->contextid);
     $this->assertSame($cohort->name, $newcohort->name);
     $this->assertSame($cohort->description, $newcohort->description);
     $this->assertSame($cohort->descriptionformat, $newcohort->descriptionformat);
     $this->assertSame($cohort->timecreated, $newcohort->timecreated);
     $this->assertSame($cohort->component, $newcohort->component);
     $this->assertGreaterThan($newcohort->timecreated, $newcohort->timemodified);
     $this->assertLessThanOrEqual(time(), $newcohort->timemodified);
 }
Example #2
0
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/cohort/lib.php';
     foreach ($this->arguments as $argument) {
         $this->expandOptionsManually(array($argument));
         $options = $this->expandedOptions;
         if ($cohort = $DB->get_record('cohort', array('name' => $argument))) {
             echo "Cohort already exists\n";
             exit(0);
         }
         if (!empty($options['category'])) {
             if ($category = $DB->get_record('course_categories', array('id' => $options['category']))) {
                 $categorycontext = context_coursecat::instance($category->id);
             }
         }
         $cohort = new \stdClass();
         if (!empty($categorycontext)) {
             $cohort->contextid = $categorycontext->id;
         } else {
             $cohort->contextid = 1;
         }
         $cohort->name = $argument;
         $cohort->idnumber = $options['idnumber'];
         $cohort->description = $options['description'];
         $cohort->descriptionformat = FORMAT_HTML;
         $newcohort = cohort_add_cohort($cohort);
         echo $newcohort . "\n";
     }
 }
Example #3
0
 /**
  * Create one or more cohorts
  *
  * @param array $cohorts An array of cohorts to create.
  * @return array An array of arrays
  * @since Moodle 2.5
  */
 public static function create_cohorts($cohorts)
 {
     global $CFG, $DB;
     require_once "{$CFG->dirroot}/cohort/lib.php";
     $params = self::validate_parameters(self::create_cohorts_parameters(), array('cohorts' => $cohorts));
     $transaction = $DB->start_delegated_transaction();
     $syscontext = context_system::instance();
     $cohortids = array();
     foreach ($params['cohorts'] as $cohort) {
         $cohort = (object) $cohort;
         // Category type (context id).
         $categorytype = $cohort->categorytype;
         if (!in_array($categorytype['type'], array('idnumber', 'id', 'system'))) {
             throw new invalid_parameter_exception('category type must be id, idnumber or system:' . $categorytype['type']);
         }
         if ($categorytype['type'] === 'system') {
             $cohort->contextid = $syscontext->id;
         } else {
             if ($catid = $DB->get_field('course_categories', 'id', array($categorytype['type'] => $categorytype['value']))) {
                 $catcontext = context_coursecat::instance($catid);
                 $cohort->contextid = $catcontext->id;
             } else {
                 throw new invalid_parameter_exception('category not exists: category ' . $categorytype['type'] . ' = ' . $categorytype['value']);
             }
         }
         // Make sure that the idnumber doesn't already exist.
         if ($DB->record_exists('cohort', array('idnumber' => $cohort->idnumber))) {
             throw new invalid_parameter_exception('record already exists: idnumber=' . $cohort->idnumber);
         }
         $context = context::instance_by_id($cohort->contextid, MUST_EXIST);
         if ($context->contextlevel != CONTEXT_COURSECAT and $context->contextlevel != CONTEXT_SYSTEM) {
             throw new invalid_parameter_exception('Invalid context');
         }
         self::validate_context($context);
         require_capability('moodle/cohort:manage', $context);
         // Validate format.
         $cohort->descriptionformat = external_validate_format($cohort->descriptionformat);
         $cohort->id = cohort_add_cohort($cohort);
         list($cohort->description, $cohort->descriptionformat) = external_format_text($cohort->description, $cohort->descriptionformat, $context->id, 'cohort', 'description', $cohort->id);
         $cohortids[] = (array) $cohort;
     }
     $transaction->allow_commit();
     return $cohortids;
 }
 /**
  * Creates a cohort for identifier if it doesn't exist
  *
  * @param string $identifier identifier of cohort uniquely identifiying cohorts between dev plugin generated cohorts
  */
 public function __construct($identifier)
 {
     global $DB;
     $cohort = new stdClass();
     $cohort->idnumber = 'local_dev:' . $identifier;
     $cohort->component = 'local_dev';
     if ($existingcohort = $DB->get_record('cohort', (array) $cohort)) {
         $this->cohort = $existingcohort;
         // populate cohort members array based on existing members
         $this->members = $DB->get_records('cohort_members', array('cohortid' => $this->cohort->id), 'userid', 'userid');
     } else {
         $cohort->contextid = context_system::instance()->id;
         $cohort->name = $identifier;
         $cohort->description = 'Automatically generated cohort from developer plugin for [' . $identifier . ']';
         $cohort->id = cohort_add_cohort($cohort);
         $this->cohort = $cohort;
         // no existing members as we've just created cohort
         $this->members = array();
     }
 }
Example #5
0
    /**
     * Create test cohort.
     * @param array|stdClass $record
     * @param array $options
     * @return stdClass cohort record
     */
    public function create_cohort($record=null, array $options=null) {
        global $DB, $CFG;
        require_once("$CFG->dirroot/cohort/lib.php");

        $this->cohortcount++;
        $i = $this->cohortcount;

        $record = (array)$record;

        if (!isset($record['contextid'])) {
            $record['contextid'] = context_system::instance()->id;
        }

        if (!isset($record['name'])) {
            $record['name'] = 'Cohort '.$i;
        }

        if (!isset($record['idnumber'])) {
            $record['idnumber'] = '';
        }

        if (!isset($record['description'])) {
            $record['description'] = "Test cohort $i\n$this->loremipsum";
        }

        if (!isset($record['descriptionformat'])) {
            $record['descriptionformat'] = FORMAT_MOODLE;
        }

        if (!isset($record['component'])) {
            $record['component'] = '';
        }

        $id = cohort_add_cohort((object)$record);

        return $DB->get_record('cohort', array('id'=>$id), '*', MUST_EXIST);
    }
Example #6
0
 // add to cohort first, it might trigger enrolments indirectly - do NOT create cohorts here!
 foreach ($filecolumns as $column) {
     if (!preg_match('/^cohort\\d+$/', $column)) {
         continue;
     }
     if (!empty($user->{$column})) {
         $addcohort = $user->{$column};
         if (!isset($cohorts[$addcohort])) {
             if (is_number($addcohort)) {
                 // only non-numeric idnumbers!
                 $cohort = $DB->get_record('cohort', array('id' => $addcohort));
             } else {
                 $cohort = $DB->get_record('cohort', array('idnumber' => $addcohort));
                 if (empty($cohort) && has_capability('moodle/cohort:manage', context_system::instance())) {
                     // Cohort was not found. Create a new one.
                     $cohortid = cohort_add_cohort((object) array('idnumber' => $addcohort, 'name' => $addcohort, 'contextid' => context_system::instance()->id));
                     $cohort = $DB->get_record('cohort', array('id' => $cohortid));
                 }
             }
             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])) {
Example #7
0
 public function test_cohort_update_cohort_event()
 {
     global $DB;
     $this->resetAfterTest();
     // Setup the cohort data structure.
     $cohort = new stdClass();
     $cohort->contextid = context_system::instance()->id;
     $cohort->name = 'test cohort';
     $cohort->idnumber = 'testid';
     $cohort->description = 'test cohort desc';
     $cohort->descriptionformat = FORMAT_HTML;
     $id = cohort_add_cohort($cohort);
     $this->assertNotEmpty($id);
     $cohort->name = 'test cohort 2';
     // Catch Events.
     $sink = $this->redirectEvents();
     // Peform the update.
     cohort_update_cohort($cohort);
     $events = $sink->get_events();
     $sink->close();
     // Validate the event.
     $this->assertCount(1, $events);
     $event = $events[0];
     $updatedcohort = $DB->get_record('cohort', array('id' => $id));
     $this->assertInstanceOf('\\core\\event\\cohort_updated', $event);
     $this->assertEquals('cohort', $event->objecttable);
     $this->assertEquals($updatedcohort->id, $event->objectid);
     $this->assertEquals($updatedcohort->contextid, $event->contextid);
     $url = new moodle_url('/cohort/edit.php', array('id' => $event->objectid));
     $this->assertEquals($url, $event->get_url());
     $this->assertEquals($cohort, $event->get_record_snapshot('cohort', $id));
     $this->assertEventLegacyData($cohort, $event);
     $this->assertEventContextNotUsed($event);
 }
Example #8
0
if ($cohort->id) {
    // edit existing
    $cohort = file_prepare_standard_editor($cohort, 'description', $editoroptions, $context);
    $strheading = get_string('editcohort', 'cohort');
} else {
    // add new
    $cohort = file_prepare_standard_editor($cohort, 'description', $editoroptions, $context);
    $strheading = get_string('addcohort', 'cohort');
}
$PAGE->set_title($strheading);
$PAGE->set_heading($COURSE->fullname);
$PAGE->navbar->add($strheading);
$editform = new cohort_edit_form(null, array('editoroptions' => $editoroptions, 'data' => $cohort));
if ($editform->is_cancelled()) {
    redirect($returnurl);
} else {
    if ($data = $editform->get_data()) {
        $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context);
        if ($data->id) {
            cohort_update_cohort($data);
        } else {
            cohort_add_cohort($data);
        }
        // use new context id, it could have been changed
        redirect(new moodle_url('/cohort/index.php', array('contextid' => $data->contextid)));
    }
}
echo $OUTPUT->header();
echo $OUTPUT->heading($strheading);
echo $editform->display();
echo $OUTPUT->footer();
Example #9
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";
         }
     }
 }
Example #10
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);
             }
         }
     }
 }
 /**
  * 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;
 }
         print "ignoring {$groupname} that does not exist in Moodle (autocreation is off)" . PHP_EOL;
         continue;
     }
     $ldap_members = $plugin->ldap_get_group_members($groupname);
     // do not create yet the cohort if no known Moodle users are concerned
     if (count($ldap_members) == 0) {
         print "not autocreating empty cohort " . $groupname . PHP_EOL;
         continue;
     }
     $cohort = new StdClass();
     $cohort->name = $cohort->idnumber = $groupname;
     $cohort->contextid = context_system::instance()->id;
     //$cohort->component='sync_ldap';
     $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);
Example #13
0
    redirect($returnurl);
} else {
    if ($data = $editform->get_data()) {
        $oldcontextid = $context->id;
        $editoroptions['context'] = $context = context::instance_by_id($data->contextid);
        if ($data->id) {
            if ($data->contextid != $oldcontextid) {
                // Cohort was moved to another context.
                get_file_storage()->move_area_files_to_new_context($oldcontextid, $context->id, 'cohort', 'description', $data->id);
            }
            $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'cohort', 'description', $data->id);
            cohort_update_cohort($data);
        } else {
            $data->descriptionformat = $data->description_editor['format'];
            $data->description = $description = $data->description_editor['text'];
            $data->id = cohort_add_cohort($data);
            $editoroptions['context'] = $context = context::instance_by_id($data->contextid);
            $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'cohort', 'description', $data->id);
            if ($description != $data->description) {
                $updatedata = (object) array('id' => $data->id, 'description' => $data->description, 'contextid' => $context->id);
                cohort_update_cohort($updatedata);
            }
        }
        if ($returnurl->get_param('showall') || $returnurl->get_param('contextid') == $data->contextid) {
            // Redirect to where we were before.
            redirect($returnurl);
        } else {
            // Use new context id, it has been changed.
            redirect(new moodle_url('/cohort/index.php', array('contextid' => $data->contextid)));
        }
    }
Example #14
0
    navigation_node::override_active_url(new moodle_url('/cohort/index.php', array('contextid' => $context->id)));
} else {
    navigation_node::override_active_url(new moodle_url('/cohort/index.php', array()));
}
$uploadform = new cohort_upload_form(null, array('contextid' => $context->id, 'returnurl' => $returnurl));
if ($returnurl) {
    $returnurl = new moodle_url($returnurl);
} else {
    $returnurl = new moodle_url('/cohort/index.php', array('contextid' => $context->id));
}
if ($uploadform->is_cancelled()) {
    redirect($returnurl);
}
$strheading = get_string('uploadcohorts', 'cohort');
$PAGE->navbar->add($strheading);
echo $OUTPUT->header();
echo $OUTPUT->heading_with_help($strheading, 'uploadcohorts', 'cohort');
if ($editcontrols = cohort_edit_controls($context, $baseurl)) {
    echo $OUTPUT->render($editcontrols);
}
if ($data = $uploadform->get_data()) {
    $cohortsdata = $uploadform->get_cohorts_data();
    foreach ($cohortsdata as $cohort) {
        cohort_add_cohort($cohort);
    }
    echo $OUTPUT->notification(get_string('uploadedcohorts', 'cohort', count($cohortsdata)), 'notifysuccess');
    echo $OUTPUT->continue_button($returnurl);
} else {
    $uploadform->display();
}
echo $OUTPUT->footer();
 /**
  * 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);
 }
Example #16
0
        cohort_update_cohort($data);
        $batchmap = $DB->get_record('local_batch_map', array('batchid' => $data->id));
        $updatetemp = new stdclass();
        $updatetemp->id = $batchmap->id;
        $updatetemp->schoolid = $data->schoolid;
        $updatetemp->programid = $data->programid;
        $updatetemp->curriculumid = $data->curriculumid;
        $updatetemp->academicyear = $data->academicyear;
        $updatetemp->usermodified = $USER->id;
        $updatetemp->timemodified = time();
        $DB->update_record('local_batch_map', $updatetemp);
        $data->id;
    } else {

        $data->batchid = cohort_add_cohort($data);
        $batches->local_batches_add_map($data);
    }

    // Use new context id, it could have been changed.
    redirect(new moodle_url('/local/batches/index.php'));
}


if ($editform->is_submitted() && !$editform->is_validated())
    $collapse = false;

//$batches = new local_batches();
//$PAGE->navbar->add(get_string('pluginname', 'local_batches'));
echo $OUTPUT->header();
//Heading of the page