/**
  * Test custom userset theme assignment.
  */
 public function test_customusersetthemectx()
 {
     $this->load_csv_data();
     // ELIS user with the associated moodle user.
     $user = new user(103);
     $muser = $user->get_moodleuser();
     // Userset with a custom theme.
     $userset = new userset(1);
     $userset->field__elis_userset_theme = 'formal_white';
     $userset->field__elis_userset_themepriority = 1;
     $userset->save();
     // Assign the user to the user set.
     $usersetassign = new clusterassignment();
     $usersetassign->userid = $user->id;
     $usersetassign->clusterid = $userset->id;
     $usersetassign->save();
     // Pretend to be that user.
     $this->setUser($muser->id);
     // Initialize page.
     $page = new moodle_page();
     $page->initialise_theme_and_output();
     // Assert we have our theme.
     $this->assertEquals('formal_white', $page->theme->name);
     $this->setUser(null);
 }
 /**
  * Test block_elisadmin_load_menu_children_course function.
  */
 public function test_block_elisadmin_load_menu_children_course()
 {
     global $DB, $USER;
     accesslib_clear_all_caches(true);
     // Create test user - ensure the returned user is NOT a site admin. if they are, our capability restrictions won't work.
     $testuser = new user();
     $testuser->username = '******';
     $testuser->idnumber = 'testELIS4093';
     $testuser->firstname = 'testELIS4093';
     $testuser->lastname = 'testELIS4093';
     $testuser->email = '*****@*****.**';
     $testuser->country = 'CA';
     $testuser->save();
     $testmuser = $testuser->get_moodleuser();
     // Create role with cap: 'local/elisprogram:class_view'.
     $testrole = new stdClass();
     $testrole->name = 'ELIS Class View';
     $testrole->shortname = '_test_ELIS_4093';
     $testrole->description = 'ELIS Class View';
     $testrole->archetype = '';
     $testrole->id = create_role($testrole->name, $testrole->shortname, $testrole->description, $testrole->archetype);
     // Ensure our new role is assignable to ELIS class contexts.
     set_role_contextlevels($testrole->id, array(CONTEXT_ELIS_CLASS));
     // Ensure the role has our required capability assigned.
     $sitecontext = context_system::instance();
     assign_capability('local/elisprogram:class_view', CAP_ALLOW, $testrole->id, $sitecontext->id, true);
     $sitecontext->mark_dirty();
     // Create ELIS Course Description.
     $testcrs = new course(array('name' => 'CD-ELIS-4093', 'idnumber' => 'CDELIS4093', 'syllabus' => ''));
     $testcrs->save();
     $testcrs->load();
     // Create three(3) Class Instances for Course Descrption.
     $testcls1 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.1'));
     $testcls1->save();
     $testcls1->load();
     $testcls2 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.2'));
     $testcls2->save();
     $testcls2->load();
     $testcls3 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.3'));
     $testcls3->save();
     $testcls3->load();
     // Assign testuser new role in one Class Instance.
     $context = \local_elisprogram\context\pmclass::instance($testcls2->id);
     role_assign($testrole->id, $testmuser->id, $context->id);
     // Switch to testuser.
     $USER = $testmuser;
     $this->setUser($testmuser);
     $items = block_elisadmin_load_menu_children_course($testcrs->id, 0, 0, 5, '');
     $this->assertEquals(1, count($items));
     $this->assertTrue($items[0]->name == 'pmclass_2');
 }
 /**
  * Validate that mappings are applied during the user enrolment (role assignment) delete action
  */
 public function test_mapping_applied_during_user_enrolment_delete()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/local/elisprogram/accesslib.php';
     $this->init_mapping();
     $userid = $this->create_test_user();
     $user = new user($userid);
     $user->load();
     $muser = $user->get_moodleuser();
     $roleid = create_role('testrolename', 'testroleshortname', 'testroledescription');
     $instance = context_user::instance($muser->id);
     role_assign($roleid, $muser->id, $instance->id);
     // Run the user enrolment delete actions.
     $record = new stdClass();
     $record->customaction = 'delete';
     $record->customcontext = 'user_testuseridnumber';
     $record->customuser_username = '******';
     $record->customuser_email = '*****@*****.**';
     $record->customuser_idnumber = 'testuseridnumber';
     $record->customrole = 'testroleshortname';
     $this->run_enrolment_import((array) $record);
     // Validation.
     $this->assertEquals(0, $DB->count_records('role_assignments'));
 }
 /**
  * ELIS-4749: Test for assigning a user a role on a user context
  */
 public function test_assignuserforusersetctx()
 {
     global $DB;
     // Get role to assign (we'll just take the first one returned).
     $rolesctx = $DB->get_records('role_context_levels', array('contextlevel' => CONTEXT_ELIS_USERSET));
     foreach ($rolesctx as $rolectx) {
         $roleid = $rolectx->roleid;
         break;
     }
     // Get user to assign role.
     $user = new user(103);
     $muser = $user->get_moodleuser();
     // Get specific context.
     $usrset = new userset(1);
     $context = \local_elisprogram\context\userset::instance($usrset->id);
     // Assign role.
     $this->assertGreaterThan(0, role_assign($roleid, $muser->id, $context->id));
 }
Exemple #5
0
 /**
  * Return the HTML to for a view page that also allows editing.
  *
  * @param int $classid The class ID.
  * @param string $type The entity type.
  * @param string $sort Field to sort on.
  * @param string $dir Direction of sort.
  * @param int $page The page to start at.
  * @param int $perpage Number of records per page.
  * @param string $namesearch Search string for item name.
  * @param string $alpha Start initial of item name filter.
  * @return string The form HTML, without the form.
  */
 public function view_form_html($classid, $type = '', $sort = 'name', $dir = 'ASC', $page = 0, $perpage = 0, $namesearch = '', $alpha = '')
 {
     global $CFG, $OUTPUT, $PAGE, $SESSION;
     $pageid = optional_param('id', 1, PARAM_INT);
     $pagetype = optional_param('s', '', PARAM_ALPHA);
     $target = optional_param('action', '', PARAM_ALPHA);
     $pagename = $pagetype . $pageid . $target;
     $output = '';
     ob_start();
     $can_unenrol = pmclasspage::can_enrol_into_class($classid);
     if (empty($this->id)) {
         $columns = array('select' => array('header' => get_string('select'), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'unenrol' => array('header' => get_string('unenrol', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'idnumber' => array('header' => get_string('student_idnumber', self::LANG_FILE), 'display_function' => 'htmltab_display_function'), 'name' => array('header' => get_string('student_name_1', self::LANG_FILE), 'display_function' => 'htmltab_display_function'), 'enrolmenttime' => array('header' => get_string('enrolment_time', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'completetime' => array('header' => get_string('completion_time', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'completestatusid' => array('header' => get_string('student_status', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'grade' => array('header' => get_string('student_grade', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'credits' => array('header' => get_string('student_credits', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'locked' => array('header' => get_string('student_locked', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'edited' => array('header' => get_string('student_edited', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'));
         if (!$can_unenrol) {
             unset($columns['unenrol']);
         }
     } else {
         $columns = array('idnumber' => array('header' => get_string('student_idnumber', self::LANG_FILE), 'display_function' => 'htmltab_display_function'), 'name' => array('header' => get_string('student_name_1', self::LANG_FILE), 'display_function' => 'htmltab_display_function'), 'enrolmenttime' => array('header' => get_string('enrolment_time', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'completetime' => array('header' => get_string('completion_time', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'completestatusid' => array('header' => get_string('student_status', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'grade' => array('header' => get_string('student_grade', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'credits' => array('header' => get_string('student_credits', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'), 'locked' => array('header' => get_string('student_locked', self::LANG_FILE), 'sortable' => false, 'display_function' => 'htmltab_display_function'));
     }
     if ($dir !== 'DESC') {
         $dir = 'ASC';
     }
     if (isset($columns[$sort])) {
         $columns[$sort]['sortable'] = $dir;
     } else {
         $sort = 'name';
         $columns[$sort]['sortable'] = $dir;
     }
     $users = array();
     if (empty($this->id)) {
         $do_select_all = optional_param('do_select_all', '0', PARAM_CLEAN);
         if (!empty($do_select_all) && $do_select_all === '1') {
             // save all users as selected in session (user clicked "select all on all pages" button)
             $users = $this->get_users_enrolled($type, $sort, $dir, 0, 0, '', '');
             foreach ($users as $userid => $user) {
                 $SESSION->associationpage[$pagename][$userid] = new stdClass();
                 $SESSION->associationpage[$pagename][$userid]->id = $userid;
                 $SESSION->associationpage[$pagename][$userid]->selected = true;
                 $SESSION->associationpage[$pagename][$userid]->associd = $user->association_id;
             }
             echo get_string('success', self::LANG_FILE);
             die;
         } else {
             $users = $this->get_users_enrolled($type, $sort, $dir, $page * $perpage, $perpage, $namesearch, $alpha);
             $usercount = $this->count_users_enrolled($type, $namesearch, $alpha);
         }
         pmalphabox(new moodle_url('/local/elisprogram/index.php', array('s' => 'stu', 'section' => 'curr', 'action' => 'bulkedit', 'id' => $classid, 'class' => $classid, 'perpage' => $perpage, 'search' => $namesearch, 'sort' => $sort, 'dir' => $dir)), 'alpha', get_string('lastname', self::LANG_FILE) . ':');
         $pagingbar = new paging_bar($usercount, $page, $perpage, "index.php?s=stu&section=curr&id={$classid}&class={$classid}&&action=bulkedit&" . "sort={$sort}&dir={$dir}&perpage={$perpage}&alpha={$alpha}&stype={$type}" . "&search=" . urlencode($namesearch));
         // TBD: .'&'
         echo $OUTPUT->render($pagingbar);
         flush();
         pmsearchbox(null, 'search', 'get', get_string('show_all_users', self::LANG_FILE));
         // TBD: moved from below
     } else {
         $newuser = new stdClass();
         $newuser->name = '?';
         if ($user = new user($this->userid)) {
             $user->load();
             $newuser = $user->to_object();
             $newuser->name = $user->moodle_fullname();
         }
         $users[] = $newuser;
         $usercount = 0;
     }
     $has_users = is_array($users) && !empty($users) || $users instanceof Iterator && $users->valid() === true ? true : false;
     if (empty($this->id) && $has_users === false) {
         pmshowmatches($alpha, $namesearch);
         $table = null;
     } else {
         $stuobj = new student();
         $newarr = array();
         // $table->width = "100%"; // TBD
         $pmclass = new pmclass($classid);
         if (empty(elis::$config->local_elisprogram->force_unenrol_in_moodle)) {
             $mcourse = $pmclass->get_moodle_course_id();
             $ctx = $mcourse ? context_course::instance($mcourse) : 0;
         }
         foreach ($users as $user) {
             $selected = false;
             $locked = $user->locked;
             $credits = $user->credits;
             $grade = $user->grade;
             $status = $user->completestatusid;
             $enrolmenttime = $user->enrolmenttime;
             $completetime = $user->completetime;
             $unenrol = false;
             $changed = false;
             $selection = retrieve_session_selection_bulkedit($user->id, 'bulkedit');
             if ($selection) {
                 if (isset($selection->selected) && $selection->selected === true) {
                     $selected = $selection->selected;
                 }
                 if (isset($selection->unenrol) && $selection->unenrol === true) {
                     $unenrol = $selection->unenrol;
                 }
                 if (isset($selection->locked) && $selection->locked === true) {
                     $locked = $selection->locked;
                 }
                 if (isset($selection->credits)) {
                     $credits = $selection->credits;
                 }
                 if (isset($selection->grade)) {
                     $grade = $selection->grade;
                 }
                 if (isset($selection->status)) {
                     $status = $selection->status;
                 }
                 if (isset($selection->enrolment_date)) {
                     $enrolmenttime = pm_timestamp(0, 0, 0, $selection->enrolment_date->month, $selection->enrolment_date->day, $selection->enrolment_date->year);
                 }
                 if (isset($selection->completion_date)) {
                     $completetime = pm_timestamp(0, 0, 0, $selection->completion_date->month, $selection->completion_date->day, $selection->completion_date->year);
                 }
                 $changed = true;
             }
             $tabobj = new stdClass();
             foreach ($columns as $column => $cdesc) {
                 switch ($column) {
                     case 'select':
                         $tabobj->{$column} = '<input type="checkbox" onclick="select_item(' . $user->id . ')" name="users[' . $user->id . '][selected]" ' . 'value="1" id="selected' . $user->id . '" ' . ($selected ? 'checked="checked" ' : ' ') . 'onchange="proxy_select(' . $user->id . ')"/>';
                         break;
                     case 'unenrol':
                         if (!empty($mcourse)) {
                             $userobj = new user($user);
                             $muser = $userobj->get_moodleuser();
                             if (!empty($muser)) {
                                 $role_assignment_exists = $this->_db->record_exists_select('role_assignments', "userid = ? AND contextid = ? AND component != 'enrol_elis'", array($muser->id, $ctx->id));
                                 if ($role_assignment_exists) {
                                     // user is assigned a role other than via the elis
                                     // enrolment plugin
                                     $tabobj->{$column} = '';
                                     break;
                                 }
                             }
                         }
                         $tabobj->{$column} = '<input type="checkbox" id="unenrol' . $user->id . '" name="users[' . $user->id . '][unenrol]" ' . 'value="1" onchange="proxy_select(' . $user->id . ')" ' . ($unenrol ? 'checked="checked" ' : ' ') . '/>';
                         break;
                     case 'name':
                     case 'idnumber':
                     case 'description':
                         $tabobj->{$column} = $user->{$column};
                         break;
                     case 'enrolmenttime':
                         $tabobj->{$column} = cm_print_date_selector('users[' . $user->id . '][startday]', 'users[' . $user->id . '][startmonth]', 'users[' . $user->id . '][startyear]', $enrolmenttime, true, 'proxy_select(' . $user->id . ')');
                         break;
                     case 'completetime':
                         $tabobj->{$column} = cm_print_date_selector('users[' . $user->id . '][endday]', 'users[' . $user->id . '][endmonth]', 'users[' . $user->id . '][endyear]', $completetime, true, 'proxy_select(' . $user->id . ')');
                         break;
                     case 'completestatusid':
                         $choices = array();
                         foreach (student::$completestatusid_values as $key => $csidv) {
                             $choices[$key] = get_string($csidv, self::LANG_FILE);
                         }
                         $tabobj->{$column} = cm_choose_from_menu($choices, 'users[' . $user->id . '][completestatusid]', $status, '', 'proxy_select(' . $user->id . ')', '', true);
                         break;
                     case 'grade':
                         $tabobj->{$column} = '<input type="text" id="grade' . $user->id . '" id="locked' . $user->id . '" ' . 'name="users[' . $user->id . '][grade]" value="' . $grade . '" ' . 'size="5" onchange="proxy_select(' . $user->id . ')" />';
                         break;
                     case 'credits':
                         $tabobj->{$column} = '<input type="text" id="credits' . $user->id . '" name="users[' . $user->id . '][credits]" ' . 'value="' . $credits . '" size="5" onchange="proxy_select(' . $user->id . ')" />';
                         break;
                     case 'locked':
                         $tabobj->{$column} = '<input type="checkbox" id="locked' . $user->id . '" name="users[' . $user->id . '][locked]" value="1" ' . ($locked ? 'checked="checked" ' : ' ') . 'onchange="proxy_select(' . $user->id . ')" />' . '<input type="hidden" name="users[' . $user->id . '][idnumber]" value="' . $user->idnumber . '" />' . '<input type="hidden" id="associationid' . $user->id . '" name="users[' . $user->id . '][association_id]" ' . 'value="' . $user->association_id . '" />';
                         break;
                     case 'edited':
                         $tabobj->{$column} = '<input type="checkbox" name="users[' . $user->id . '][changed]" id="changed' . $user->id . '" ' . ($changed ? 'checked="checked" ' : ' ') . '/>';
                         break;
                     default:
                         $tabobj->{$column} = '';
                         break;
                 }
             }
             $newarr[] = $tabobj;
             // $table->data[] = $newarr;
         }
         // TBD: student_table() ???
         $table = new display_table($newarr, $columns, $this->get_base_url(), 'sort', 'dir', array('id' => 'selectiontbl', 'width' => '100%'));
     }
     unset($users);
     $ids_for_checkbox_selection = !empty($SESSION->associationpage[$pagename]) && is_array($SESSION->associationpage[$pagename]) ? array_keys($SESSION->associationpage[$pagename]) : array();
     print_ids_for_checkbox_selection($ids_for_checkbox_selection, $classid, 'stu', 'bulkedit');
     if (empty($this->id)) {
         echo '<form method="post" action="index.php?s=stu&amp;section=curr&amp;id=' . $classid . '" >' . "\n";
         echo '<input type="hidden" name="action" value="updatemultiple_confirm" />' . "<br />\n";
         echo '<input type="hidden" name="sesskey" value="' . sesskey() . '"/>';
         echo $this->get_bulk_edit_ui();
     } else {
         echo '<form method="post" action="index.php?s=stu&amp;section=curr&amp;id=' . $classid . '" >' . "\n";
         echo '<input type="hidden" name="action" value="updatemultiple" />' . "\n";
         echo '<input type="hidden" name="sesskey" value="' . sesskey() . '"/>';
         echo '<input type="hidden" name="association_id" value="' . $this->id . '" />' . "\n";
         echo '<input type="hidden" name="id" value="' . $this->classid . '" />' . "\n";
         echo '<input type="hidden" name="userid" value="' . $this->userid . '" />' . "\n";
     }
     if (!empty($newarr)) {
         // TBD: $newarr or $table?
         if (empty($this->id)) {
             $PAGE->requires->js('/local/elisprogram/js/classform_bulkedit.js');
             $numselected_allpages = !empty($SESSION->associationpage[$pagename]) ? count($SESSION->associationpage[$pagename]) : 0;
             $str_numchanged_allpages = get_string('numchanged_allpages', 'local_elisprogram', array('num' => '<span id="numselected_allpages">' . $numselected_allpages . '</span>'));
             echo '<div style="display:inline-block;width:100%">';
             echo '<span style="float:right;font-weight:bold">' . $str_numchanged_allpages . '</span>';
             echo '<input type="button" onclick="checkbox_select(true,\'[selected]\',\'selected\')" value="' . get_string('selectallonpage', self::LANG_FILE) . '" /> ';
             echo '<input type="button" onclick="do_select_all();" value="' . get_string('selectallonallpages', self::LANG_FILE) . '" /> ';
             echo '<input type="button" onclick="checkbox_select(false,\'[selected]\',\'selected\')" value="' . get_string('deselectallonpage', self::LANG_FILE) . '" /> ';
             echo '<input type="button" onclick="do_deselect_all();" value="' . get_string('deselectallonallpages', self::LANG_FILE) . '" /> ';
             echo '</div>';
         }
         echo $table->get_html();
     }
     if (isset($this->id)) {
         $elements = $this->pmclass->course->get_completion_elements();
         if (!empty($elements) && $elements->valid() === true) {
             $select = 'classid = ? AND userid = ? ';
             $grades = $this->_db->get_records_select(student_grade::TABLE, $select, array($this->classid, $this->userid), 'id', 'completionid,id,classid,userid,grade,locked,timegraded,timemodified');
             $columns = array('element' => array('header' => get_string('grade_element', self::LANG_FILE), 'display_function' => 'htmltab_display_function'), 'grade' => array('header' => get_string('grade', self::LANG_FILE), 'display_function' => 'htmltab_display_function'), 'locked' => array('header' => get_string('student_locked', self::LANG_FILE), 'display_function' => 'htmltab_display_function'), 'timegraded' => array('header' => get_string('date_graded', self::LANG_FILE), 'display_function' => 'htmltab_display_function'));
             if ($dir !== 'DESC') {
                 $dir = 'ASC';
             }
             if (isset($columns[$sort])) {
                 $columns[$sort]['sortable'] = $dir;
             } else {
                 $sort = 'element';
                 // TBD
                 $columns[$sort]['sortable'] = $dir;
             }
             // $table->width = "100%"; // TBD
             $newarr = array();
             foreach ($elements as $element) {
                 $tabobj = new stdClass();
                 foreach ($columns as $column => $cdesc) {
                     switch ($column) {
                         case 'element':
                             if (isset($grades[$element->id])) {
                                 $name = 'element[' . $grades[$element->id]->id . ']';
                                 $value = $element->id;
                             } else {
                                 $name = 'newelement[' . $element->id . ']';
                                 $value = $element->id;
                             }
                             $tabobj->{$column} = '<input type="hidden" name="' . $name . '" ' . 'value="' . $value . '" />' . s($element->idnumber);
                             break;
                         case 'timegraded':
                             if (isset($grades[$element->id])) {
                                 $name = 'timegraded[' . $grades[$element->id]->id . ']';
                                 $value = $grades[$element->id]->timegraded;
                             } else {
                                 $name = 'newtimegraded[' . $element->id . ']';
                                 $value = 0;
                             }
                             $tabobj->{$column} = cm_print_date_selector($name . '[startday]', $name . '[startmonth]', $name . '[startyear]', $value, true);
                             break;
                         case 'grade':
                             if (isset($grades[$element->id])) {
                                 $name = 'grade[' . $grades[$element->id]->id . ']';
                                 $value = $grades[$element->id]->grade;
                             } else {
                                 $name = 'newgrade[' . $element->id . ']';
                                 $value = 0;
                             }
                             $tabobj->{$column} = '<input type="text" name="' . $name . '" ' . 'value="' . $value . '" size="5" />';
                             break;
                         case 'locked':
                             if (isset($grades[$element->id])) {
                                 $name = 'locked[' . $grades[$element->id]->id . ']';
                                 $value = $grades[$element->id]->locked;
                             } else {
                                 $name = 'newlocked[' . $element->id . ']';
                                 $value = 0;
                             }
                             $tabobj->{$column} = '<input type="checkbox" name="' . $name . '" ' . 'value="1" ' . ($value ? 'checked="checked"' : '') . '/>';
                             break;
                         default:
                             $tabobj->{$column} = '';
                             break;
                     }
                 }
                 $newarr[] = $tabobj;
                 // $table->data[] = $newarr;
             }
             // TBD: student_table() ???
             $table = new display_table($newarr, $columns, $this->get_base_url(), 'sort', 'dir', array('id' => 'wowwww'));
             if (!empty($table)) {
                 // TBD: $newarr or $table?
                 echo '<br />';
                 echo $table->get_html();
             }
         }
         unset($elements);
     }
     if ($has_users === true) {
         echo '<br /><input type="submit" value="' . get_string('save_enrolment_changes', self::LANG_FILE) . '">' . "\n";
     }
     $cancel_js = "document.location='index.php?s=stu&amp;section=curr&amp;action=default&amp;id={$classid}&amp;" . "sort={$sort}&amp;dir={$dir}&amp;perpage={$perpage}&amp;alpha={$alpha}&amp;search=" . urlencode($namesearch) . "';";
     echo '<input type="button" onclick="' . $cancel_js . '" value="' . get_string('cancel') . '" />';
     echo '<input type="button" onclick="datapersist_do_reset()" value="' . get_string('reset') . '" />';
     echo '</form>' . "\n";
     $output = ob_get_contents();
     ob_end_clean();
     return $output;
 }
 /**
  * Test main newenrolmentemail() function.
  */
 public function test_version1importnewenrolmentemail()
 {
     global $CFG, $DB;
     // This is needed by the required files.
     require_once dirname(__FILE__) . '/other/rlip_importplugin_version1elis_fakeemail.php';
     $importplugin = new rlip_importplugin_version1elis_fakeemail();
     // Create Moodle course.
     $course = $this->getDataGenerator()->create_course();
     // Enrol some students into Moodle course.
     $user2 = $this->getDataGenerator()->create_user();
     $this->getDataGenerator()->enrol_user($user2->id, $course->id);
     $user3 = $this->getDataGenerator()->create_user();
     $this->getDataGenerator()->enrol_user($user3->id, $course->id);
     // Enrol teachers into Moodle course.
     $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
     $teacher = $this->getDataGenerator()->create_user();
     $this->getDataGenerator()->enrol_user($teacher->id, $course->id, $teacherrole->id);
     $teacher2 = $this->getDataGenerator()->create_user();
     $this->getDataGenerator()->enrol_user($teacher2->id, $course->id, $teacherrole->id);
     // Create ELIS class and ELIS user.
     $ecourse = new course(array('name' => 'Test Course', 'idnumber' => 'CRS100', 'syllabus' => ''));
     $ecourse->save();
     $eclass = new pmclass(array('idnumber' => 'CLS100', 'courseid' => $ecourse->id));
     $eclass->save();
     $euser = new user(array('username' => 'testuser', 'idnumber' => 'testuser', 'firstname' => 'Test', 'lastname' => 'User', 'email' => '*****@*****.**', 'city' => 'Waterloo', 'country' => 'CA'));
     $euser->save();
     $muser = $euser->get_moodleuser();
     // Create student object for elis user/elis class.
     $student = new student(array('userid' => $euser->id, 'classid' => $eclass->id));
     // Test false return when student "no_moodle_enrol" is set.
     $student->no_moodle_enrol = true;
     $result = $importplugin->newenrolmentemail($student);
     $this->assertFalse($result);
     $student->no_moodle_enrol = false;
     // Test false return when ELIS class is not linked to Moodle course.
     $DB->delete_records(classmoodlecourse::TABLE, array('classid' => $eclass->id, 'moodlecourseid' => $course->id));
     $result = $importplugin->newenrolmentemail($student);
     $this->assertFalse($result);
     // Test false return when ELIS class is linked to a Moodle course, but Moodle course does not exist.
     $cmcid = $DB->insert_record(classmoodlecourse::TABLE, array('classid' => $eclass->id, 'moodlecourseid' => 999999999));
     $result = $importplugin->newenrolmentemail($student);
     $this->assertFalse($result);
     $DB->update_record(classmoodlecourse::TABLE, array('id' => $cmcid, 'moodlecourseid' => $course->id));
     // Test false return when ELIS user is not linked to Moodle user.
     $DB->delete_records(usermoodle::TABLE, array('cuserid' => $euser->id, 'muserid' => $muser->id));
     $result = $importplugin->newenrolmentemail($student);
     $this->assertFalse($result);
     // Test false return when ELIS user is linked to Moodle user, but Moodle user does not exist.
     $usermoodleid = $DB->insert_record(usermoodle::TABLE, array('cuserid' => $euser->id, 'muserid' => 99999999));
     $result = $importplugin->newenrolmentemail($student);
     $this->assertFalse($result);
     $DB->update_record(usermoodle::TABLE, array('id' => $usermoodleid, 'muserid' => $muser->id));
     // Test false return when not enabled.
     set_config('newenrolmentemailenabled', '0', 'dhimport_version1elis');
     set_config('newenrolmentemailsubject', 'Test Subject', 'dhimport_version1elis');
     set_config('newenrolmentemailtemplate', 'Test Body', 'dhimport_version1elis');
     set_config('newenrolmentemailfrom', 'teacher', 'dhimport_version1elis');
     $result = $importplugin->newenrolmentemail($student);
     $this->assertFalse($result);
     // Test false return when enabled but empty template.
     set_config('newenrolmentemailenabled', '1', 'dhimport_version1elis');
     set_config('newenrolmentemailsubject', 'Test Subject', 'dhimport_version1elis');
     set_config('newenrolmentemailtemplate', '', 'dhimport_version1elis');
     set_config('newenrolmentemailfrom', 'teacher', 'dhimport_version1elis');
     $result = $importplugin->newenrolmentemail($student);
     $this->assertFalse($result);
     // Test success when enabled, has template text, and user has email.
     $testsubject = 'Test Subject';
     $testbody = 'Test Body';
     set_config('newenrolmentemailenabled', '1', 'dhimport_version1elis');
     set_config('newenrolmentemailsubject', $testsubject, 'dhimport_version1elis');
     set_config('newenrolmentemailtemplate', $testbody, 'dhimport_version1elis');
     set_config('newenrolmentemailfrom', 'admin', 'dhimport_version1elis');
     $result = $importplugin->newenrolmentemail($student);
     $this->assertNotEmpty($result);
     $this->assertInternalType('array', $result);
     $this->assertArrayHasKey('user', $result);
     $this->assertEquals($muser, $result['user']);
     $this->assertArrayHasKey('from', $result);
     $this->assertEquals(get_admin(), $result['from']);
     $this->assertArrayHasKey('subject', $result);
     $this->assertEquals($testsubject, $result['subject']);
     $this->assertArrayHasKey('body', $result);
     $this->assertEquals($testbody, $result['body']);
     // Test success and from is set to teacher when selected.
     $testsubject = 'Test Subject';
     $testbody = 'Test Body';
     set_config('newenrolmentemailenabled', '1', 'dhimport_version1elis');
     set_config('newenrolmentemailsubject', $testsubject, 'dhimport_version1elis');
     set_config('newenrolmentemailtemplate', $testbody, 'dhimport_version1elis');
     set_config('newenrolmentemailfrom', 'teacher', 'dhimport_version1elis');
     $result = $importplugin->newenrolmentemail($student);
     $this->assertNotEmpty($result);
     $this->assertInternalType('array', $result);
     $this->assertArrayHasKey('user', $result);
     $this->assertEquals($muser, $result['user']);
     $this->assertArrayHasKey('from', $result);
     $this->assertEquals($teacher, $result['from']);
     $this->assertArrayHasKey('subject', $result);
     $this->assertEquals($testsubject, $result['subject']);
     $this->assertArrayHasKey('body', $result);
     $this->assertEquals($testbody, $result['body']);
     // Test that subject is replaced by empty string when not present.
     $testsubject = null;
     $testbody = 'Test Body';
     set_config('newenrolmentemailenabled', '1', 'dhimport_version1elis');
     set_config('newenrolmentemailsubject', $testsubject, 'dhimport_version1elis');
     set_config('newenrolmentemailtemplate', $testbody, 'dhimport_version1elis');
     set_config('newenrolmentemailfrom', 'admin', 'dhimport_version1elis');
     $result = $importplugin->newenrolmentemail($student);
     $this->assertNotEmpty($result);
     $this->assertInternalType('array', $result);
     $this->assertArrayHasKey('user', $result);
     $this->assertEquals($muser, $result['user']);
     $this->assertArrayHasKey('from', $result);
     $this->assertEquals(get_admin(), $result['from']);
     $this->assertArrayHasKey('subject', $result);
     $this->assertEquals('', $result['subject']);
     $this->assertArrayHasKey('body', $result);
     $this->assertEquals($testbody, $result['body']);
     // Full testing of replacement is done below, but just test that it's being done at all from the main function.
     $testsubject = 'Test Subject';
     $testbody = 'Test Body %%user_username%%';
     $expectedtestbody = 'Test Body ' . $muser->username;
     set_config('newenrolmentemailenabled', '1', 'dhimport_version1elis');
     set_config('newenrolmentemailsubject', $testsubject, 'dhimport_version1elis');
     set_config('newenrolmentemailtemplate', $testbody, 'dhimport_version1elis');
     set_config('newenrolmentemailfrom', 'admin', 'dhimport_version1elis');
     $result = $importplugin->newenrolmentemail($student);
     $this->assertNotEmpty($result);
     $this->assertInternalType('array', $result);
     $this->assertArrayHasKey('user', $result);
     $this->assertEquals($muser, $result['user']);
     $this->assertArrayHasKey('from', $result);
     $this->assertEquals(get_admin(), $result['from']);
     $this->assertArrayHasKey('subject', $result);
     $this->assertEquals($testsubject, $result['subject']);
     $this->assertArrayHasKey('body', $result);
     $this->assertEquals($expectedtestbody, $result['body']);
 }
 /**
  * Test contexts in notifications.
  *
  * Covers:
  * local/elisprogram/lib/notifications.php:616
  * local/elisprogram/lib/notifications.php:617
  */
 public function test_notifications()
 {
     global $DB;
     $this->setup_users();
     context_helper::reset_caches();
     elis::$config->local_elisprogram->notify_classenrol_user = true;
     $rolesctx = $DB->get_records('role_context_levels', array('contextlevel' => CONTEXT_ELIS_PROGRAM));
     foreach ($rolesctx as $rolectx) {
         $roleid = $rolectx->roleid;
         break;
     }
     // Get user to assign role.
     $user = new user(103);
     $muser = $user->get_moodleuser();
     // Get specific context.
     $cur = $this->create_curriculum();
     $context = \local_elisprogram\context\program::instance($cur->id);
     // Assign role.
     $raid = role_assign($roleid, $muser->id, $context);
 }
Exemple #8
0
/**
 *
 * Takes an instructor unassignment and deletes the appropriate
 * Moodle course role assignments
 *
 * @param  stdClass  $eventdata  The appropriate local_elisprogram_cls_nstrct record
 * @return bool always returns true
 */
function pm_notify_instructor_unassigned_handler($eventdata)
{
    global $CFG, $DB;
    require_once elispm::lib('data/user.class.php');
    // make sure users in some roles are identified as course managers
    if (empty($CFG->coursecontact)) {
        return true;
    }
    // create the curriculum administration class
    try {
        if (!($pmclass = new pmclass($eventdata->classid))) {
            return true;
        }
    } catch (dml_missing_record_exception $e) {
        // record does not exists, so no need to sync
        return true;
    }
    // ensure that the class is tied to a Moodle course
    $moodlecourseid = $pmclass->get_moodle_course_id();
    if (empty($moodlecourseid)) {
        return true;
    }
    // retrieve the context for the Moodle course
    $coursecontext = context_course::instance($moodlecourseid);
    if (!$coursecontext) {
        return true;
    }
    // make sure the Moodle course is not tied to other curriculum administration classes
    if ($DB->count_records(classmoodlecourse::TABLE, array('moodlecourseid' => $moodlecourseid)) != 1) {
        return true;
    }
    // Retrieve the Moodle user
    $cmuser = new user();
    $cmuser->id = $eventdata->userid;
    $instructor = $cmuser->get_moodleuser();
    if (!$instructor) {
        return true;
    }
    // Go through all applicable roles to see if we can remove them from the Moodle side of things
    $roleids = explode(',', $CFG->coursecontact);
    $course = new stdClass();
    $course->id = $coursecontext->instanceid;
    // Loop through each of the course contact roles, check if they have the role assignment, unenroll them and remove it
    foreach ($roleids as $roleid) {
        $hasroleassignment = user_has_role_assignment($instructor->id, $roleid, $coursecontext->id);
        if ($hasroleassignment) {
            // This method  unenrolls and removes all of the user's roles from the course @see role_unassign_all()
            $plugin = enrol_get_plugin('elis');
            $enrolinstance = $plugin->get_or_create_instance($course);
            $plugin->unenrol_user($enrolinstance, $instructor->id);
        }
    }
    return true;
}
Exemple #9
0
 /**
  * Send an email to the user when they are enroled.
  *
  * @param student $student The student object of for the enrolment.
  * @return bool Success/Failure.
  */
 public function newenrolmentemail(student $student)
 {
     global $DB;
     if (!empty($student->no_moodle_enrol)) {
         return false;
     }
     // Look for attached Moodle course, and get the course info.
     $moodlecourseid = moodle_get_course($student->classid);
     if (empty($moodlecourseid)) {
         return false;
     }
     $course = $DB->get_record('course', array('id' => $moodlecourseid));
     if (empty($course)) {
         return false;
     }
     // Get the elis user and the moodle user.
     $user = new user($student->userid);
     $muser = $user->get_moodleuser();
     if (empty($muser)) {
         return false;
     }
     // Check whether emails are enabled.
     $enabled = get_config('dhimport_version1elis', 'newenrolmentemailenabled');
     if (empty($enabled)) {
         return false;
     }
     // Check whether email text has been set.
     $template = get_config('dhimport_version1elis', 'newenrolmentemailtemplate');
     if (empty($template)) {
         return false;
     }
     // Ensure Moodle user has an email address.
     if (empty($muser->email)) {
         return false;
     }
     // Get the email subject line, set an empty string if necessary.
     $subject = get_config('dhimport_version1elis', 'newenrolmentemailsubject');
     if (empty($subject) || !is_string($subject)) {
         $subject = '';
     }
     // Get the user the email will be from.
     $from = get_config('dhimport_version1elis', 'newenrolmentemailfrom');
     if ($from === 'teacher') {
         $context = context_course::instance($course->id);
         $cap = 'moodle/course:update';
         if ($users = get_users_by_capability($context, $cap, 'u.*', 'u.id ASC', '', '', '', '', false, true)) {
             $users = sort_by_roleassignment_authority($users, $context);
             $from = current($users);
         } else {
             $from = get_admin();
         }
     } else {
         $from = get_admin();
     }
     // Generate email.
     $body = $this->newenrolmentemail_generate($template, $muser, $course);
     // Send!
     return $this->sendemail($muser, $from, $subject, $body);
 }
Exemple #10
0
/**
 * Handle the event when a user is unassigned from a user set.
 *
 * @uses $DB
 * @param object $usersetinfo The ELIS crlm_cluster_assignments record object.
 * @return bool True on success or failure (event handlers must always return true).
 */
function elis_files_userset_deassigned($usersetinfo) {
    global $DB;

    // Only proceed here if we have valid userid,clusterid & the Alfresco plug-in is actually enabled.
    if (empty($usersetinfo->userid) || empty($usersetinfo->clusterid) ||
        !($repo = repository_factory::factory('elisfiles'))) {
        return true;
    }

    $user = new user($usersetinfo->userid);

    // Get the Moodle user info from the CM user record.
    if (!$muser = $user->get_moodleuser()) {
        return true;
    }

    if (!($userset = $DB->get_record(userset::TABLE, array('id' => $usersetinfo->clusterid)))) {
        return true;
    }

    if (!file_exists(elispm::file('plugins/usetclassify/usersetclassification.class.php'))) {
        return true;
    }

    require_once(elispm::file('plugins/usetclassify/usersetclassification.class.php'));

    // Get the extra user set data and ensure it is present before proceeding.
    $usersetdata = usersetclassification::get_for_cluster($userset);

    if (empty($usersetdata->params)) {
        return true;
    }

    $usersetparams = unserialize($usersetdata->params);

    // Make sure this user set has the Alfresco shared folder property defined
    if (empty($usersetparams['elis_files_shared_folder'])) {
        return true;
    }

    // Does this organization have an Alfresco storage space?
    if (!$uuid = $repo->get_userset_store($userset->id, false)) {
        return true;
    }

    $context = \local_elisprogram\context\userset::instance($userset->id);

    $sql = 'SELECT rc.*
            FROM {role_assignments} ra
            INNER JOIN {role} r ON ra.roleid = r.id
            INNER JOIN {role_capabilities} rc ON r.id = rc.roleid
            WHERE ra.contextid = :contextid
            AND ra.userid = :userid
            AND rc.capability IN (:cap1, :cap2)
            AND rc.permission = '.CAP_ALLOW;

    $params = array(
        'contextid' => $context->id,
        'userid'    => $muser->id,
        'cap1'      => 'repository/elisfiles:createusersetcontent',
        'cap2'      => 'local/elisprogram:userset_enrol'
    );

    // Check if the user has a specific role assignment on the user set context with the editing capability
    if ($DB->record_exists_sql($sql, $params)) {
        // Remove all non-editing permissions for this user on the organization shared space.
        if ($permissions = elis_files_get_permissions($uuid, $muser->username)) {
            foreach ($permissions as $permission) {
                // Do not remove editing permissions if this user still actually has a user set membership.
                if ($permission == ELIS_FILES_ROLE_COLLABORATOR) {
                    continue;
                }

                elis_files_set_permission($muser->username, $uuid, $permission, ELIS_FILES_CAPABILITY_DENIED);
            }
        }

    // Remove all permissions for this user on the organization shared space.
    } else if ($permissions = elis_files_get_permissions($uuid, $muser->username)) {
        require_once(elispm::lib('data/clusterassignment.class.php'));
        foreach ($permissions as $permission) {
            // Do not remove view permissions if this user still actually has a user set membership.
            $params = array(
                'userid'    => $usersetinfo->userid,
                'clusterid' => $userset->id
            );

            if ($permission == ELIS_FILES_ROLE_CONSUMER && $DB->record_exists(clusterassignment::TABLE, $params)) {
                continue;
            }

            elis_files_set_permission($muser->username, $uuid, $permission, ELIS_FILES_CAPABILITY_DENIED);
        }
    }

    return true;
}
Exemple #11
0
 function can_do_delete()
 {
     global $USER;
     // make sure we don't delete the admin user, or ourselves
     $cuser = new user($this->required_param('id', PARAM_INT));
     $muser = $cuser->get_moodleuser();
     if (!isset($muser->id)) {
         //no corresponding Moodle user, so just check the capability
         return $this->_has_capability('local/elisprogram:user_delete');
     }
     return !is_primary_admin($muser->id) && $muser->id != $USER->id && $this->_has_capability('local/elisprogram:user_delete');
 }