/**
  * Test successful userset delete
  */
 public function test_success()
 {
     global $DB;
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_USERSET;
     $fieldctx->save();
     $this->give_permissions(array('local/elisprogram:userset_delete'));
     $userset = array('name' => 'testuserset', 'recursive' => true);
     // Setup userset to delete.
     $us = new userset(array('name' => 'testuserset'));
     $us->save();
     $response = local_datahub_elis_userset_delete::userset_delete($userset);
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertEquals(get_string('ws_userset_delete_success_code', 'local_datahub', get_string('ws_userset_delete_recursive', 'local_datahub')), $response['messagecode']);
     $this->assertEquals(get_string('ws_userset_delete_success_msg', 'local_datahub', get_string('ws_userset_delete_subsets', 'local_datahub')), $response['message']);
 }
 /**
  * Test successful program delete
  */
 public function test_success()
 {
     global $DB;
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_PROGRAM;
     $fieldctx->save();
     // Create test program to delete.
     $cur = new curriculum(array('idnumber' => 'testprogram', 'name' => 'testprogram'));
     $cur->save();
     $program = array('idnumber' => 'testprogram');
     $this->give_permissions(array('local/elisprogram:program_delete'));
     $response = local_datahub_elis_program_delete::program_delete($program);
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertEquals(get_string('ws_program_delete_success_code', 'local_datahub'), $response['messagecode']);
     $this->assertEquals(get_string('ws_program_delete_success_msg', 'local_datahub'), $response['message']);
     $this->assertFalse($DB->record_exists(curriculum::TABLE, array('idnumber' => 'testprogram')));
 }
 /**
  * Method to create ELIS field & owner objects given test data array.
  *
  * @param array $inputarray The test data array with params to build elis field object & owner
  *        input array format:
  *        array('field' => array(fieldparam => fieldparam_value [,...]),
  *              'context' => contextlevel,
  *              'manual' => array(fieldowners_manual_param => fomp_value [,...]),
  *              'moodle_profile' => array(fieldowners_moodleprofile_param => fompp_value [,...]),
  *        )
  * @return object The ELIS field object created
  */
 public function build_elis_field_data($inputarray)
 {
     $field = new field((object) $inputarray['field']);
     $field->save();
     $fieldcontext = new field_contextlevel();
     $fieldcontext->fieldid = $field->id;
     $fieldcontext->contextlevel = $inputarray['context'];
     $fieldcontext->save();
     if (isset($inputarray['manual'])) {
         $manual = new field_owner();
         $manual->fieldid = $field->id;
         $manual->plugin = 'manual';
         foreach ($inputarray['manual'] as $key => $val) {
             $manual->{'param_' . $key} = $val;
         }
         $manual->save();
     }
     if (isset($inputarray['moodle_profile'])) {
         $moodleprofile = new field_owner();
         $moodleprofile->fieldid = $field->id;
         $moodleprofile->plugin = 'moodle_profile';
         foreach ($inputarray['moodle_profile'] as $key => $val) {
             $moodleprofile->{$key} = $val;
         }
         $moodleprofile->save();
     }
     $field->load();
     // TDB.
     return $field;
 }
 /**
  * Test successful course update.
  */
 public function test_success()
 {
     global $DB;
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_COURSE;
     $fieldctx->save();
     // Grant permissions.
     $this->give_permissions(array('local/elisprogram:course_edit'));
     // Create test program.
     $datagen = new elis_program_datagenerator($DB);
     $program = $datagen->create_program(array('idnumber' => 'TestProgram'));
     // Create test course to update.
     $crs = new course(array('idnumber' => 'TestCourse', 'name' => 'Test Course', 'syllabus' => ''));
     $crs->save();
     $course = array('idnumber' => 'TestCourse', 'name' => 'Test Course', 'code' => 'CRS1', 'syllabus' => 'Test syllabus', 'lengthdescription' => 'Weeks', 'length' => 2, 'credits' => 1.1, 'completion_grade' => 50, 'cost' => '$100', 'version' => '1.0.0', 'assignment' => $program->idnumber);
     // Update test course.
     $response = local_datahub_elis_course_update::course_update($course);
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertArrayHasKey('record', $response);
     $this->assertEquals(get_string('ws_course_update_success_code', 'local_datahub'), $response['messagecode']);
     $this->assertEquals(get_string('ws_course_update_success_msg', 'local_datahub'), $response['message']);
     $this->assertInternalType('array', $response['record']);
     $this->assertArrayHasKey('id', $response['record']);
     // Get course.
     $updatedcourse = new course($response['record']['id']);
     $updatedcourse->load();
     $updatedcourse = $updatedcourse->to_array();
     foreach ($course as $param => $val) {
         if ($param != 'assignment') {
             $this->assertArrayHasKey($param, $updatedcourse);
             $this->assertEquals($val, $updatedcourse[$param]);
         }
     }
     // Check that course was assigned to program.
     $curriculumcourseid = $DB->get_field(curriculumcourse::TABLE, 'id', array('curriculumid' => $program->id, 'courseid' => $response['record']['id']));
     $this->assertNotEmpty($curriculumcourseid);
 }
 /**
  * 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;
 }
 /**
  * Create the necessary custom field
  *
  * @return int The id of the created field
  */
 private function create_custom_field()
 {
     global $CFG;
     require_once $CFG->dirroot . '/local/eliscore/lib/data/customfield.class.php';
     require_once $CFG->dirroot . '/local/elisprogram/accesslib.php';
     // Field category.
     $fieldcategory = new field_category(array('name' => 'testcategoryname'));
     $fieldcategory->save();
     // Custom field.
     $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'testfieldshortname', 'name' => 'testfieldname', 'datatype' => 'bool'));
     $field->save();
     // Field context level assocation.
     $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER));
     $fieldcontextlevel->save();
     return $field->id;
 }
 /**
  * Test successful user creation.
  */
 public function test_success()
 {
     global $DB;
     $this->give_permissions(array('local/elisprogram:class_edit'));
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_CLASS;
     $fieldctx->save();
     $course = new course();
     $course->idnumber = 'testcourse1';
     $course->name = 'Test Course 1';
     $course->syllabus = 'Test';
     $course->save();
     $class = new pmclass(array('idnumber' => 'testclass', 'startdate' => 1357016400, 'enddate' => 1359694800, 'courseid' => $course->id, 'assignment' => $course->idnumber, 'field_testfield' => 'Test Field'));
     $class->save();
     $classupdates = array('idnumber' => 'testclass', 'startdate' => 'Feb/04/2013', 'enddate' => 'Mar/01/2013', 'field_testfield' => 'Test Field 2');
     $response = local_datahub_elis_class_update::class_update($classupdates);
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertArrayHasKey('record', $response);
     $this->assertEquals(get_string('ws_class_update_success_code', 'local_datahub'), $response['messagecode']);
     $this->assertEquals(get_string('ws_class_update_success_msg', 'local_datahub'), $response['message']);
     $this->assertInternalType('array', $response['record']);
     $this->assertArrayHasKey('id', $response['record']);
     // Get class.
     $expectedclass = array('idnumber' => $class->idnumber, 'startdate' => rlip_timestamp(0, 0, 0, 2, 4, 2013), 'enddate' => rlip_timestamp(0, 0, 0, 3, 1, 2013), 'courseid' => $course->id, 'field_testfield' => 'Test Field 2');
     $createdclass = new pmclass($response['record']['id']);
     $createdclass->load();
     $createdclass = $createdclass->to_array();
     foreach ($expectedclass as $param => $val) {
         $this->assertArrayHasKey($param, $createdclass);
         $this->assertEquals($val, $createdclass[$param]);
     }
 }
 /**
  * Set up necessary data
  *
  * @param int $numfields The number of custom fields used in auto-association
  */
 private function init_required_data($numfields = 1)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elis::file('eliscore/fields/moodleprofile/custom_fields.php');
     require_once elis::lib('data/customfield.class.php');
     require_once elispm::file('accesslib.php');
     require_once elispm::lib('data/userset.class.php');
     require_once $CFG->dirroot . '/user/profile/definelib.php';
     require_once $CFG->dirroot . '/user/profile/field/checkbox/define.class.php';
     // Set up the category only once.
     $fieldcategory = new field_category(array('name' => 'testcategoryname'));
     $fieldcategory->save();
     // Ste up the target userset only once.
     $userset = new userset(array('name' => 'testusersetname'));
     $userset->save();
     for ($i = 1; $i <= $numfields; $i++) {
         // Custom field.
         $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'testfieldshortname' . $i, 'name' => 'testfieldname' . $i, 'datatype' => 'bool'));
         $field->save();
         // Ensure manual field owner exists for syncing.
         field_owner::ensure_field_owner_exists($field, 'manual');
         $ownerid = $DB->get_field(field_owner::TABLE, 'id', array('fieldid' => $field->id, 'plugin' => 'manual'));
         $owner = new field_owner($ownerid);
         $owner->param_control = 'checkbox';
         $owner->save();
         // Ensure moodle profile field owner exists.
         field_owner::ensure_field_owner_exists($field, 'moodle_profile');
         $DB->execute("UPDATE {" . field_owner::TABLE . "} SET exclude = ?", array(pm_moodle_profile::sync_to_moodle));
         // Field context level assocation.
         $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER));
         $fieldcontextlevel->save();
         // The associated Moodle user profile field.
         $profiledefinecheckbox = new profile_define_checkbox();
         $data = new stdClass();
         $data->datatype = 'checkbox';
         $data->categoryid = 99999;
         $data->shortname = 'testfieldshortname' . $i;
         $data->name = 'testfieldname' . $i;
         $profiledefinecheckbox->define_save($data);
         $mfield = $DB->get_record('user_info_field', array('shortname' => 'testfieldshortname' . $i));
         // The "cluster-profile" association.
         $usersetprofile = new userset_profile(array('clusterid' => $userset->id, 'fieldid' => $mfield->id, 'value' => 1));
         $usersetprofile->save();
     }
 }
 /**
  * Test successful user edit.
  * @dataProvider dataprovider_success
  * @param array $update Incoming update data.
  */
 public function test_success($update)
 {
     global $DB;
     $this->give_permissions(array('local/elisprogram:user_edit'));
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_USER;
     $fieldctx->save();
     $user = array('idnumber' => 'testuser', 'username' => 'testuser', 'firstname' => 'testuser', 'lastname' => 'testuser', 'email' => '*****@*****.**', 'country' => 'CA', 'field_testfield' => 'Test Field');
     $user = new user($user);
     $user->save();
     $expecteduser = (array) $DB->get_record(user::TABLE, array('id' => $user->id));
     $expecteduser = array_merge($expecteduser, $update);
     $response = local_datahub_elis_user_update::user_update($update);
     // Verify general response structure.
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertArrayHasKey('record', $response);
     // Verify response message/code.
     $this->assertEquals(get_string('ws_user_update_success_code', 'local_datahub'), $response['messagecode']);
     $this->assertEquals(get_string('ws_user_update_success_msg', 'local_datahub'), $response['message']);
     // Verify returned user information.
     $this->assertInternalType('array', $response['record']);
     $this->assertArrayHasKey('id', $response['record']);
     $actualuser = $DB->get_record(user::TABLE, array('id' => $response['record']['id']));
     $this->assertNotEmpty($actualuser);
     $actualuser = (array) $actualuser;
     // Unset timemodified as it's unreliable to test.
     unset($actualuser['timemodified']);
     foreach ($actualuser as $param => $val) {
         $this->assertEquals($expecteduser[$param], $val);
     }
 }
 /**
  * Test successful track update
  */
 public function test_success()
 {
     global $DB;
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_TRACK;
     $fieldctx->save();
     $this->give_permissions(array('local/elisprogram:track_edit'));
     // Setup program and track.
     $datagen = new elis_program_datagenerator($DB);
     $program = $datagen->create_program(array('idnumber' => 'test_program_idnumber', 'name' => 'ProgramName'));
     $track = $datagen->create_track(array('idnumber' => 'testtrack', 'name' => 'testtrackname', 'curid' => $program->id));
     // Perform update.
     $trackupdatedata = array('idnumber' => $track->idnumber, 'name' => 'testtrackname_changed', 'description' => 'testtrack description', 'field_testfield' => 'Test field');
     $response = local_datahub_elis_track_update::track_update($trackupdatedata);
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertArrayHasKey('record', $response);
     $this->assertEquals(get_string('ws_track_update_success_code', 'local_datahub'), $response['messagecode']);
     $this->assertEquals(get_string('ws_track_update_success_msg', 'local_datahub'), $response['message']);
     $this->assertInternalType('array', $response['record']);
     $this->assertArrayHasKey('id', $response['record']);
     // Get Track.
     $updatedtrk = new track($response['record']['id']);
     $updatedtrk->load();
     $updatedtrk = $updatedtrk->to_array();
     $expecttrk = array('id' => $response['record']['id'], 'idnumber' => 'testtrack', 'name' => 'testtrackname_changed', 'curid' => $program->id, 'description' => 'testtrack description', 'field_testfield' => 'Test field');
     foreach ($expecttrk as $param => $val) {
         $this->assertArrayHasKey($param, $updatedtrk);
         $this->assertEquals($val, $updatedtrk[$param]);
     }
 }
 /**
  * Test successful userset update
  */
 public function test_success()
 {
     global $DB;
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_USERSET;
     $fieldctx->save();
     $this->give_permissions(array('local/elisprogram:userset_edit'));
     $userset = array('name' => 'testuserset', 'display' => 'test userset description', 'parent' => 'top', 'field_testfield' => 'Test field');
     // Setup userset to update.
     $us = new userset(array('name' => 'testuserset'));
     $us->save();
     $response = local_datahub_elis_userset_update::userset_update($userset);
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertArrayHasKey('record', $response);
     $this->assertEquals(get_string('ws_userset_update_success_code', 'local_datahub'), $response['messagecode']);
     $this->assertEquals(get_string('ws_userset_update_success_msg', 'local_datahub'), $response['message']);
     $this->assertInternalType('array', $response['record']);
     $this->assertArrayHasKey('id', $response['record']);
     // Get Userset.
     $updatedus = new userset($response['record']['id']);
     $updatedus->load();
     $updatedus = $updatedus->to_array();
     $expectus = array('id' => $response['record']['id'], 'name' => 'testuserset', 'display' => 'test userset description', 'parent' => 0, 'field_testfield' => 'Test field');
     foreach ($expectus as $param => $val) {
         $this->assertArrayHasKey($param, $updatedus);
         $this->assertEquals($val, $updatedus[$param]);
     }
 }
 /**
  * Test successful program update
  */
 public function test_success()
 {
     global $DB;
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_PROGRAM;
     $fieldctx->save();
     // Create test program to update.
     $datagen = new elis_program_datagenerator($DB);
     $program = $datagen->create_program(array('idnumber' => 'testprogram', 'name' => 'testprogram'));
     $program = array('idnumber' => 'testprogram', 'name' => 'newtestprogramname', 'reqcredits' => 4.5, 'timetocomplete' => '6m', 'frequency' => '1y', 'field_testfield' => 'Test Field');
     $this->give_permissions(array('local/elisprogram:program_edit'));
     $response = local_datahub_elis_program_update::program_update($program);
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertArrayHasKey('record', $response);
     $this->assertEquals(get_string('ws_program_update_success_code', 'local_datahub'), $response['messagecode']);
     $this->assertEquals(get_string('ws_program_update_success_msg', 'local_datahub'), $response['message']);
     $this->assertInternalType('array', $response['record']);
     $this->assertArrayHasKey('id', $response['record']);
     // Get Program.
     $createdprg = new curriculum($response['record']['id']);
     $createdprg->load();
     $createdprg = $createdprg->to_array();
     foreach ($program as $param => $val) {
         $this->assertArrayHasKey($param, $createdprg);
         $this->assertEquals($val, $createdprg[$param]);
     }
 }
 /**
  * Test successful user creation.
  */
 public function test_success()
 {
     global $DB;
     // Create custom field.
     $fieldcat = new field_category();
     $fieldcat->name = 'Test';
     $fieldcat->save();
     $field = new field();
     $field->categoryid = $fieldcat->id;
     $field->shortname = 'testfield';
     $field->name = 'Test Field';
     $field->datatype = 'text';
     $field->save();
     $fieldctx = new field_contextlevel();
     $fieldctx->fieldid = $field->id;
     $fieldctx->contextlevel = CONTEXT_ELIS_USER;
     $fieldctx->save();
     $user = array('idnumber' => 'testuser', 'username' => 'testuser', 'firstname' => 'testuser', 'lastname' => 'testuser', 'email' => '*****@*****.**', 'country' => 'CA', 'field_testfield' => 'Test Field');
     $tempuser = new user();
     $tempuser->reset_custom_field_list();
     $this->give_permissions(array('local/elisprogram:user_create'));
     $response = local_datahub_elis_user_create::user_create($user);
     $this->assertNotEmpty($response);
     $this->assertInternalType('array', $response);
     $this->assertArrayHasKey('messagecode', $response);
     $this->assertArrayHasKey('message', $response);
     $this->assertArrayHasKey('record', $response);
     $this->assertEquals(get_string('ws_user_create_success_code', 'local_datahub'), $response['messagecode']);
     $this->assertEquals(get_string('ws_user_create_success_msg', 'local_datahub'), $response['message']);
     $this->assertInternalType('array', $response['record']);
     $this->assertArrayHasKey('id', $response['record']);
     // Get user.
     $createduser = new user($response['record']['id']);
     $createduser->load();
     $createduser = $createduser->to_array();
     foreach ($user as $param => $val) {
         $this->assertArrayHasKey($param, $createduser);
         $this->assertEquals($val, $createduser[$param]);
     }
 }
 /**
  * Create the test custom profile field, category and owner
  *
  * @param string $contextlevelname The name of the custom context level to create the field at
  * @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 boolean $multivalued Set to true to make field multivalued, otherwise false
  * @param mixed $options Array of menu options, or null for none
  * @param int $maxlength The maximum data length, or null for none
  * @return int The id of the created field
  */
 private function create_test_field($contextlevelname, $datatype, $uitype, $multivalued, $options, $maxlength, $inctime)
 {
     global $CFG;
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elis::lib('data/customfield.class.php');
     // Category.
     $fieldcategory = new field_category(array('name' => 'testcategoryname'));
     $fieldcategory->save();
     // Category contextlevel.
     $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextlevelname);
     $fieldcategorycontextlevel = new field_category_contextlevel(array('categoryid' => $fieldcategory->id, 'contextlevel' => $contextlevel));
     $fieldcategorycontextlevel->save();
     // Field.
     $field = new field(array('shortname' => 'testfieldshortname', 'name' => 'testfieldname', 'categoryid' => $fieldcategory->id, 'datatype' => $datatype));
     if ($multivalued) {
         // Enable multivalued ability.
         $field->multivalued = true;
     }
     $field->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.
         $ownerdata['options'] = implode("\n", $options);
     }
     if ($maxlength !== null) {
         // Set max length.
         $ownerdata['maxlength'] = $maxlength;
     }
     if ($inctime !== null) {
         $ownerdata['inctime'] = $inctime;
     }
     field_owner::ensure_field_owner_exists($field, 'manual', $ownerdata);
     return $field->id;
 }
 private function create_test_field($name, $datatype, $control, $inctime, $maxlength, $options, $context)
 {
     $fieldcategory = new field_category(array('name' => 'testcategoryname'));
     $fieldcategory->save();
     $field = new field(array('shortname' => $name, 'name' => $name, 'datatype' => $datatype, 'categoryid' => $fieldcategory->id));
     $field->save();
     $ownerdata = array('control' => $control);
     if ($options !== null) {
         $ownerdata['options'] = implode("\n", $options);
     }
     if ($maxlength !== null) {
         $ownerdata['maxlength'] = $maxlength;
     }
     if ($inctime !== null) {
         $ownerdata['inctime'] = $inctime;
     }
     // Associate fields to context levels.
     $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => $context));
     $fieldcontextlevel->save();
     field_owner::ensure_field_owner_exists($field, 'manual', $ownerdata);
     return $field->id;
 }
Exemple #16
0
 /**
  * Validate that custom user fields are synched over to Moodle when PM user is created
  * during an import
  */
 public function test_user_multi_custom_field_on_user_create()
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elis::lib('data/customfield.class.php');
     require_once elis::file('eliscore/fields/moodleprofile/custom_fields.php');
     require_once elispm::file('accesslib.php');
     require_once elispm::lib('data/user.class.php');
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->dirroot . '/user/profile/definelib.php';
     require_once $CFG->dirroot . '/user/profile/field/menu/define.class.php';
     $CFG->filterall = true;
     $USER = get_admin();
     $context = context_user::instance($USER->id);
     /*
       $filternames = filter_get_all_installed();
       ob_start();
       var_dump($filternames);
       $tmp = ob_get_contents();
       ob_end_clean();
       error_log("test_user_multi_custom_field_on_user_create: all-filters => {$tmp}");
     */
     // Note: >= m25 filter paths no longer prefixed with 'filter/'
     filter_set_global_state('multilang', TEXTFILTER_ON);
     filter_set_applies_to_strings('multilang', true);
     $multilangoption1 = '<span class="multilang" lang="en">Male</span><span class="multilang" lang="pt_br">Masculino</span>' . '<span class="multilang" lang="es">Masculino</span>';
     $multilangoption2 = '<span class="multilang" lang="en">Female</span><span class="multilang" lang="pt_br">Feminino</span>' . '<span class="multilang" lang="es">Femenino</span>';
     // The associated Moodle user profile field.
     $profiledefinemenu = new profile_define_menu();
     $data = new stdClass();
     $data->datatype = 'menu';
     $data->categoryid = 99999;
     $data->shortname = 'testfieldgender';
     $data->name = 'testfieldgender';
     $data->param1 = "{$multilangoption1}\n{$multilangoption2}";
     $data->defaultdata = $multilangoption2;
     $profiledefinemenu->define_save($data);
     // Reset cached custom fields.
     $user = new user();
     $user->reset_custom_field_list();
     // Field category.
     $fieldcategory = new field_category(array('name' => 'testcategoryname'));
     $fieldcategory->save();
     // Custom field.
     $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'testfieldgender', 'name' => 'testfieldgender', 'datatype' => 'text', 'multivalued' => 1));
     $field->save();
     // Field owners
     field_owner::ensure_field_owner_exists($field, 'moodle_profile');
     $manualowneroptions = array('required' => 0, 'edit_capability' => '', 'view_capability' => '', 'control' => 'menu', 'options' => "{$multilangoption1}\n{$multilangoption2}");
     field_owner::ensure_field_owner_exists($field, 'manual', $manualowneroptions);
     // Field context level assocation.
     $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER));
     $fieldcontextlevel->save();
     // Run the user create action.
     $record = new stdClass();
     $record->action = 'create';
     $record->idnumber = 'testuseridnumber';
     $record->username = '******';
     $record->firstname = 'testuserfirstname';
     $record->lastname = 'testuserlastname';
     $record->email = '*****@*****.**';
     $record->address = 'testuseraddress';
     $record->city = 'testusercity';
     $record->country = 'CA';
     $record->language = 'en';
     $record->testfieldgender = 'Male/Female';
     $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis');
     $importplugin->fslogger = new silent_fslogger(null);
     $importplugin->process_record('user', $record, 'bogus');
     // Validation.
     $userid = $DB->get_field(user::TABLE, 'id', array('username' => 'testuserusername'));
     $user = new user($userid);
     $user->load();
     $user = $user->to_object();
     /*
       $datars = field_data::get_for_context_and_field(\local_elisprogram\context\user::instance($user->id), 'testfieldgender');
       foreach ($datars as $data) {
           ob_start();
           var_dump($data);
           $tmp = ob_get_contents();
           ob_end_clean();
           error_log("test_user_multi_custom_field_on_user_create: data => {$tmp}");
       }
     */
     /*
       ob_start();
       var_dump($user);
       $tmp = ob_get_contents();
       ob_end_clean();
       error_log("test_user_multi_custom_field_on_user_create: user => {$tmp}");
     */
     $this->assertEquals(array($multilangoption1, $multilangoption2), $user->field_testfieldgender);
 }
 /**
  * Set up data that is needed for testing
  */
 private function set_up_required_data($assignusertouserset = true, $assigncoursetoclass = true, $assigntracktoclass = true, $initclusterprofile = false, $initusersetfielddata = true)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/lib/enrollib.php';
     require_once elis::lib('data/customfield.class.php');
     require_once elispm::file('accesslib.php');
     require_once elispm::lib('data/classmoodlecourse.class.php');
     require_once elispm::lib('data/clusterassignment.class.php');
     require_once elispm::lib('data/clustertrack.class.php');
     require_once elispm::lib('data/course.class.php');
     require_once elispm::lib('data/curriculum.class.php');
     require_once elispm::lib('data/pmclass.class.php');
     require_once elispm::lib('data/track.class.php');
     require_once elispm::lib('data/user.class.php');
     require_once elispm::lib('data/userset.class.php');
     require_once elispm::lib('data/usertrack.class.php');
     $fieldcategoryid = $DB->get_field(field_category::TABLE, 'id', array('name' => 'Associated Group'));
     $this->assertNotEquals(false, $fieldcategoryid);
     $fieldcategory = new field_category($fieldcategoryid);
     $fieldcategory->load();
     // Set up the test user.
     $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA'));
     $user->save();
     // Set up the test course description and class instance.
     $course = new course(array('name' => 'testcoursename', 'idnumber' => 'testcourseidnumber', 'syllabus' => ''));
     $course->save();
     $pmclass = new pmclass(array('courseid' => $course->id, 'idnumber' => 'testclassidnumber'));
     $pmclass->save();
     $category = new stdClass();
     $category->name = 'testcategoryname';
     $category->id = $DB->insert_record('course_categories', $category);
     // Set up the test Moodle course.
     set_config('enrol_plugins_enabled', 'manual');
     set_config('defaultenrol', 1, 'enrol_manual');
     set_config('status', ENROL_INSTANCE_ENABLED, 'enrol_manual');
     $course = new stdClass();
     $course->category = $category->id;
     $course->shortname = 'testcourseshortname';
     $course->fullname = 'testcoursefullname';
     $course = create_course($course);
     if ($assigncoursetoclass) {
         // Assign the Moodle course to a class instance.
         $classmoodlecourse = new classmoodlecourse(array('classid' => $pmclass->id, 'moodlecourseid' => $course->id));
         $classmoodlecourse->save();
     }
     // Set up the test program and track.
     $curriculum = new curriculum(array('idnumber' => 'testcurriculumidnumber'));
     $curriculum->save();
     $track = new track(array('curid' => $curriculum->id, 'idnumber' => 'testtrackidnumber'));
     $track->save();
     if ($assigntracktoclass) {
         // Assign the test track to the test class instance.
         $trackassignment = new trackassignment(array('trackid' => $track->id, 'classid' => $pmclass->id, 'autoenrol' => 1));
         $trackassignment->save();
     }
     // Set up the test userset.
     $userset = new userset();
     $usersetdata = array('name' => 'testusersetname');
     if ($initusersetfielddata) {
         $usersetdata['field_userset_group'] = 1;
         $usersetdata['field_userset_groupings'] = 1;
     }
     $userset->set_from_data((object) $usersetdata);
     $userset->save();
     // Assign the test user to the test track.
     $usertrack = new usertrack(array('userid' => $user->id, 'trackid' => $track->id));
     $usertrack->save();
     $clustertrack = new clustertrack(array('clusterid' => $userset->id, 'trackid' => $track->id));
     $clustertrack->save();
     if ($assignusertouserset) {
         // Assign the test user to the test userset.
         $clusterassignment = new clusterassignment(array('userid' => $user->id, 'clusterid' => $userset->id, 'plugin' => 'manual'));
         $clusterassignment->save();
     }
     if ($initclusterprofile) {
         // Set up a file we can use to auto-associate users to a userset.
         $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'autoassociate', 'name' => 'autoassociate', 'datatype' => 'bool'));
         $field->save();
         // Ensure manual field owner exists for syncing.
         field_owner::ensure_field_owner_exists($field, 'manual');
         $ownerid = $DB->get_field(field_owner::TABLE, 'id', array('fieldid' => $field->id, 'plugin' => 'manual'));
         $owner = new field_owner($ownerid);
         $owner->param_control = 'checkbox';
         $owner->save();
         field_owner::ensure_field_owner_exists($field, 'moodle_profile');
         $DB->execute("UPDATE {" . field_owner::TABLE . "} SET exclude = ?", array(pm_moodle_profile::sync_to_moodle));
         $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER));
         $fieldcontextlevel->save();
         // The associated Moodle user profile field.
         require_once $CFG->dirroot . '/user/profile/definelib.php';
         require_once $CFG->dirroot . '/user/profile/field/checkbox/define.class.php';
         $profiledefinecheckbox = new profile_define_checkbox();
         $data = new stdClass();
         $data->datatype = 'checkbox';
         $data->categoryid = 99999;
         $data->shortname = 'autoassociate';
         $data->name = 'autoassociate';
         $profiledefinecheckbox->define_save($data);
         $mfield = $DB->get_record('user_info_field', array('shortname' => 'autoassociate'));
         // The "cluster-profile" association.
         $usersetprofile = new userset_profile(array('clusterid' => $userset->id, 'fieldid' => $mfield->id, 'value' => true));
         $usersetprofile->save();
     }
     // Enrol the user in the Moodle course.
     $mdluserid = $DB->get_field('user', 'id', array('username' => 'testuserusername'));
     $roleid = create_role('testrole', 'testrole', 'testrole');
     enrol_try_internal_enrol($course->id, $mdluserid, $roleid);
     // Set up the necessary config data.
     set_config('userset_groups', 1, 'elisprogram_usetgroups');
     set_config('siteguest', '');
     // Validate setup.
     $this->assertEquals(0, $DB->count_records('groups'));
 }
 /**
  * Set up data that is needed for testing
  *
  * @param boolean $setcustomfielddata Specify whether the userset's custom fields should be set
  * @param boolean $assignuser Specify whether the user should be directly assigned to the user set
  * @param boolean $setautoassociatefields Specity whether we should set up fields that allow userset autoassociation
  */
 private function set_up_required_data($setcustomfielddata = true, $assignuser = true, $setautoassociatefields = false)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elis::lib('data/customfield.class.php');
     require_once elispm::file('accesslib.php');
     require_once elispm::file('enrol/userset/moodleprofile/userset_profile.class.php');
     require_once elispm::lib('data/clusterassignment.class.php');
     require_once elispm::lib('data/user.class.php');
     require_once elispm::lib('data/usermoodle.class.php');
     require_once elispm::lib('data/userset.class.php');
     $fieldcategoryid = $DB->get_field(field_category::TABLE, 'id', array('name' => 'Associated Group'));
     $this->assertNotEquals(false, $fieldcategoryid);
     $fieldcategory = new field_category($fieldcategoryid);
     $fieldcategory->load();
     // Set up the test user.
     $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA'));
     $user->save();
     $user->synchronize_moodle_user();
     // We need a system-level role assignment.
     $roleid = create_role('systemrole', 'systemrole', 'systemrole');
     $userid = $DB->get_field('user', 'id', array('username' => 'testuserusername'));
     $context = context_system::instance();
     role_assign($roleid, $userid, $context->id);
     // Set up the userset.
     $userset = new userset();
     $usersetdata = array('name' => 'testusersetname');
     if ($setcustomfielddata) {
         $usersetdata['field_userset_group'] = 1;
         $usersetdata['field_userset_groupings'] = 1;
     }
     $userset->set_from_data((object) $usersetdata);
     $userset->save();
     if ($setautoassociatefields) {
         // Set up a file we can use to auto-associate users to a userset.
         $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'autoassociate', 'name' => 'autoassociate', 'datatype' => 'bool'));
         $field->save();
         // Ensure manual field owner exists for syncing.
         field_owner::ensure_field_owner_exists($field, 'manual');
         $ownerid = $DB->get_field(field_owner::TABLE, 'id', array('fieldid' => $field->id, 'plugin' => 'manual'));
         $owner = new field_owner($ownerid);
         $owner->param_control = 'checkbox';
         $owner->save();
         field_owner::ensure_field_owner_exists($field, 'moodle_profile');
         $DB->execute("UPDATE {" . field_owner::TABLE . "} SET exclude = ?", array(pm_moodle_profile::sync_to_moodle));
         $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER));
         $fieldcontextlevel->save();
         // The associated Moodle user profile field.
         require_once $CFG->dirroot . '/user/profile/definelib.php';
         require_once $CFG->dirroot . '/user/profile/field/checkbox/define.class.php';
         $profiledefinecheckbox = new profile_define_checkbox();
         $data = new stdClass();
         $data->datatype = 'checkbox';
         $data->categoryid = 99999;
         $data->shortname = 'autoassociate';
         $data->name = 'autoassociate';
         $profiledefinecheckbox->define_save($data);
         $mfield = $DB->get_record('user_info_field', array('shortname' => 'autoassociate'));
         // The "cluster-profile" association.
         $usersetprofile = new userset_profile(array('clusterid' => $userset->id, 'fieldid' => $mfield->id, 'value' => 1));
         $usersetprofile->save();
     }
     if ($assignuser) {
         // Assign the user to the user set.
         $clusterassignment = new clusterassignment(array('clusterid' => $userset->id, 'userid' => $user->id, 'plugin' => 'manual'));
         $clusterassignment->save();
     }
 }
 function action_editfield()
 {
     global $CURMAN;
     $level = $this->required_param('level', PARAM_ACTION);
     $ctxlvl = context_level_base::get_custom_context_level($level, 'block_curr_admin');
     if (!$ctxlvl) {
         print_error('invalid_context_level', 'block_curr_admin');
     }
     $id = $this->optional_param('id', NULL, PARAM_INT);
     require_once CURMAN_DIRLOCATION . '/form/customfieldform.class.php';
     $tmppage = new customfieldpage(array('level' => $level, 'action' => 'editfield'), $this);
     $form = new customfieldform($tmppage->get_moodle_url(), $this);
     if ($form->is_cancelled()) {
         $tmppage = new customfieldpage(array('level' => $level));
         redirect($tmppage->get_url(), get_string('edit_cancelled', 'block_curr_admin'));
     } else {
         if ($data = $form->get_data()) {
             $field = new field($data);
             if ($id) {
                 $field->id = $id;
                 $field->update();
             } else {
                 $field->add();
                 // assume each field only belongs to one context level (for now)
                 $fieldcontext = new field_contextlevel();
                 $fieldcontext->fieldid = $field->id;
                 $fieldcontext->contextlevel = $ctxlvl;
                 $fieldcontext->add();
             }
             //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) {
                     // 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);
                 }
                 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 = get_list_of_plugins('curriculum/plugins');
             foreach ($plugins as $plugin) {
                 if (is_readable(CURMAN_DIRLOCATION . '/plugins/' . $plugin . '/custom_fields.php')) {
                     include_once CURMAN_DIRLOCATION . '/plugins/' . $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->get_url(), get_string('field_saved', 'block_curr_admin', $field));
         } else {
             if (!empty($id)) {
                 if ($this->optional_param('from', NULL, PARAM_CLEAN) == 'moodle' && $level == 'user') {
                     $moodlefield = $CURMAN->db->get_record('user_info_field', 'id', $id);
                     if (!$moodlefield) {
                         print_error('invalidfieldid', 'block_curr_admin');
                     }
                     unset($moodlefield->id);
                     $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::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_array = $data->to_array();
                     $defaultdata = field_data::get_for_context_and_field(NULL, $data);
                     if (!empty($defaultdata)) {
                         if ($data->multivalued) {
                             $values = array();
                             // extract the data
                             foreach ($defaultdata as $data) {
                                 $values[] = $data->data;
                             }
                             // represent as a CSV string
                             $fh = fopen("php://memory", "rw");
                             fputcsv($fh, $values);
                             rewind($fh);
                             $defaultdata = fgets($fh);
                             fclose($fh);
                         } else {
                             $defaultdata = current($defaultdata);
                             $defaultdata = $defaultdata->data;
                         }
                     }
                     $data_array['defaultdata'] = $defaultdata;
                     $plugins = get_list_of_plugins('curriculum/plugins');
                     foreach ($plugins as $plugin) {
                         if (is_readable(CURMAN_DIRLOCATION . '/plugins/' . $plugin . '/custom_fields.php')) {
                             include_once CURMAN_DIRLOCATION . '/plugins/' . $plugin . '/custom_fields.php';
                             if (function_exists("{$plugin}_field_get_form_data")) {
                                 $data_array += call_user_func("{$plugin}_field_get_form_data", $form, $data);
                             }
                         }
                     }
                 }
                 $form->set_data($data_array);
             }
             $form->display();
         }
     }
 }
Exemple #20
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;
 }
 /**
  * Create a test custom field.
  * @return field The test custom field.
  */
 protected function create_field($shortname, field_category &$cat, $context)
 {
     $data = new stdClass();
     $data->shortname = $shortname;
     $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();
     return $field;
 }
 /**
  * Helper method for creating a custom field
  *
  * @param int $contextlevel The context level for which to create the field
  * @param string $uitype The input control / UI type
  * @param array $otherparams Other parameters to give to the field owner
  */
 private function create_custom_field($contextlevel, $uitype, $otherparams)
 {
     global $CFG;
     require_once $CFG->dirroot . '/local/eliscore/lib/data/customfield.class.php';
     // Category.
     $fieldcategory = new field_category(array('name' => 'testcategoryname'));
     $fieldcategory->save();
     // Field.
     $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'testfieldshortname', 'name' => 'testfieldname', 'datatype' => 'text'));
     $field->save();
     // Field-contextlevel.
     $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => $contextlevel));
     $fieldcontextlevel->save();
     // Owner.
     $ownerparams = array_merge(array('control' => $uitype), $otherparams);
     field_owner::ensure_field_owner_exists($field, 'manual', $ownerparams);
 }
 /**
  * Makes sure that a custom field (identified by $field->shortname) exists
  * for the given context level.  If not, it will create a field, putting it
  * in the given category (identified by $category->name), creating it if
  * necessary.
  *
  * @param object a field object, specifying the field configuration if a
  * new field is created
  * @param mixed the context level
  * @param object a field_category object, specifying the category
  * configuration if a new category is created
  * @return object a field object
  */
 static function ensure_field_exists_for_context_level($field, $ctx_lvl, $category)
 {
     if (!is_numeric($ctx_lvl)) {
         $ctx_lvl = context_level_base::get_custom_context_level($ctx_lvl, 'block_curr_admin');
     }
     // see if we need to create a new field
     $fields = field::get_for_context_level($ctx_lvl);
     if (!empty($fields)) {
         foreach ($fields as $f) {
             if ($f->shortname === $field->shortname) {
                 return new field($f);
             }
         }
     }
     // No existing field found.  See if we need to create a category for it
     $categories = field_category::get_for_context_level($ctx_lvl);
     $found = false;
     if (!empty($categories)) {
         foreach ($categories as $c) {
             if ($c->name === $category->name) {
                 $category = $found = $c;
                 break;
             }
         }
     }
     if (!$found) {
         // create the category
         $category->add();
         $categorycontext = new field_category_contextlevel();
         $categorycontext->categoryid = $category->id;
         $categorycontext->contextlevel = $ctx_lvl;
         $categorycontext->add();
     }
     // create the field
     $field->categoryid = $category->id;
     $field->add();
     $fieldcontext = new field_contextlevel();
     $fieldcontext->fieldid = $field->id;
     $fieldcontext->contextlevel = $ctx_lvl;
     $fieldcontext->add();
     return $field;
 }
 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();
         }
     }
 }
 /**
  * Validate that an invalid category for a field causes a field
  * to be moved to the Miscellaneous category
  */
 public function test_orphanedcustomfieldsmovedtomiscellaneouscategory()
 {
     global $CFG, $DB;
     $contextlevel = CONTEXT_ELIS_USERSET;
     $misccat = get_string('misc_category', 'local_elisprogram');
     // Set up a custom field with an invalid category.
     $field = new field(array('name' => 'testcustomfieldname', 'datatype' => 'char', 'categoryid' => '99', 'multivalued' => 1));
     $field->save();
     // Set up the default data.
     $defaultparams = array('fieldid' => $field->id, 'contextid' => $contextlevel, 'data' => 'value1');
     $defaultdata = new field_data_char($defaultparams);
     $defaultdata->save();
     // Also create a contextlevel record for the field.
     $fieldcontext = new field_contextlevel();
     $fieldcontext->fieldid = $field->id;
     $fieldcontext->contextlevel = $contextlevel;
     $fieldcontext->save();
     // Call function to check if this is an orphaned field.
     pm_fix_orphaned_fields();
     // Assert that the field exists.
     $result = $DB->get_field(field::TABLE, 'id', array('id' => $field->id));
     $this->assertEquals($field->id, $result);
     // Assert that the field is in the correct context still.
     $sql = "SELECT field.id\n                  FROM {" . field::TABLE . "} field\n                  JOIN {" . field_contextlevel::TABLE . "} ctx\n                    ON ctx.fieldid = field.id\n                 WHERE ctx.contextlevel = ?\n                   AND field.id = ?";
     $params = array($contextlevel, $field->id);
     $result = $DB->get_field_sql($sql, $params);
     $this->assertEquals($field->id, $result);
     // Assert that the Miscellaneous category exists.
     $result = $DB->get_field(field_category::TABLE, 'name', array('name' => $misccat));
     $this->assertEquals($misccat, $result);
     // Assert that the Miscellaneous category is in the correct context.
     $sql = "SELECT category.name\n                  FROM {" . field_category::TABLE . "} category\n                  JOIN {" . field_category_contextlevel::TABLE . "} category_context\n                    ON category.id = category_context.categoryid\n                 WHERE category_context.contextlevel = ?\n                   AND category.name = ?";
     $params = array($contextlevel, $misccat);
     $result = $DB->get_field_sql($sql, $params);
     $this->assertEquals($misccat, $result);
     // Assert that the field is in the Miscellaneous category.
     $sql = "SELECT field.id\n                  FROM {" . field::TABLE . "} field\n                  JOIN {" . field_category::TABLE . "} category\n                    ON category.id = field.categoryid\n                 WHERE field.id = ?\n                   AND category.name = ?";
     $params = array($field->id, $misccat);
     $result = $DB->get_field_sql($sql, $params);
     $this->assertEquals($field->id, $result);
     // Now check that an invalid field will be moved to the existing Miscellaneous category
     // and not create a second Miscellaneous category.
     // Set up a custom field with an invalid category.
     $field = new field(array('name' => 'testcustomfieldname2', 'datatype' => 'char', 'categoryid' => '109'));
     $field->save();
     // Set up the default data.
     $defaultparams = array('fieldid' => $field->id, 'contextid' => $contextlevel, 'data' => 'value2');
     $defaultdata = new field_data_char($defaultparams);
     $defaultdata->save();
     // Also create a contextlevel record for the field.
     $fieldcontext = new field_contextlevel();
     $fieldcontext->fieldid = $field->id;
     $fieldcontext->contextlevel = $contextlevel;
     $fieldcontext->save();
     // Call function to check if this is an orphaned field.
     pm_fix_orphaned_fields();
     // Assert that only one Miscellaneous category exists.
     $result = $DB->get_records(field_category::TABLE, array('name' => $misccat));
     $this->assertEquals(1, count($result));
     // Assert that the field is in the Miscellaneous category.
     $sql = "SELECT field.id\n                  FROM {" . field::TABLE . "} field\n                  JOIN {" . field_category::TABLE . "} category\n                    ON category.id = field.categoryid\n                 WHERE field.id = ?\n                   AND category.name = ?";
     $params = array($field->id, $misccat);
     $result = $DB->get_field_sql($sql, $params);
     $this->assertEquals($field->id, $result);
 }
 /**
  * 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;
 }
Exemple #27
0
 /**
  * Makes sure that a custom field (identified by $field->shortname) exists
  * for the given context level.  If not, it will create a field, putting it
  * in the given category (identified by $category->name), creating it if
  * necessary.
  *
  * @param field $field a field object, specifying the field configuration
  * if a new field is created
  * @param mixed $contextlevel the context level
  * @param field_category $category a field_category object, specifying the
  * category configuration if a new category is created
  * @return object a field object
  */
 public static function ensure_field_exists_for_context_level(field $field, $contextlevel, field_category $category)
 {
     if (!is_numeric($contextlevel)) {
         $contextlevel = \local_eliscore\context\helper::get_level_from_name($contextlevel);
     }
     // see if we need to create a new field
     $fields = self::get_for_context_level($contextlevel);
     if (!empty($fields)) {
         foreach ($fields as $f) {
             if ($f->shortname === $field->shortname) {
                 return $f;
             }
         }
     }
     // No existing field found.  See if we need to create a category for it
     $categories = field_category::get_for_context_level($contextlevel);
     $found = false;
     if (!empty($categories)) {
         foreach ($categories as $c) {
             if ($c->name === $category->name) {
                 $category = $found = $c;
                 break;
             }
         }
     }
     if (!$found) {
         // create the category
         $category->save();
         $categorycontext = new field_category_contextlevel();
         $categorycontext->categoryid = $category->id;
         $categorycontext->contextlevel = $contextlevel;
         $categorycontext->save();
     }
     // create the field
     $field->categoryid = $category->id;
     $field->save();
     $fieldcontext = new field_contextlevel();
     $fieldcontext->fieldid = $field->id;
     $fieldcontext->contextlevel = $contextlevel;
     $fieldcontext->save();
     return $field;
 }