Example #1
0
 /**
  * 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;
 }
 /**
  * Helper function for creating a Moodle user profile field
  *
  * @param string $name Profile field shortname
  * @param string $datatype Profile field data type
  * @param int $categoryid Profile field category id
  * @return int The id of the created profile field
  */
 private function create_profile_field($name, $datatype, $categoryid, $contextlevelname = 'user')
 {
     global $CFG;
     require_once $CFG->dirroot . '/local/eliscore/lib/data/customfield.class.php';
     $file = get_plugin_directory('dhimport', 'version1elis') . '/lib.php';
     require_once $file;
     $field = new field(array('categoryid' => $categoryid, 'shortname' => $name, 'name' => $name));
     $field->save();
     // Field contextlevel.
     $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextlevelname);
     $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => $contextlevel));
     $fieldcontextlevel->save();
     return $field->id;
 }
Example #3
0
/**
 * ELIS(TM): Enterprise Learning Intelligence Suite
 * Copyright (C) 2008-2013 Remote-Learner.net Inc (http://www.remote-learner.net)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    local_elisprogram
 * @author     Remote-Learner.net Inc
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @copyright  (C) 2008-2013 Remote Learner.net Inc http://www.remote-learner.net
 *
 */
function xmldb_local_elisprogram_install()
{
    global $CFG, $DB;
    $elisadminblockinstalled = file_exists($CFG->dirroot . '/local/elisprogram/lib/setup.php') && $DB->record_exists('block', array('name' => 'elisadmin'));
    if ($elisadminblockinstalled) {
        require_once $CFG->dirroot . '/blocks/elisadmin/lib.php';
    }
    require_once $CFG->dirroot . '/local/elisprogram/lib/lib.php';
    // Install custom context levels.
    \local_eliscore\context\helper::set_custom_levels(\local_elisprogram\context\contextinfo::get_contextinfo());
    \local_eliscore\context\helper::install_custom_levels();
    // Initialize custom context levels.
    context_helper::reset_levels();
    \local_eliscore\context\helper::reset_levels();
    \local_eliscore\context\helper::init_levels();
    // Migrate component.
    $migrator = new \local_elisprogram\install\migration\elis26();
    if ($migrator->old_component_installed() === true) {
        $migrator->migrate();
    }
    //make sure the site has exactly one curr admin block instance
    //that is viewable everywhere
    if ($elisadminblockinstalled) {
        block_elisadmin_create_instance();
    }
    // make sure that the manager role can be assigned to all PM context levels
    update_capabilities('local_elisprogram');
    // load context levels
    pm_ensure_role_assignable('manager');
    pm_ensure_role_assignable('curriculumadmin');
    // Migrate dataroot files
    pm_migrate_certificate_files();
    // These notifications are default-on.
    pm_set_config('notify_addedtowaitlist_user', 1);
    pm_set_config('notify_enroledfromwaitlist_user', 1);
    pm_set_config('notify_incompletecourse_user', 1);
    // Ensure ELIS scheduled tasks is initialized.
    require_once $CFG->dirroot . '/local/eliscore/lib/tasklib.php';
    elis_tasks_update_definition('local_elisprogram');
    // Remove some lingering subplugins that were renamed
    unset_all_config_for_plugin('usersetenrol_manual');
    unset_all_config_for_plugin('usersetenrol_moodle_profile');
}
Example #4
0
 /**
  * Test the migrate_contextlevels function.
  */
 public function test_migrate_contextlevels()
 {
     global $DB;
     // Setup.
     $ctxoldnewmap = array(1001 => \local_eliscore\context\helper::get_level_from_name('curriculum'), 1002 => \local_eliscore\context\helper::get_level_from_name('track'), 1003 => \local_eliscore\context\helper::get_level_from_name('course'), 1004 => \local_eliscore\context\helper::get_level_from_name('class'), 1005 => \local_eliscore\context\helper::get_level_from_name('user'), 1006 => \local_eliscore\context\helper::get_level_from_name('cluster'));
     $createdrecs = array();
     foreach ($ctxoldnewmap as $oldlevel => $newlevel) {
         $context = new \stdClass();
         $context->contextlevel = $oldlevel;
         $context->instanceid = '1' . $oldlevel;
         $context->path = '/2/' . $oldlevel;
         $context->depth = 2;
         $context->id = $DB->insert_record('context', $context);
         $createdrecs['context'][$oldlevel] = $context->id;
         $fieldclevel = new \stdClass();
         $fieldclevel->fieldid = '2' . $oldlevel;
         $fieldclevel->contextlevel = $oldlevel;
         $fieldclevel->id = $DB->insert_record('local_eliscore_field_clevels', $fieldclevel);
         $createdrecs['local_eliscore_field_clevels'][$oldlevel] = $fieldclevel->id;
         $catctx = new \stdClass();
         $catctx->categoryid = '3' . $oldlevel;
         $catctx->contextlevel = $oldlevel;
         $catctx->id = $DB->insert_record('local_eliscore_fld_cat_ctx', $catctx);
         $createdrecs['local_eliscore_fld_cat_ctx'][$oldlevel] = $catctx->id;
         $rolectx = new \stdClass();
         $rolectx->roleid = '3' . $oldlevel;
         $rolectx->contextlevel = $oldlevel;
         $rolectx->id = $DB->insert_record('role_context_levels', $rolectx);
         $createdrecs['role_context_levels'][$oldlevel] = $rolectx->id;
     }
     // Migrate.
     $migrator = new \local_elisprogram\install\migration\elis26();
     $migrator->migrate_context_levels();
     // Check records.
     foreach ($createdrecs as $table => $recs) {
         foreach ($recs as $oldlevel => $recid) {
             $newlevel = $ctxoldnewmap[$oldlevel];
             $rec = $DB->get_record($table, array('id' => $recid));
             $this->assertEquals($newlevel, $rec->contextlevel);
         }
     }
 }
 public function validation($data, $files)
 {
     global $DB;
     $errors = array();
     $level = required_param('level', PARAM_ACTION);
     $ctxlvl = \local_eliscore\context\helper::get_level_from_name($level);
     if (!empty($ctxlvl)) {
         $sql = 'SELECT cat.id
             FROM {local_eliscore_field_cats} cat
             JOIN {local_eliscore_fld_cat_ctx} ctx ON cat.id = ctx.categoryid
             WHERE ctx.contextlevel = ? AND cat.name=?';
         $params = array($ctxlvl, $data['name']);
         $existing_catname = $DB->get_recordset_sql($sql, $params);
         if ($existing_catname->valid() === true) {
             $a = new stdClass();
             $a->tablename = 'local_eliscore_field_cats';
             $a->fields = 'name';
             $errors['name'] = get_string('data_object_validation_unique', 'local_eliscore', $a);
         }
         unset($existing_catname);
     }
     return $errors;
 }
Example #6
0
 /**
  * Migrate context levels.
  */
 public function migrate_context_levels()
 {
     global $DB;
     // Migrate old custom context levels.
     $ctxoldnewmap = array(1001 => \local_eliscore\context\helper::get_level_from_name('curriculum'), 1002 => \local_eliscore\context\helper::get_level_from_name('track'), 1003 => \local_eliscore\context\helper::get_level_from_name('course'), 1004 => \local_eliscore\context\helper::get_level_from_name('class'), 1005 => \local_eliscore\context\helper::get_level_from_name('user'), 1006 => \local_eliscore\context\helper::get_level_from_name('cluster'));
     foreach ($ctxoldnewmap as $oldctxlevel => $newctxlevel) {
         // Update context table.
         $sql = 'UPDATE {context} SET contextlevel = ? WHERE contextlevel = ?';
         $params = array($newctxlevel, $oldctxlevel);
         $DB->execute($sql, $params);
         // Update role context levels.
         $sql = 'UPDATE {role_context_levels} SET contextlevel = ? WHERE contextlevel = ?';
         $params = array($newctxlevel, $oldctxlevel);
         $DB->execute($sql, $params);
         // Update custom field context levels.
         $sql = 'UPDATE {local_eliscore_field_clevels} SET contextlevel = ? WHERE contextlevel = ?';
         $params = array($newctxlevel, $oldctxlevel);
         $DB->execute($sql, $params);
         // Update custom field category context levels.
         $sql = 'UPDATE {local_eliscore_fld_cat_ctx} SET contextlevel = ? WHERE contextlevel = ?';
         $params = array($newctxlevel, $oldctxlevel);
         $DB->execute($sql, $params);
     }
 }
 /**
  * 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;
 }
Example #8
0
 /**
  * Rebuild context paths and depths at ELIS course context level.
  *
  * @static
  * @param bool $force Set to false to include records whose path is null or depth is zero
  */
 protected static function build_paths($force)
 {
     global $DB;
     $contextlevel = \local_eliscore\context\helper::get_level_from_class_name(get_called_class());
     if ($force or $DB->record_exists_select('context', "contextlevel = " . $contextlevel . " AND (depth = 0 OR path IS NULL)")) {
         $emptyclause = $force ? '' : "AND ({context}.path IS NULL OR {context}.depth = 0)";
         $base = '/' . SYSCONTEXTID;
         // Normal top level categories
         $sql = "UPDATE {context}\n                       SET depth = 2,\n                           path = " . $DB->sql_concat("'{$base}/'", 'id') . "\n                     WHERE contextlevel = " . $contextlevel . "\n                           AND EXISTS (SELECT 'x'\n                                         FROM {local_elisprogram_crs} ep\n                                        WHERE ep.id = {context}.instanceid)\n                           {$emptyclause}";
         $DB->execute($sql);
     }
 }
 /**
  * Return a boolean to indicate whether or not this filter is displayed
  * depending upon whether any custom fields are found for this user
  * @param string       $field_type  type of custom field to check
  * @return boolean  true if the filter is to show
  */
 function check_for_custom_fields($field_type)
 {
     // Get custom course fields by context level
     $context = \local_eliscore\context\helper::get_level_from_name($field_type);
     $fields = field::get_for_context_level($context);
     $fields = $fields ? $fields : array();
     $testfields = array();
     foreach ($fields as $field) {
         //make sure the current user can access this field in at least one
         //course context
         if (!$this->field_accessible($field)) {
             continue;
         }
         return true;
     }
     return false;
 }
Example #10
0
 /**
  * Displays the portion of the field editing form specific to a context level
  *
  * @param  string  $contextlevel_name  The description of the context level, such
  *                                     as 'course' or 'class'
  * @param  string  $field_header       The display string used for the header above
  *                                     the field value entry elements
  * @param  string  $button_text        Text to display on the add button
  * @uses   $CFG
  * @uses   $DB
  */
 private function display_for_context($contextlevel_name, $field_header, $button_text)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/elisprogram/lib/contexts.php';
     $fields = field::get_for_context_level($contextlevel_name)->to_array();
     $fields = $fields ? $fields : array();
     // only retrieve fields for the specified context level
     $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextlevel_name);
     $questions = $DB->get_records('block_courserequest_fields', array('contextlevel' => $contextlevel));
     print '<fieldset class="hidden">';
     if (!empty($questions)) {
         print '<table cellpadding="2">';
         print '<tr align="right">';
         // print '<th><span style="margin-right:10px;">'.get_string('name_on_form', 'block_courserequest').'</span></th>';
         print '<th><span style="margin-right:10px;">' . get_string('existing_fields', 'block_courserequest') . '</span></th>';
         print '<th><span style="margin-right:10px;">' . $field_header . '</span></th>';
         print '</tr>';
         foreach ($questions as $question) {
             print '<tr>';
             if ($question->fieldid) {
                 $field = new field($question->fieldid);
                 try {
                     $fieldname = $field->name;
                 } catch (dml_missing_record_exception $ex) {
                     continue;
                     // ELIS-4014: custom field deleted!
                 }
             } else {
                 $fieldname = 'select a field';
             }
             // print "<td><input type="text" name=\"custom_name[]\" value=\"$value\" /></td>";
             print "<td>{$fieldname}</td>";
             print "<td><select name=\"field[{$question->id}]\" />";
             // print '<option value="none">none</option>';
             foreach ($fields as $f) {
                 if ($f->id == $question->fieldid) {
                     print '<option value="' . $f->id . '" selected="true">' . $f->name . '</option>';
                     $selected = true;
                 } else {
                     print '<option value="' . $f->id . '">' . $f->name . '</option>';
                 }
             }
             print "</select></td>";
             print "<td><input type=\"submit\" name=\"delete[{$question->id}]\" value=\"" . get_string('delete', 'block_courserequest') . '" /></td>';
             print '</tr>';
         }
         print '</table>';
     }
     $add_element_name = "add_field_{$contextlevel}";
     print '<div style="margin-top:5px"><input type="submit" name="' . $add_element_name . '" value="' . $button_text . '" /></div>';
     print '</fieldset>';
 }
Example #11
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);
 }
Example #12
0
 /**
  * Rebuild context paths and depths at ELIS User Set context level.
  *
  * @static
  * @param bool $force Set to false to include records whose path is null or depth is zero
  */
 protected static function build_paths($force)
 {
     global $DB;
     $contextlevel = \local_eliscore\context\helper::get_level_from_class_name(get_called_class());
     if ($force or $DB->record_exists_select('context', "contextlevel = " . $contextlevel . " AND (depth = 0 OR path IS NULL)")) {
         if ($force) {
             $ctxemptyclause = $emptyclause = '';
         } else {
             $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
             $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
         }
         $base = '/' . SYSCONTEXTID;
         // Normal top level user sets
         $sql = "UPDATE {context}\n                       SET depth = 2,\n                           path = " . $DB->sql_concat("'{$base}/'", 'id') . "\n                     WHERE contextlevel = " . $contextlevel . "\n                           AND EXISTS (SELECT 'x'\n                                         FROM {" . \userset::TABLE . "} eu\n                                        WHERE eu.id = {context}.instanceid AND eu.depth = 1)\n                           {$emptyclause}";
         $DB->execute($sql);
         // Deeper categories - one query per depthlevel
         $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {" . \userset::TABLE . "}");
         for ($n = 2; $n <= $maxdepth; $n++) {
             $sql = "INSERT INTO {context_temp} (id, path, depth)\n                        SELECT ctx.id, " . $DB->sql_concat('pctx.path', "'/'", 'ctx.id') . ", pctx.depth+1\n                          FROM {context} ctx\n                          JOIN {" . \userset::TABLE . "} eu ON (eu.id = ctx.instanceid AND ctx.contextlevel = " . $contextlevel . " AND eu.depth = {$n})\n                          JOIN {context} pctx ON (pctx.instanceid = eu.parent AND pctx.contextlevel = " . $contextlevel . ")\n                         WHERE pctx.path IS NOT NULL AND pctx.depth > 0\n                               {$ctxemptyclause}";
             $trans = $DB->start_delegated_transaction();
             $DB->delete_records('context_temp');
             $DB->execute($sql);
             \local_eliscore\context\base::merge_context_temp_table();
             $DB->delete_records('context_temp');
             $trans->allow_commit();
         }
     }
 }
 /**
  * Determines if standard and custom curriculum fields are included in the
  * details report.  This function is needed in order to resolve the issues
  * described in EOPSS-70
  *
  * @param array array of fields included with the report
  * @uses   $DB
  * @return boolean - false if no custom curriculum fields are included
  */
 protected function custom_fields_included($filters)
 {
     global $DB;
     $levels = array();
     $no_custom_fields = true;
     foreach (array('curriculum', 'course', 'class') as $entity) {
         $level = \local_eliscore\context\helper::get_level_from_name($entity);
         if ($level) {
             $levels[] = $level;
             $no_custom_fields = false;
         } else {
             error_log("UCCDR::custom_fields_included(); NO custom field context level for '{$entity}'!");
         }
     }
     if ($no_custom_fields) {
         return false;
     }
     foreach ($filters as $key => $filter) {
         foreach ($filter['value'] as $field_alias => $filter_value) {
             // If the filter_value is 0 then we don't need to worry about it
             if ($filter_value) {
                 if (false !== ($pos = strpos($field_alias, '_'))) {
                     // Determine whether this field has a 'custom' prefix
                     $custom_field_name = substr($field_alias, 0, $pos);
                     // Get the custom field id
                     if (0 == strcmp($custom_field_name, 'custom')) {
                         // Only get the last part of the field name as it contains the custom field id
                         $custom_field_id = substr($field_alias, $pos + 1);
                         //TBD: Check the custom field
                         if ($DB->record_exists_select(field_contextlevel::TABLE, "fieldid = {$custom_field_id} AND contextlevel IN (" . implode(', ', $levels) . ')')) {
                             //error_log("UCCDR::custom_fields_included(): fieldid {$custom_field_id} exists for an ELIS contextlevel!");
                             return true;
                         }
                     } else {
                         if (0 == strcmp($field_alias, 'cur_name')) {
                             return true;
                         }
                     }
                 }
             }
         }
     }
     return false;
 }
 /**
  * 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);
     }
 }
 /**
  * Create the test custom profile field and owner
  *
  * @param string $contextlevelname The name of the custom context level to create the field at
  * @param string $name PM custom field shortname
  * @param string $datatype The string identifier of the data type to use
  * @param string $uitype The string identifier of the UI / control type to use
  * @param int $categoryid PM custom field category id
  * @param string $options Extra parameter, used for select options
  * @param string $defaultdata Default value.
  *
  * @return int The id of the created field
  */
 private function create_test_field($contextlevelname = 'user', $name = 'testfieldname', $datatype, $uitype, $categoryid, $options = null, $defaultdata = null)
 {
     global $CFG;
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elis::lib('data/customfield.class.php');
     // Category contextlevel.
     $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextlevelname);
     $fieldcategorycontextlevel = new field_category_contextlevel(array('categoryid' => $categoryid, 'contextlevel' => $contextlevel));
     $fieldcategorycontextlevel->save();
     // Field.
     $field = new field(array('shortname' => 'testfieldshortname', 'name' => $name, 'categoryid' => $categoryid, 'datatype' => $datatype));
     $field->save();
     // Field_data if a default value needs to be set.
     if ($defaultdata !== null) {
         $classname = 'field_data_' . $datatype;
         $fielddata = new $classname(array('fieldid' => $field->id, 'data' => $defaultdata));
         $fielddata->save();
     }
     // Field contextlevel.
     $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => $contextlevel));
     $fieldcontextlevel->save();
     // Field owner.
     $ownerdata = array('control' => $uitype);
     if ($options !== null) {
         // Set options.
         $options = is_array($options) ? implode("\n", $options) : $options;
         $ownerdata['options'] = $options;
     }
     field_owner::ensure_field_owner_exists($field, 'manual', $ownerdata);
     return $field;
 }
Example #16
0
 /**
  * Make field list
  *
  * @param array $groups A two dimensional array of groups => choices => values
  */
 function make_field_list($groups)
 {
     // Force $groups to be an associative array
     foreach ($groups as $key => $choices) {
         if (!$this->is_assoc_array($choices)) {
             $groups[$key] = array_fill_keys($choices, '');
         }
     }
     if (get_class($this) != 'generalized_filter_userprofilematch') {
         // UPM filter uses Moodle profile, we should obey 'extra' option
         // Generate a list of custom fields
         foreach ($this->sections as $group => $section) {
             $ctxtlvl = \local_eliscore\context\helper::get_level_from_name($section['name']);
             $this->sections[$group]['contextlevel'] = $ctxtlvl;
             // Add custom fields to array
             $extrafields = field::get_for_context_level($ctxtlvl);
             $this->get_custom_fields($group, $extrafields);
         }
     }
     // Generate the standard fields
     foreach ($groups as $group => $choices) {
         $custom_fields = isset($this->_fields[$group]) ? $this->_fields[$group] : array();
         $this->_fields[$group] = array();
         foreach ($choices as $name => $alias) {
             $label = $name;
             if (!empty($alias)) {
                 $label = get_string($alias, $this->languagefile);
             } else {
                 if (isset($this->labels[$group]) && array_key_exists($name, $this->labels[$group])) {
                     $label = get_string($this->labels[$group][$name], $this->languagefile);
                 } else {
                     foreach ($this->sections as $section) {
                         if (array_key_exists($name, $section['custom'])) {
                             $label = $section['custom'][$name];
                         }
                     }
                 }
             }
             $this->_fields[$group][$name] = $label;
         }
         if (!empty($this->sections[$group]['custom'])) {
             $this->_fields[$group] = array_merge($this->_fields[$group], $this->sections[$group]['custom']);
         }
         if (!empty($custom_fields)) {
             $this->_fields[$group] = array_merge($this->_fields[$group], $custom_fields);
         }
     }
 }
Example #17
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;
 }
Example #18
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;
    }
Example #19
0
 /**
  * Rebuild context paths and depths at ELIS track context level.
  *
  * @static
  * @param bool $force Set to false to include records whose path is null or depth is zero
  */
 protected static function build_paths($force)
 {
     global $DB;
     $contextlevel = \local_eliscore\context\helper::get_level_from_class_name(get_called_class());
     if ($force or $DB->record_exists_select('context', "contextlevel = " . $contextlevel . " AND (depth = 0 OR path IS NULL)")) {
         $ctxemptyclause = $force ? '' : "AND (ctx.path IS NULL OR ctx.depth = 0)";
         $parentcontextlevel = \local_eliscore\context\helper::get_level_from_class_name('\\local_elisprogram\\context\\program');
         $sql = "INSERT INTO {context_temp} (id, path, depth)\n                    SELECT ctx.id, " . $DB->sql_concat('pctx.path', "'/'", 'ctx.id') . ", pctx.depth+1\n                      FROM {context} ctx\n                      JOIN {local_elisprogram_trk} trk ON (trk.id = ctx.instanceid AND ctx.contextlevel = " . $contextlevel . ")\n                      JOIN {context} pctx ON (pctx.instanceid = trk.curid AND pctx.contextlevel = " . $parentcontextlevel . ")\n                     WHERE pctx.path IS NOT NULL AND pctx.depth > 0\n                           {$ctxemptyclause}";
         $trans = $DB->start_delegated_transaction();
         $DB->delete_records('context_temp');
         $DB->execute($sql);
         \local_eliscore\context\base::merge_context_temp_table();
         $DB->delete_records('context_temp');
         $trans->allow_commit();
     }
 }
Example #20
0
 /**
  * Test validate_custom_fields function.
  */
 public function test_validatecustomfields()
 {
     // Get a form.
     $frm = new test_moodleform();
     $contextlevels = \local_eliscore\context\helper::get_legacy_levels();
     foreach ($contextlevels as $ctxname => $ctxlvl) {
         $category = $this->create_field_category($ctxlvl);
         $field = $this->create_field($category, $ctxlvl);
         switch ($ctxname) {
             case 'curriculum':
                 // Create a curriculum.
                 $cur = $this->create_curriculum($field);
                 // Set up a dummy custom field with a default value.
                 $testvalue = array('id' => $cur->id, 'field_' . $field->shortname => '');
                 break;
             case 'track':
                 // Create a track.
                 $trk = $this->create_track($cur, $field);
                 // Set up a dummy custom field with a default value.
                 $testvalue = array('id' => $trk->id, 'field_' . $field->shortname => '');
                 break;
             case 'course':
                 // Create a course.
                 $crs = $this->create_course($field);
                 // Set up a dummy custom field with a default value.
                 $testvalue = array('id' => $crs->id, 'field_' . $field->shortname => '');
                 break;
             case 'class':
                 // Create a class.
                 $cls = $this->create_class($crs, $field);
                 // Set up a dummy custom field with a default value.
                 $testvalue = array('id' => $cls->id, 'field_' . $field->shortname => '');
                 break;
             case 'user':
                 // Create a user.
                 $user = $this->create_user($field);
                 // Set up a dummy custom field with a default value.
                 $testvalue = array('id' => $user->id, 'field_' . $field->shortname => '');
                 break;
             case 'cluster':
                 // Create a userset.
                 $userset = $this->create_userset($field);
                 // Set up a dummy custom field with a default value.
                 $testvalue = array('id' => $userset->id, 'field_' . $field->shortname => '');
                 break;
         }
         $return = $frm->validate_custom_fields($testvalue, $ctxname);
         $this->assertEmpty($return);
     }
 }
Example #21
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);
 }
Example #22
0
 /**
  * Obtains the listing of fields that are available for the specified
  * entity type
  *
  * @param string $entitytype The type of entity
  */
 function get_available_fields($entitytype)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/eliscore/lib/setup.php';
     require_once $CFG->dirroot . '/local/elisprogram/accesslib.php';
     require_once elis::lib('data/customfield.class.php');
     if ($this->plugin_supports($entitytype) !== false) {
         $attribute = 'available_fields_' . $entitytype;
         $result = array_merge(array('action'), static::${$attribute});
         // enrolments do not have custom fields
         if ($entitytype == 'enrolment') {
             return $result;
         }
         if (!is_numeric($entitytype)) {
             $entitytype = \local_eliscore\context\helper::get_level_from_name($entitytype);
         }
         // courses get all custom fields except user custom fields
         if ($entitytype == CONTEXT_ELIS_COURSE) {
             $contextsql = "ctx.contextlevel != " . CONTEXT_ELIS_USER;
         } else {
             if ($entitytype == CONTEXT_ELIS_USER) {
                 $contextsql = "ctx.contextlevel = {$entitytype}";
             } else {
                 // unsupported entity type
                 return $result;
             }
         }
         //add ELIS custom fields - get by context
         $sql = "SELECT field.shortname\n                      FROM {" . field::TABLE . "} field\n                      JOIN {" . field_contextlevel::TABLE . "} ctx ON ctx.fieldid = field.id AND " . $contextsql;
         if ($fields = $DB->get_recordset_sql($sql)) {
             foreach ($fields as $field) {
                 $result[] = $field->shortname;
             }
         }
         // make sure there are no duplicate field shortnames returned
         return array_unique($result);
     } else {
         return false;
     }
 }
 /**
  * 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);
 }
Example #24
0
 /**
  * Constructor
  *
  * @param string $uniqueid Unique prefix for filters
  * @param string $label    Filter label
  * @param array  $options  Filter options (see above)
  * @return array The sub-filters
  * @uses $PAGE
  */
 function generalized_filter_curriculumclass($uniqueid, $label, $options = array())
 {
     global $PAGE;
     parent::__construct($uniqueid, $label, $options);
     $this->_fields = array();
     if (empty($options['help'])) {
         $options['help'] = array();
     }
     // Get table aliases
     if (empty($options['tables'])) {
         $options['tables'] = array();
     }
     $allfields = array();
     foreach ($this->labels as $group => $labels) {
         foreach ($labels as $key => $val) {
             $this->record_short_field_name($group . '-' . $key);
         }
     }
     // Check for & assign table aliases
     foreach ($this->tables as $group => $tables) {
         if (!array_key_exists($group, $options['tables'])) {
             continue;
         }
         foreach ($tables as $key => $val) {
             if (!empty($options['tables'][$group][$key])) {
                 // use defaults table aliases if not specified
                 $this->tables[$group][$key] = $options['tables'][$group][$key];
             }
         }
     }
     foreach ($this->sections as $group => $section) {
         $ctxtlvl = \local_eliscore\context\helper::get_level_from_name($section['name']);
         $this->sections[$group]['contextlevel'] = $ctxtlvl;
         // Add custom fields to array
         $extrafields = field::get_for_context_level($ctxtlvl);
         $this->get_custom_fields($group, $extrafields);
     }
     // Force $options['choices'] to be an associative array
     foreach ($options['choices'] as $key => $choices) {
         if (!$this->is_assoc_array($choices)) {
             $options['choices'][$key] = array_fill_keys($choices, '');
         }
     }
     foreach ($options['choices'] as $group => $choices) {
         $allfields[$group] = array();
         foreach ($choices as $name => $alias) {
             $label = $name;
             if (!empty($alias) && get_string_manager()->string_exists($alias, $this->languagefile)) {
                 $label = get_string($alias, $this->languagefile);
             } else {
                 if (array_key_exists($name, $this->defaultlabels[$group]) && get_string_manager()->string_exists($this->defaultlabels[$group][$name], $this->languagefile)) {
                     $label = get_string($this->defaultlabels[$group][$name], $this->languagefile);
                 } else {
                     foreach ($this->sections as $section) {
                         if (array_key_exists($name, $section['custom'])) {
                             $label = $section['custom'][$name];
                         }
                     }
                 }
             }
             $allfields[$group][$name] = $label;
         }
         if (!empty($options['extra']) && !empty($this->sections[$group]['custom'])) {
             $allfields[$group] = array_merge($allfields[$group], $this->sections[$group]['custom']);
         }
     }
     foreach ($allfields as $group => $fields) {
         $this->_filters[$group] = array();
         foreach ($fields as $name => $label) {
             // must setup select choices for specific fields
             $myoptions = $this->make_filter_options($group, $name, $options['help'], $options['tables']);
             if (!is_array($myoptions)) {
                 continue;
             }
             $filterid = $this->_uniqueid . $group . '-' . substr($name, 0, MAX_FILTER_SUFFIX_LEN);
             $ftype = (string) $this->fieldtofiltermap[$group][$name];
             $advanced = !empty($options['advanced'][$group]) && in_array($name, $options['advanced'][$group]) || !empty($options['notadvanced'][$group]) && !in_array($name, $options['notadvanced'][$group]);
             $this->_filters[$group][$name] = new generalized_filter_entry($filterid, $myoptions['talias'], $myoptions['dbfield'], $label, $advanced, $ftype, $myoptions);
         }
     }
 }
Example #25
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;
 }
Example #26
0
 function display_editfield()
 {
     global $CFG, $DB;
     $level = $this->required_param('level', PARAM_ACTION);
     $ctxlvl = \local_eliscore\context\helper::get_level_from_name($level);
     if (!$ctxlvl) {
         print_error('invalid_context_level', 'local_elisprogram');
     }
     $id = $this->optional_param('id', NULL, PARAM_INT);
     require_once elispm::file('form/customfieldform.class.php');
     $tmppage = new customfieldpage(array('level' => $level, 'action' => 'editfield'), $this);
     $form = new customfieldform($tmppage->url, array('id' => $id, 'level' => $level, 'from' => optional_param('from', '', PARAM_CLEAN)));
     if ($form->is_cancelled()) {
         $tmppage = new customfieldpage(array('level' => $level));
         redirect($tmppage->url, get_string('edit_cancelled', 'local_elisprogram'));
     } else {
         if ($data = $form->get_data()) {
             $src = !empty($data->manual_field_options_source) ? $data->manual_field_options_source : '';
             // ELIS-8066: strip CRs "\r" from menu options & default data (below)
             if (!empty($data->manual_field_options)) {
                 $data->manual_field_options = str_replace("\r", '', $data->manual_field_options);
             }
             switch ($data->manual_field_control) {
                 case 'checkbox':
                     if (!$data->multivalued && !empty($src)) {
                         $elem = "defaultdata_radio_{$src}";
                         $data->defaultdata = isset($data->{$elem}) ? $data->{$elem} : '';
                         // radio buttons unset by default
                         // error_log("/local/elisprogram/customfieldpage.class.php:: defaultdata->{$elem} = {$data->defaultdata}");
                     } else {
                         if (!$data->multivalued && !empty($data->manual_field_options)) {
                             $data->defaultdata = str_replace("\r", '', $data->defaultdata_radio);
                         } else {
                             $data->defaultdata = $data->defaultdata_checkbox;
                         }
                     }
                     break;
                 case 'menu':
                     $elem = !empty($src) ? "defaultdata_menu_{$src}" : "defaultdata_menu";
                     $data->defaultdata = $data->{$elem};
                     if (empty($src)) {
                         $data->defaultdata = str_replace("\r", '', $data->defaultdata);
                     }
                     break;
                 case 'datetime':
                     $data->defaultdata = $data->defaultdata_datetime;
                     break;
                 default:
                     $data->defaultdata = $data->defaultdata_text;
                     break;
             }
             $field = new field($data);
             if ($id) {
                 $field->id = $id;
                 $field->save();
             } else {
                 $field->save();
                 // assume each field only belongs to one context level (for now)
                 $fieldcontext = new field_contextlevel();
                 $fieldcontext->fieldid = $field->id;
                 $fieldcontext->contextlevel = $ctxlvl;
                 $fieldcontext->save();
             }
             //don't use !empty here because we might be storing a 0 or similar value
             if ($data->defaultdata != '') {
                 // save the default value
                 $defaultdata = $data->defaultdata;
                 if ($field->multivalued && is_string($defaultdata)) {
                     // parse as a CSV string
                     // until we can use str_getcsv from PHP 5.3...
                     $temp = fopen("php://memory", "rw");
                     fwrite($temp, $defaultdata);
                     rewind($temp);
                     $defaultdata = fgetcsv($temp);
                     fclose($temp);
                 } else {
                     if (!$field->multivalued && is_array($defaultdata)) {
                         foreach ($defaultdata as $val) {
                             $defaultdata = $val;
                             break;
                         }
                     }
                 }
                 field_data::set_for_context_and_field(NULL, $field, $defaultdata);
             } else {
                 if ($field->multivalued) {
                     field_data::set_for_context_and_field(NULL, $field, array());
                 } else {
                     field_data::set_for_context_and_field(NULL, $field, NULL);
                 }
             }
             $plugins = core_component::get_plugin_list('elisfields');
             foreach ($plugins as $plugin => $dir) {
                 if (is_readable($CFG->dirroot . '/local/eliscore/fields/' . $plugin . '/custom_fields.php')) {
                     require_once elis::plugin_file('elisfields_' . $plugin, 'custom_fields.php');
                     if (function_exists("{$plugin}_field_save_form_data")) {
                         call_user_func("{$plugin}_field_save_form_data", $form, $field, $data);
                     }
                 }
             }
             $tmppage = new customfieldpage(array('level' => $level));
             redirect($tmppage->url, get_string('field_saved', 'local_elisprogram', $field));
         } else {
             if (!empty($id)) {
                 if ($this->optional_param('from', NULL, PARAM_CLEAN) == 'moodle' && $level == 'user') {
                     $moodlefield = $DB->get_record('user_info_field', array('id' => $id));
                     if (!$moodlefield) {
                         print_error('invalid_field_id', 'local_elisprogram');
                     }
                     unset($moodlefield->id);
                     $data = $moodlefield;
                     $data_array = (array) $moodlefield;
                     $data_array['datatype'] = 'text';
                     $data_array['manual_field_control'] = $moodlefield->datatype;
                     switch ($moodlefield->datatype) {
                         case field::CHECKBOX:
                             $data_array['datatype'] = 'bool';
                             break;
                         case field::DATETIME:
                             $data_array['datatype'] = 'datetime';
                             $data_array['manual_field_startyear'] = $moodlefield->param1;
                             $data_array['manual_field_stopyear'] = $moodlefield->param2;
                             $data_array['manual_field_inctime'] = $moodlefield->param3;
                             break;
                         case field::MENU:
                             $data_array['datatype'] = 'char';
                             $data_array['manual_field_options'] = $moodlefield->param1;
                             break;
                         case field::TEXTAREA:
                             $data_array['manual_field_columns'] = $moodlefield->param1;
                             $data_array['manual_field_rows'] = $moodlefield->param2;
                             break;
                         case field::TEXT:
                             if ($moodlefield->param3) {
                                 $data_array['manual_field_control'] = 'password';
                             }
                             $data_array['manual_field_columns'] = $moodlefield->param1;
                             $data_array['manual_field_maxlength'] = $moodlefield->param2;
                             break;
                     }
                 } else {
                     $data = new field($id);
                     $data->load();
                     $manual = new field_owner(!isset($field->owners) || !isset($field->owners['manual']) ? false : $field->owners['manual']);
                     $menu_src = !empty($manual->options_source) ? $manual->options_source : 0;
                     $data_array = $data->to_array();
                     $field_record = $DB->get_record(field::TABLE, array('id' => $id));
                     if (!empty($field_record)) {
                         foreach ($field_record as $field_item => $field_value) {
                             $data_array[$field_item] = $field_value;
                         }
                     }
                     $defaultdata = field_data::get_for_context_and_field(NULL, $data);
                     if (!empty($defaultdata)) {
                         if ($data->multivalued) {
                             $values = array();
                             foreach ($defaultdata as $defdata) {
                                 $values[] = $defdata->data;
                             }
                             $defaultdata = $values;
                         } else {
                             foreach ($defaultdata as $defdata) {
                                 $defaultdata = $defdata->data;
                                 break;
                             }
                         }
                     }
                     $field = new field();
                     // Format decimal numbers
                     if ($data_array['datatype'] == 'num' && $manual->param_control != 'menu') {
                         $defaultdata = $field->format_number($defaultdata);
                     }
                     if (!is_object($defaultdata)) {
                         $data_array['defaultdata'] = $defaultdata;
                     }
                     $plugins = core_component::get_plugin_list('elisfields');
                     foreach ($plugins as $plugin => $dir) {
                         if (is_readable($CFG->dirroot . '/local/eliscore/fields/' . $plugin . '/custom_fields.php')) {
                             include_once $CFG->dirroot . '/local/eliscore/fields/' . $plugin . '/custom_fields.php';
                             if (function_exists("{$plugin}_field_get_form_data")) {
                                 $data_array += call_user_func("{$plugin}_field_get_form_data", $form, $data);
                             }
                         }
                     }
                 }
                 if (isset($data_array['defaultdata'])) {
                     // ELIS-6699 -- load the field to determine the data type used, $data may be a field_data_* or field object
                     if (isset($data->fieldid)) {
                         $field->id = $data->fieldid;
                         $field->load();
                     } else {
                         $field = $data;
                     }
                     $data_array['defaultdata_checkbox'] = !empty($data_array['defaultdata']);
                     // ELIS-6699 -- If this is not a datetime field, then we can't use the default data value as a timestamp
                     $data_array['defaultdata_datetime'] = $field->datatype == 'datetime' ? $data_array['defaultdata'] : time();
                     $data_array['defaultdata_text'] = strval($data_array['defaultdata']);
                     $data_array[empty($menu_src) ? 'defaultdata_menu' : "defaultdata_menu_{$menu_src}"] = $data_array['defaultdata'];
                     $data_array[empty($menu_src) ? 'defaultdata_radio' : "defaultdata_radio_{$menu_src}"] = $data_array['defaultdata'];
                 }
                 $form->set_data($data_array);
             }
             $form->display();
         }
     }
 }
Example #27
0
 /**
  * Test that the pm_ensure_role_assignable function works correctly
  */
 public function test_pmensureroleassignable()
 {
     global $DB;
     // This test needs to have the role_context_levels table completely empty before beginning.
     $DB->delete_records('role_context_levels');
     $contextlevels = \local_eliscore\context\helper::get_all_levels();
     $managerroleid = $DB->get_field('role', 'id', array('shortname' => 'manager'));
     $programadminroleid = $DB->get_field('role', 'id', array('shortname' => 'curriculumadmin'));
     // Test that the function works with the 'manager' role.
     $this->assertEquals($managerroleid, pm_ensure_role_assignable('manager'));
     foreach ($contextlevels as $ctxlevel => $ctxclass) {
         $params = array('roleid' => $managerroleid, 'contextlevel' => $ctxlevel);
         $this->assertTrue($DB->record_exists('role_context_levels', $params));
     }
     // Test that the function works with the 'curriculumadmin' role.
     $this->assertEquals($programadminroleid, pm_ensure_role_assignable('curriculumadmin'));
     foreach ($contextlevels as $ctxlevel => $ctxclass) {
         $params = array('roleid' => $programadminroleid, 'contextlevel' => $ctxlevel);
         $this->assertTrue($DB->record_exists('role_context_levels', $params));
     }
 }
Example #28
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;
 }
Example #29
0
/**
 * Function to move any custom fields with an invalid category
 * into a category called Miscellaneous
 *
 */
function pm_fix_orphaned_fields()
{
    global $DB;
    $misc_cat = get_string('misc_category', 'local_elisprogram');
    //set up context array
    $context_array = \local_eliscore\context\helper::get_all_levels();
    foreach ($context_array as $contextlevel => $contextname) {
        //find all fields with non existant category assignments
        $sql = "SELECT field.id\n                  FROM {" . field::TABLE . "} field\n                  JOIN {" . field_contextlevel::TABLE . "} ctx ON ctx.fieldid = field.id AND ctx.contextlevel = ?\n                  WHERE NOT EXISTS (\n                    SELECT 'x' FROM {" . field_category::TABLE . "} category\n                    WHERE category.id = field.categoryid)";
        $params = array($contextlevel);
        $rs = $DB->get_recordset_sql($sql, $params);
        //if any are found - then check if miscellaneous category exists - if not, create it
        foreach ($rs as $field) {
            $sql = "SELECT category.id\n                    FROM {" . field_category::TABLE . "} category\n                    JOIN {" . field_category_contextlevel::TABLE . "} categorycontext\n                      ON categorycontext.categoryid = category.id\n                    WHERE categorycontext.contextlevel = ?\n                      AND category.name = ?";
            $params = array($contextlevel, $misc_cat);
            $categoryid = $DB->get_field_sql($sql, $params);
            //create a miscellaneous category if it doesn't already exist
            if (!$categoryid) {
                // create an empty category
                $category = new field_category(array('name' => $misc_cat));
                $category->save();
                $categorycontext = new field_category_contextlevel();
                $categorycontext->categoryid = $category->id;
                $categorycontext->contextlevel = $contextlevel;
                $categorycontext->save();
                $categoryid = $category->id;
            }
            $field = new field($field->id);
            // set the field category to the Miscellaneous category
            $field->categoryid = $categoryid;
            $field->save();
        }
        $rs->close();
    }
}
 /**
  * Returns an SQL fragment needed to connect a context entity table to its
  * CM custom fields data in the CM system
  *
  * @param string $contextlevel Shortname of the context level we are looking for fields
  *                             related to
  * @param array $fieldids List of ids of field records we are displaying
  * @param string $instancefield Database field representing the context id
  * @return string The appropriate SQL fragment
  */
 function get_custom_field_sql($fieldids, $instancefields)
 {
     global $DB;
     $where = $DB->get_in_or_equal($fieldids);
     $contexts = $DB->get_records_select(field_contextlevel::TABLE, 'fieldid ' . $where[0], $where[1]);
     $fragment = array();
     /* *** debug ***
           ob_start();
           var_dump($instancefields);
           $tmp = ob_get_contents();
           ob_end_clean();
           error_log("UCCR::get_custom_field_sql(fieldids, instancefields = {$tmp})");
        */
     // Get the legacy context names mapped to the context level values
     $contextlevelnames = array_flip(\local_eliscore\context\helper::get_legacy_levels());
     $contextlevel = '';
     $contextname = '';
     if (!empty($contexts)) {
         //add a join for each profile field
         foreach ($contexts as $context) {
             $ctxname = $contextlevelnames[$context->contextlevel];
             if (!in_array($ctxname, array_keys($instancefields))) {
                 // Not a context level we care about
                 continue;
             }
             if ($contextlevel != $context->contextlevel) {
                 $contextlevel = $context->contextlevel;
                 $contextname = $ctxname . '_';
                 // TBD
                 list($instancefield, $_as, $_var) = explode(' ', $instancefields[$ctxname]);
                 // have one or more profile field we're joining, so join the context table at the top level
                 $fragment[$ctxname] = " LEFT JOIN {context} {$contextname}context\n                                      ON {$instancefield} = {$contextname}context.instanceid\n                                     AND {$contextname}context.contextlevel = {$contextlevel}";
             }
             $field = new field($context->fieldid);
             $identifier = "customfielddata_{$context->fieldid}";
             $fragment[] = ' LEFT JOIN {' . $field->data_table() . "} {$identifier}\n                                       ON {$contextname}context.id = {$identifier}.contextid\n                                      AND {$identifier}.fieldid = {$context->fieldid}";
         }
     }
     $result = implode("\n", $fragment);
     //         error_log("UCCR::get_custom_field_sql() => {$result}");
     return $result;
 }