/**
  * Set up an ELIS custom field category.
  * @return field_category The created field category.
  */
 protected function set_up_elis_field_category()
 {
     $data = new stdClass();
     $data->name = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USER) . ' Test';
     $category = new field_category($data);
     $category->save();
     $categorycontext = new field_category_contextlevel();
     $categorycontext->categoryid = $category->id;
     $categorycontext->contextlevel = CONTEXT_ELIS_USER;
     $categorycontext->save();
     return $category;
 }
Beispiel #2
0
/**
 * Update environments and environment assignments to custom fields and
 * custom field data (run as a one-off during the elis program upgrade)
 *
 * If there are one or more entities (courses, classes) with environments
 * assigned to them, a new category and custom field is created, specific to the
 * appropriate context level. Then, that custom field is populated for each entity
 * that has and environment assigned (custom field is a single-select, where the options
 * are all the different environments on the site).
 */
function pm_migrate_environments()
{
    global $DB;
    require_once elis::lib('data/customfield.class.php');
    require_once elispm::lib('data/course.class.php');
    require_once elispm::lib('data/pmclass.class.php');
    //set up our contextlevel mapping
    $contextlevels = array(course::TABLE => 'course', pmclass::TABLE => 'class');
    //lookup on all tags
    $environment_lookup = $DB->get_records('local_elisprogram_env', null, '', 'id, name');
    foreach ($environment_lookup as $id => $environment) {
        $environment_lookup[$id] = $environment->name;
    }
    //go through each contextlevel and look for tags
    foreach ($contextlevels as $instancetable => $contextname) {
        //calculate the context level integer
        $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextname);
        //make sure one or more environments are used at the current context level
        $select = 'environmentid != 0';
        if ($DB->record_exists_select($instancetable, $select)) {
            //used to reference the category name
            $category = new field_category(array('name' => get_string('misc_category', 'local_elisprogram')));
            //make sure our field for storing environments is created
            $field = new field(array('shortname' => "_19upgrade_{$contextname}_environment", 'name' => get_string('environment', 'local_elisprogram'), 'datatype' => 'char'));
            $field = field::ensure_field_exists_for_context_level($field, $contextlevel, $category);
            //determine environment options
            $options = array();
            if ($records = $DB->get_recordset('local_elisprogram_env', null, 'name', 'DISTINCT name')) {
                foreach ($records as $record) {
                    $options[] = $record->name;
                }
            }
            $options = implode("\n", $options);
            //set up our field owner
            field_owner::ensure_field_owner_exists($field, 'manual', array('control' => 'menu', 'options' => $options, 'edit_capability' => '', 'view_capability' => ''));
            //set up data for all relevant entries
            $sql = "SELECT id, environmentid\n                    FROM {{$instancetable}}\n                    WHERE environmentid != 0";
            if ($records = $DB->get_recordset_sql($sql)) {
                foreach ($records as $record) {
                    $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextname);
                    $contextclass = \local_eliscore\context\helper::get_class_for_level($contextlevel);
                    $context = $contextclass::instance($record->id);
                    $environmentid = $environment_lookup[$record->environmentid];
                    field_data::set_for_context_and_field($context, $field, $environmentid);
                }
            }
        }
    }
}
 /**
  * Creates a PM custom field data record associated to the entity
  *
  * @param int $userid The PM user's id
  * @param int $fieldid The PM custom field id
  * @param string $data The data to set
  */
 private function update_data_record($entitytype = 'user', $entity, $field, $data)
 {
     require_once elispm::lib('data/' . $entitytype . '.class.php');
     // Save the value for the custom field for the entity.
     $contextlevel = \local_eliscore\context\helper::get_level_from_name($entitytype);
     $contextclass = \local_eliscore\context\helper::get_class_for_level($contextlevel);
     $context = $contextclass::instance($entity->id);
     $classname = 'field_data_' . $field->datatype;
     $fielddata = new $classname(array('fieldid' => $field->id));
     $result = $fielddata->set_for_context_and_field($context, $field, $data);
     return $result;
 }
Beispiel #4
0
 function validate_custom_fields($data, $eliscontext)
 {
     $errors = array();
     $contextlevel = \local_eliscore\context\helper::get_level_from_name($eliscontext);
     $fields = field::get_for_context_level($contextlevel);
     $fields = $fields ? $fields : array();
     if (!empty($data['id'])) {
         $contextclass = \local_eliscore\context\helper::get_class_for_level($contextlevel);
         $context = $contextclass::instance($data['id']);
         $contextid = $context->id;
     } else {
         $contextid = 0;
     }
     foreach ($fields as $field) {
         $field = new field($field);
         $key = "field_{$field->shortname}";
         if ($errstr = manual_field_validation(isset($data[$key]) ? $data[$key] : null, $field, $contextid)) {
             $errors[$key] = $errstr;
         }
         //error_log("cmform.class.php::validation(): contextid = {$contextid}, data[{$key}] = {$data[$key]}, errors[$key] = {$errstr}");
     }
     return $errors;
 }
Beispiel #5
0
 /**
  * Fetch the contexts where the user has a given capability.  This only works
  * with the CM context levels.
  *
  * Assumes that the user does not have "too many" role assignments.  Assumes
  * the user has no "prevents"/"prohibits" roles.
  */
 static function for_user_with_capability($contextlevel, $capability, $userid = null, $doanything = true)
 {
     global $USER, $DB;
     static $pm_context_parents = array('track' => array('curriculum'), 'course' => array('curriculum'), 'class' => array('course', 'track'), 'user' => array('cluster'));
     if ($userid === null) {
         $userid = $USER->id;
     }
     $obj = new pm_context_set();
     $obj->contextlevel = $contextlevel;
     // if the user has the capability at the system level (or has the
     // manage master capability), we can stop here
     if (has_capability($capability, context_system::instance(), $userid, $doanything) || has_capability('local/elisprogram:manage', context_system::instance(), $userid, $doanything)) {
         $obj->contexts = array('system' => 1);
         return $obj;
     }
     $contexts = array($contextlevel => array());
     // find all contexts at the given context level where the user has a direct
     // role assignment
     $ctxlevel = \local_eliscore\context\helper::get_level_from_name($contextlevel);
     $ctxclass = \local_eliscore\context\helper::get_class_for_level($ctxlevel);
     $sql = "SELECT c.id, c.instanceid\n                  FROM {role_assignments} ra\n                  JOIN {context} c ON ra.contextid = c.id\n                 WHERE ra.userid = {$userid}\n                   AND c.contextlevel = " . $ctxlevel;
     $possiblecontexts = $DB->get_recordset_sql($sql);
     foreach ($possiblecontexts as $c) {
         $context = $ctxclass::instance($c->instanceid);
         if (has_capability($capability, $context, $userid, $doanything)) {
             $contexts[$contextlevel][] = $context->__get('instanceid');
         }
     }
     if (empty($contexts[$contextlevel])) {
         unset($contexts[$contextlevel]);
     }
     // look in the parent contexts
     if (isset($pm_context_parents[$contextlevel])) {
         foreach ($pm_context_parents[$contextlevel] as $parentlevel) {
             $parent = pm_context_set::for_user_with_capability($parentlevel, $capability, $userid, $doanything);
             $contexts = array_merge($contexts, $parent->contexts);
         }
     }
     $obj->contexts = $contexts;
     return $obj;
 }
 /**
  * Validate that the listing respects the local/elisprogram:track_enrol_userset_user
  * capability as long as the appropriate userset and track are associated to
  * one another and the target user is in the userset
  */
 public function test_availableusersrespectsindirectusersetpermissions()
 {
     global $DB, $USER;
     $this->load_csv_data();
     set_config('siteguest', '');
     set_config('siteadmins', '');
     accesslib_clear_all_caches_for_unit_testing();
     // Create a test user to be in the userset.
     $usersetmember = new user(array('idnumber' => 'usersetmember', 'username' => 'usersetmember', 'firstname' => 'usersetmember', 'lastname' => 'usersetmember', 'email' => '*****@*****.**', 'country' => 'CA'));
     $usersetmember->save();
     // Our test userset.
     $userset = new userset(array('name' => 'userset'));
     $userset->save();
     // Assign the test user to the test userset.
     $clusterassignment = new clusterassignment(array('userid' => $usersetmember->id, 'clusterid' => $userset->id));
     $clusterassignment->save();
     // Assign the userset to our track.
     $clustertrack = new clustertrack(array('clusterid' => $userset->id, 'trackid' => 1));
     $clustertrack->save();
     // Set up a db record for the active user for permissions reasons.
     // (i.e. so they are not treated as an admin).
     $activeuser = new user(array('idnumber' => 'activeuser', 'username' => 'activeuser', 'firstname' => 'activeuser', 'lastname' => 'activeuser', 'email' => '*****@*****.**', 'country' => 'CA'));
     $activeuser->save();
     // Set up our test role.
     $roleid = create_role('testrole', 'testrole', 'testrole');
     $syscontext = context_system::instance();
     assign_capability('local/elisprogram:track_enrol_userset_user', CAP_ALLOW, $roleid, $syscontext->id);
     // Perform the role necessary assignment.
     $moodleuser = $DB->get_record('user', array('username' => 'activeuser'));
     // Make sure all the contexts are created, so that we can find the children.
     $contextclass = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USERSET);
     $instance = $contextclass::instance($userset->id);
     role_assign($roleid, $moodleuser->id, $instance->id);
     // Assume the role of the user with the role assignment.
     $USER = $moodleuser;
     $usersrecset = usertrack::get_available_users(1);
     $users = array();
     foreach ($usersrecset as $key => $user) {
         $users[$key] = $user;
     }
     unset($usersrecset);
     $this->assertEquals(1, count($users));
     // Validate user.
     $this->assertArrayHasKey($usersetmember->id, $users);
     $user = $users[$usersetmember->id];
     $this->assertEquals($usersetmember->username, 'usersetmember');
     // Validate count.
     $count = usertrack::count_available_users(1);
     $this->assertEquals(1, $count);
 }
 /**
  * Create a test custom field category.
  * @return field_category The test category.
  */
 protected function create_field_category($context)
 {
     $data = new stdClass();
     $data->name = \local_eliscore\context\helper::get_class_for_level($context) . ' Test';
     $category = new field_category($data);
     $category->save();
     $categorycontext = new field_category_contextlevel();
     $categorycontext->categoryid = $category->id;
     $categorycontext->contextlevel = $context;
     $categorycontext->save();
     return $category;
 }
Beispiel #8
0
 /**
  * Validate that counting the number of role assignments on a particular
  * cluster for a particular role respects special userset permissions
  */
 public function test_clusterrolepagecountroleusersrespectsusersetpermissions()
 {
     global $CFG, $USER, $DB;
     require_once elispm::lib('data/clusterassignment.class.php');
     require_once elispm::lib('data/user.class.php');
     require_once elispm::lib('data/userset.class.php');
     accesslib_clear_all_caches(true);
     // Create a user record so that Moodle and PM ids don't match by fluke.
     set_config('auto_assign_user_idnumber', 0, 'local_elisprogram');
     elis::$config = new elis_config();
     create_user_record('bogususer', 'Bogususer!0');
     // Create our test userset.
     $userset = new userset(array('name' => 'testuserset'));
     $userset->save();
     // The user who is assigned to the user set.
     $assigneduser = new user(array('idnumber' => 'assigned', 'username' => 'assigned', 'firstname' => 'assigned', 'lastname' => 'assigned', 'email' => '*****@*****.**', 'country' => 'CA'));
     $assigneduser->save();
     // Userset assignment.
     $clusterassignment = new clusterassignment(array('clusterid' => $userset->id, 'userid' => $assigneduser->id));
     $clusterassignment->save();
     // User who is potentially assigning the userset member a new role within the userset.
     $assigninguser = new user(array('idnumber' => 'assigning', 'username' => 'assigning', 'firstname' => 'assigning', 'lastname' => 'assigning', 'email' => '*****@*****.**', 'country' => 'CA'));
     $assigninguser->save();
     // Need the system context for role assignments.
     $systemcontext = context_system::instance();
     // Set up the role that allows a user to assign roles but only to userset members.
     $permissionsroleid = create_role('permissionsrole', 'permissionsrole', 'permissionsrole');
     // Enable the appropriate capabilities.
     assign_capability('moodle/role:assign', CAP_ALLOW, $permissionsroleid, $systemcontext->id);
     assign_capability('local/elisprogram:userset_role_assign_userset_users', CAP_ALLOW, $permissionsroleid, $systemcontext->id);
     // Perform the role assignment.
     $moodleuserid = $DB->get_field('user', 'id', array('username' => 'assigning'));
     role_assign($permissionsroleid, $moodleuserid, $systemcontext->id);
     // Imitate the user assigned the role which allows for further role assignments only on userset members.
     $USER = $DB->get_record('user', array('id' => $moodleuserid));
     // Test role for potential assignment to userset members.
     $roleid = create_role('targetrole', 'targetrole', 'targetrole');
     // Assign the both users to the userset role.
     $contextclass = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USERSET);
     $usersetcontext = $contextclass::instance($userset->id);
     role_assign($roleid, $moodleuserid, $usersetcontext->id);
     $moodleuserid = $DB->get_field('user', 'id', array('username' => 'assigned'));
     role_assign($roleid, $moodleuserid, $usersetcontext->id);
     // Obtain the count of assigned users.
     $page = new cluster_rolepage(array('id' => $userset->id));
     $count = $page->count_role_users($roleid, $usersetcontext);
     // List should only contain the userset member.
     $this->assertEquals(1, $count);
 }
Beispiel #9
0
 /**
  * Convenience function for use by data_object objects
  *
  * @param mixed $contextlevel the context level.  Either a numeric value,
  * or the name of the context level from the ELIS Program Manager
  * @param object $record the data_object to fetch the field values from
  * @return bool  true
  */
 public static function set_for_context_from_datarecord($contextlevel, $record)
 {
     if (!is_numeric($contextlevel)) {
         $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextlevel);
         if (!$contextlevel) {
             // context levels not set up -- we must be in initial installation,
             // so no fields set up
             return true;
         }
     }
     $ctxclass = \local_eliscore\context\helper::get_class_for_level($contextlevel);
     $context = $ctxclass::instance($record->id);
     $fields = field::get_for_context_level($contextlevel);
     $fields = $fields ? $fields : array();
     foreach ($fields as $field) {
         $fieldname = "field_{$field->shortname}";
         if (isset($record->{$fieldname})) {
             self::set_for_context_and_field($context, $field, $record->{$fieldname});
         }
     }
     return true;
 }
Beispiel #10
0
/**
 * Get the default repository location.
 *
 * @uses $CFG, $COURSE, $USER
 * @param int  $cid      A course record ID.
 * @param int  $uid      A user record ID.
 * @param bool $shared   A flag to indicate whether the user is currently located in the shared repository area.
 * @param int  $oid      A userset record ID.
 * @return string The UUID of the last location the user was browsing files in.
 */
    function get_default_browsing_location(&$cid, &$uid, &$shared, &$oid) {
        global $CFG, $COURSE, $USER, $DB;

        // If the default location is not set at all, just return nothing now.
        if (!isset($this->config->default_browse)) {
            return false;
        } elseif (isset($this->config->default_browse)) {
        // Handle determining if the user can actually access the chosen default location.
            if (empty($cid)) {
                $cid = $COURSE->id;
            }
            $syscontext = context_system::instance();
            if ($cid == SITEID) {
                $context = $syscontext;
            } else {
                $context = context_course::instance($cid);
            }

         /* **** Disable following block for ELIS-7127 ****
            // If on ELIS Files page or in course context - default to course page if we have access to it
            if ($cid != SITEID && (has_capability('repository/elisfiles:viewcoursecontent', $context) ||
                has_capability('repository/elisfiles:createcoursecontent', $context))) {
                    $shared = 0;
                    $uid    = 0;
                    return $this->get_course_store($cid);
            } else if ($cid == SITEID && $uid == 0 && (has_capability('repository/elisfiles:viewsitecontent', $context) ||
                        has_capability('repository/elisfiles:createsitecontent', $context))) {
            // If on home page and not in user context - default to Company Home if we have access to it
                    $root = $this->get_root();
                    if (!empty($root->uuid)) {
                        $shared = 0;
                        $uid    = 0;
                        return $root->uuid;
                    }
            }
         **** END Disable block for ELIS-7127 **** */

            $oid = 0;

            /**
             * ELIS-7452: We're gonna go thru all possible browing locations
             * in pre-determined order:
             * User > Site > Shared [> Userset > Course]
             * but we'll put desired default_browsing location first!
             */
            $browsing_locs = array(ELIS_FILES_BROWSE_USER_FILES,
                                   ELIS_FILES_BROWSE_SITE_FILES,
                                   ELIS_FILES_BROWSE_SHARED_FILES,
                                   ELIS_FILES_BROWSE_COURSE_FILES,
                                   ELIS_FILES_BROWSE_USERSET_FILES);

            $default_entry = array_search($this->config->default_browse,
                                          $browsing_locs);
            if ($default_entry !== false) {
                array_splice($browsing_locs, $default_entry, 1);
            }
            $browsing_locs = array_merge(array($this->config->default_browse),
                                         $browsing_locs);

            // If a user does not have permission to access the default location, fall through to the next
            // lower level to see if they can access that location.
            // TBD: MUST CHECK FOR CAPABILITIES AY ANY CONTEXT LEVEL!!!
            foreach ($browsing_locs as $browse_loc) {
                switch ($browse_loc) {
                case ELIS_FILES_BROWSE_SITE_FILES:
                    if (has_capability('repository/elisfiles:viewsitecontent', $syscontext) ||
                        has_capability('repository/elisfiles:createsitecontent', $syscontext)) {

                        $root = $this->get_root();

                        if (!empty($root->uuid)) {
                            $shared = 0;
                            $uid    = 0;
                            $cid    = 0;
                            return $root->uuid;
                        }
                    }
                    break;

                case ELIS_FILES_BROWSE_SHARED_FILES:
                    // Get the non context based permissions
                    $capabilities = array(
                        'repository/elisfiles:viewsharedcontent'  => false,
                        'repository/elisfiles:createsharedcontent'=> false
                    );
                    $this->get_other_capabilities($USER, $capabilities);

                    $has_permission = $capabilities['repository/elisfiles:viewsharedcontent'] ||
                                      $capabilities['repository/elisfiles:createsharedcontent'] ||
                                      has_capability('repository/elisfiles:viewsitecontent', $syscontext) ||
                                      has_capability('repository/elisfiles:createsitecontent', $syscontext);
                    if ($has_permission) {
                        $shared = true;
                        $uid    = 0;
                        $cid    = 0;
                        return $this->suuid;
                    }
                    break;

                case ELIS_FILES_BROWSE_COURSE_FILES:
                    $has_permission = false;
                    if ($cid == SITEID && $COURSE->id != SITEID) {
                        $cid = $COURSE->id;
                    }
                    if (!$cid || $cid == SITEID) {
                        // TBD: no valid $COURSE so just find first one???
                        $courses = enrol_get_my_courses();
                        if (empty($courses)) {
                            $cid = 0;
                            break;
                        }
                        foreach ($courses as $course) {
                            $context = context_course::instance($course->id);
                            $has_permission = has_capability('repository/elisfiles:viewcoursecontent', $context) ||
                                              has_capability('repository/elisfiles:createcoursecontent', $context) ||
                                              has_capability('repository/elisfiles:viewsitecontent', $syscontext) ||
                                              has_capability('repository/elisfiles:createsitecontent', $syscontext);
                            if ($has_permission) {
                                $cid = $course->id;
                                break;
                            }
                        }
                    }
                    if ($cid && $cid != SITEID) {
                        if (!$has_permission) {
                            $context = context_course::instance($cid);
                            $has_permission = has_capability('repository/elisfiles:viewcoursecontent', $context) ||
                                              has_capability('repository/elisfiles:createcoursecontent', $context) ||
                                              has_capability('repository/elisfiles:viewsitecontent', $syscontext) ||
                                              has_capability('repository/elisfiles:createsitecontent', $syscontext);
                        }
                        if ($has_permission) {
                            $shared = 0;
                            $uid    = 0;
                            return $this->get_course_store($cid);
                        }
                    }
                    $cid = 0;
                    break;

                case ELIS_FILES_BROWSE_USER_FILES:
                    $context = context_user::instance($USER->id);

                    $has_permission = has_capability('repository/elisfiles:viewowncontent', $syscontext) ||
                                      has_capability('repository/elisfiles:createowncontent', $syscontext) ||
                                      has_capability('repository/elisfiles:viewowncontent', $context) ||
                                      has_capability('repository/elisfiles:createowncontent', $context) ||
                                      has_capability('repository/elisfiles:viewsitecontent', $syscontext) ||
                                      has_capability('repository/elisfiles:createsitecontent', $syscontext);
                    if ($has_permission) {

                        if (empty($this->uuuid)) {
                            $this->uuuid = $this->elis_files_userdir($USER->username);
                        }
                        if (($uuid = $this->uuuid) !== false) {
                            $shared = 0;
                            $uid    = $USER->id;
                            $cid    = 0;
                            return $uuid;
                        }
                    }
                    break;

                case ELIS_FILES_BROWSE_USERSET_FILES:
                    if (!file_exists($CFG->dirroot.'/local/elisprogram/accesslib.php')) {
                        break;
                    }
                    require_once($CFG->dirroot.'/local/elisprogram/accesslib.php');
                    require_once($CFG->dirroot.'/local/elisprogram/lib/setup.php');
                    require_once($CFG->dirroot.'/local/elisprogram/lib/deprecatedlib.php');
                    $crlm_user = cm_get_crlmuserid($USER->id);
                    if ($crlm_user === false) {
                        break;
                    }
                    $contextclass = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USERSET);
                    $assignments = $DB->get_records('local_elisprogram_uset_asign',
                                                    array('userid' => $crlm_user));
                    // TBD: just get the first valid userset store???
                    foreach ($assignments as $cluster_assignment) {
                        $context = $contextclass::instance($cluster_assignment->clusterid);

                        $has_permission = has_capability('repository/elisfiles:viewusersetcontent', $context) ||
                                          has_capability('repository/elisfiles:createusersetcontent', $context) ||
                                          has_capability('repository/elisfiles:viewsitecontent', $syscontext) ||
                                          has_capability('repository/elisfiles:createsitecontent', $syscontext);
                        if ($has_permission) {
                            $uuid = $this->get_userset_store($cluster_assignment->clusterid);
                            if (!empty($uuid)) {
                                $oid    = $cluster_assignment->clusterid;
                                $shared = 0;
                                $uid    = 0;
                                $cid    = 0;
                                return $uuid;
                            }
                        }
                    }
                    break;
                }
            }
        }

        return false;
    }
Beispiel #11
0
 /**
  * Create an ELIS custom field.
  * @param field_category &$cat The category to create the field in.
  * @param int $context The context level constant to create the category for (ex. CONTEXT_ELIS_USER)
  * @return field The created field.
  */
 protected function create_field(field_category &$cat, $context)
 {
     $data = new stdClass();
     $data->shortname = \local_eliscore\context\helper::get_class_for_level($context) . '_testfield';
     $data->name = ' Test Field';
     $data->categoryid = $cat->id;
     $data->description = 'Test Field';
     $data->datatype = 'text';
     $data->forceunique = '0';
     $data->mform_showadvanced_last = 0;
     $data->multivalued = '0';
     $data->defaultdata = '';
     $data->manual_field_enabled = '1';
     $data->manual_field_edit_capability = '';
     $data->manual_field_view_capability = '';
     $data->manual_field_control = 'text';
     $data->manual_field_options_source = '';
     $data->manual_field_options = '';
     $data->manual_field_columns = 30;
     $data->manual_field_rows = 10;
     $data->manual_field_maxlength = 2048;
     $field = new field($data);
     $field->save();
     $fieldcontext = new field_contextlevel();
     $fieldcontext->fieldid = $field->id;
     $fieldcontext->contextlevel = $context;
     $fieldcontext->save();
     $owner = new field_owner();
     $owner->fieldid = $field->id;
     $owner->plugin = 'manual';
     $owner->params = serialize(array('required' => false, 'edit_capability' => '', 'view_capability' => '', 'control' => 'text', 'columns' => 30, 'rows' => 10, 'maxlength' => 2048, 'startyear' => '1970', 'stopyear' => '2038', 'inctime' => '0'));
     $owner->save();
     return $field;
 }
Beispiel #12
0
 /**
  * Test that you can delete and promote user subsets
  */
 public function test_deletingrecordcanpromoteusersubsets()
 {
     $this->load_csv_data();
     accesslib_clear_all_caches(true);
     // Make sure all the contexts are created, so that we can find the children.
     $contextclass = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USERSET);
     for ($i = 1; $i <= 4; $i++) {
         $clustercontextinstance = $contextclass::instance($i);
     }
     // Delete a record.
     $src = new userset(2, null, array(), false, array());
     $src->deletesubs = false;
     $src->delete();
     // Read it back.
     $result = new moodle_recordset_phpunit_datatable(userset::TABLE, userset::find(null, array(), 0, 0));
     $dataset = new PHPUnit_Extensions_Database_DataSet_CsvDataSet();
     $dataset->addTable(userset::TABLE, elispm::file('tests/fixtures/userset_promote_test_result.csv'));
     $this->assertTablesEqual($dataset->getTable(userset::TABLE), $result);
 }
 /**
  * Ensure that the context is loaded for this record.
  */
 private function _load_context()
 {
     if (!isset($this->_context) && isset($this->id)) {
         $ctxclass = \local_eliscore\context\helper::get_class_for_level($this->get_field_context_level());
         $this->_context = $ctxclass::instance($this->id);
     }
 }
 /**
  * Validate multi-valued custom field data update removes previous selection
  *
  * @dataProvider entity_type_provider
  * @param string $entitytype The type of entity we are running the import for
  * @param array $record The inport record to process
  * @param string $contextlevelname The name used to refer to the appropriate context level
  * @param string $fileidentifier The entity type represented by the input file
  * @param mixed $parententitytype The parent entity type, or null if none
  * @param mixed $parentrecord The parent data record, or null if none
  * @param mixed $parentreffield The field used to refer to the parent element, or null if none
  * @param mixed $ipparentreffield The field used to refer to the parent element in IP, or null if none
  */
 public function test_multivalue_field_data_update_overwrites_previous_selection($entitytype, $record, $contextlevelname, $fileidentifier, $parententitytype = null, $parentrecord = null, $parentreffield = null, $ipparentreffield = null)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elis::lib('data/customfield.class.php');
     require_once elispm::lib('data/' . $entitytype . '.class.php');
     // Set up the custom field, category, context association, and owner.
     $fieldid = $this->create_test_field($contextlevelname, 'int', 'menu', true, array('1', '2', '3', '4'), null, null);
     // Create parent entity if needed.
     if ($parentid = $this->create_parent_entity($parententitytype, $parentrecord, $parentreffield)) {
         $record[$parentreffield] = $parentid;
     }
     // Persist the entity.
     $entity = new $entitytype();
     $entity->set_from_data((object) array_merge($record, array('field_testfieldshortname' => array('4'))));
     $entity->save();
     $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextlevelname);
     $contextlevel = \local_eliscore\context\helper::get_class_for_level($contextlevel);
     $instance = $contextlevel::instance($entity->id);
     // Validate setup.
     $this->assertEquals(1, $DB->count_records(field_data_int::TABLE));
     $this->assertTrue($DB->record_exists(field_data_int::TABLE, array('fieldid' => $fieldid, 'contextid' => $instance->id, 'data' => '4')));
     $record['action'] = 'update';
     $record['testfieldshortname'] = '1/2/3';
     // Run the entity update action.
     $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis');
     $importplugin->fslogger = new silent_fslogger(null);
     $importplugin->process_record($fileidentifier, (object) $record, 'bogus');
     // Validation.
     $this->assert_field_values($contextlevelname, $entitytype::TABLE, field_data_int::TABLE, $fieldid, array('1', '2', '3'));
 }
Beispiel #15
0
 /**
  * Perform the necessary actions required to "delete" a cluster from the system.
  *
  * @param none
  * @return bool True on success, False otherwise.
  */
 function delete()
 {
     require_once elis::lib('data/data_filter.class.php');
     if ($this->deletesimple) {
         //core delete method, not including recursion (entered once for each
         //individual userset being delete)
         //clean make the delete cascade into association records
         $filter = new field_filter('clusterid', $this->id);
         clustercurriculum::delete_records($filter, $this->_db);
         clustertrack::delete_records($filter, $this->_db);
         clusterassignment::delete_records($filter, $this->_db);
         //cluster plugin cleanup
         $plugins = get_plugin_list(self::ENROL_PLUGIN_TYPE);
         foreach ($plugins as $plugin => $plugindir) {
             require_once elis::plugin_file(self::ENROL_PLUGIN_TYPE . '_' . $plugin, 'lib.php');
             call_user_func('cluster_' . $plugin . '_delete_for_cluster', $this->id);
         }
         //delete the userset record
         parent::delete();
         //delete this cluster's context
         //get a new context instance,
         $contextclass = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USERSET);
         $userset_context = $contextclass::instance($this->id);
         $userset_context->delete();
         events_trigger('cluster_deleted', $this->id);
         return;
     }
     $result = true;
     $children = array();
     $delete_ids = array();
     $promote_ids = array();
     /// Figure out all the sub-clusters
     $cluster_context_instance = \local_elisprogram\context\userset::instance($this->id);
     $instance_id = $cluster_context_instance->id;
     $instance_path = $cluster_context_instance->path;
     $children = userset::find(new join_filter('id', 'context', 'instanceid', new AND_filter(array(new field_filter('path', "{$instance_path}/%", field_filter::LIKE), new field_filter('contextlevel', CONTEXT_ELIS_USERSET)))), array('depth' => 'ASC'), 0, 0, $this->_db);
     $children = $children->to_array();
     if ($this->deletesubs) {
         $todelete = $children;
         $todelete[] = $this;
         // The specified cluster always gets deleted
     } else {
         $todelete = array($this);
     }
     foreach ($todelete as $userset) {
         //delete without recursion
         $userset->deletesimple = true;
         $userset->delete();
     }
     if (!$this->deletesubs && !empty($children)) {
         foreach ($children as $child) {
             $lower_depth = $child->depth - 1;
             if (userset::exists(new field_filter('id', $child->parent))) {
                 /// A parent found so lets lower the depth
                 $child->depth = 0;
             } else {
                 /// Parent not found so this cluster will be top-level
                 $child->parent = 0;
                 $child->depth = 1;
             }
             $child->save();
             $sql = "UPDATE {context}\n                        SET depth=0, path=NULL\n                        WHERE contextlevel=? AND instanceid=?";
             $this->_db->execute($sql, array(CONTEXT_ELIS_USERSET, $child->id));
         }
         \local_eliscore\context\helper::build_all_paths(false, array(CONTEXT_ELIS_USERSET));
         // Re-build the context table for all sub-clusters
     }
     return $result;
 }