Beispiel #1
0
 /**
  * Gets users on course who have the specified capability. Returns an array
  * of user objects which only contain the 'id' field. If the same capability
  * has already been checked (e.g. by another condition) then a cached
  * result will be used.
  *
  * More fields are not necessary because this code is only used to filter
  * users from an existing list.
  *
  * @param string $capability Required capability
  * @return array Associative array of user id => objects containing only id
  */
 public function get_users_by_capability($capability)
 {
     if (!array_key_exists($capability, $this->cache)) {
         $this->cache[$capability] = get_users_by_capability($this->context, $capability, 'u.id');
     }
     return $this->cache[$capability];
 }
Beispiel #2
0
 function print_filter(&$mform)
 {
     global $remotedb, $COURSE;
     //$filter_user = optional_param('filter_user',0,PARAM_INT);
     $reportclassname = 'report_' . $this->report->type;
     $reportclass = new $reportclassname($this->report);
     if ($this->report->type != 'sql') {
         $components = cr_unserialize($this->report->components);
         $conditions = $components['conditions'];
         $userlist = $reportclass->elements_by_conditions($conditions);
     } else {
         $coursecontext = context_course::instance($COURSE->id);
         $userlist = array_keys(get_users_by_capability($coursecontext, 'moodle/user:viewdetails'));
     }
     $useroptions = array();
     $useroptions[0] = get_string('filter_all', 'block_configurable_reports');
     if (!empty($userlist)) {
         list($usql, $params) = $remotedb->get_in_or_equal($userlist);
         $users = $remotedb->get_records_select('user', "id {$usql}", $params);
         foreach ($users as $c) {
             $useroptions[$c->id] = format_string($c->lastname . ' ' . $c->firstname);
         }
     }
     $mform->addElement('select', 'filter_user', get_string('user'), $useroptions);
     $mform->setType('filter_user', PARAM_INT);
 }
/**
 * Returns list of all admins
 *
 * @uses $CFG
 * @return object
 */
function get_admins()
{
    global $CFG;
    $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
    return get_users_by_capability($context, 'moodle/site:doanything', 'u.*, ra.id as adminid', 'ra.id ASC');
    // only need first one
}
 function choice_get_response_data($choice, $cm, $groupmode)
 {
     global $CFG, $USER;
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     /// Get the current group
     if ($groupmode > 0) {
         $currentgroup = groups_get_activity_group($cm);
     } else {
         $currentgroup = 0;
     }
     /// Initialise the returned array, which is a matrix:  $allresponses[responseid][userid] = responseobject
     $allresponses = array();
     /// First get all the users who have access here
     /// To start with we assume they are all "unanswered" then move them later
     $allresponses[0] = get_users_by_capability($context, 'mod/choice:choose', 'u.id, u.picture, u.firstname, u.lastname, u.idnumber', 'u.firstname ASC', '', '', $currentgroup, '', false, true);
     /// Get all the recorded responses for this choice
     $rawresponses = get_records('choice_answers', 'choiceid', $choice->id);
     /// Use the responses to move users into the correct column
     if ($rawresponses) {
         foreach ($rawresponses as $response) {
             if (isset($allresponses[0][$response->userid])) {
                 // This person is enrolled and in correct group
                 $allresponses[0][$response->userid]->timemodified = $response->timemodified;
                 $allresponses[$response->optionid][$response->userid] = clone $allresponses[0][$response->userid];
                 unset($allresponses[0][$response->userid]);
                 // Remove from unanswered column
             }
         }
     }
     return $allresponses;
 }
 function get_professor($course_id)
 {
     $context = get_context_instance(CONTEXT_COURSE, $course_id);
     $users = get_users_by_capability($context, 'moodle/course:managegroups', 'u.id, u.firstname, u.lastname, u.email, u.mailformat, u.phone2', 'lastname ASC, firstname DESC');
     $advanced_users = get_users_by_capability($context, 'moodle/course:create', 'u.id', 'lastname ASC, firstname DESC');
     foreach ($advanced_users as $key => $value) {
         unset($users[$key]);
     }
     return current($users);
 }
function virtualclass_course_teacher_list()
{
    global $COURSE;
    $courseid = $COURSE->id;
    $context = context_course::instance($courseid);
    $heads = get_users_by_capability($context, 'moodle/course:update');
    $teachers = array();
    foreach ($heads as $head) {
        $teachers[$head->id] = fullname($head);
    }
    return $teachers;
}
 /**
  * Sets up form for display to user
  * @global object $CFG Moodle global config
  * @version 2015062901
  * @since 2011042601
  */
 public function definition()
 {
     global $CFG;
     global $PAGE;
     $accountDAO = new TxttoolsAccountDAO();
     $accountCount = $accountDAO->countTxttoolsRecords();
     $PAGE->requires->jquery();
     $PAGE->requires->yui_module('moodle-block_moodletxt-admin', 'M.block_moodletxt.admin.init');
     $installForm =& $this->_form;
     // We need a list of users that can be default inboxes,
     // for the user to choose from for this initial account
     $defaultInboxUsers = get_users_by_capability(context_system::instance(), 'block/moodletxt:defaultinbox');
     $admins = get_admins();
     foreach ($admins as $admin) {
         $defaultInboxUsers[$admin->id] = $admin;
     }
     $defaultInboxList = array();
     foreach ($defaultInboxUsers as $defaultInboxUser) {
         $defaultInboxList[$defaultInboxUser->id] = MoodletxtStringHelper::formatNameForDisplay($defaultInboxUser->firstname, $defaultInboxUser->lastname, $defaultInboxUser->username);
     }
     $ctxtInstances = array();
     $ctxtInstances[TxttoolsAccount::$UK_LOCATION] = TxttoolsAccount::$UK_LOCATION . ' - ' . TxttoolsAccount::$UK_URL;
     $ctxtInstances[TxttoolsAccount::$US_LOCATION] = TxttoolsAccount::$US_LOCATION . ' - ' . TxttoolsAccount::$US_URL;
     $ctxtInstances['URL'] = 'Custom';
     // Txttools account
     $installForm->addElement('header', 'addAccount', get_string('adminlabeladdaccount', 'block_moodletxt'));
     if ($accountCount < 1) {
         $installForm->addElement('select', 'accountCtxtInstance', get_string('adminaccountctxtinstance', 'block_moodletxt'), $ctxtInstances);
         $installForm->setType('accountCtxtInstance', PARAM_STRINGID);
         $installForm->addElement('text', 'accountUrl', get_string('adminaccounturl', 'block_moodletxt'));
         $installForm->setType('accountUrl', PARAM_URL);
     }
     $installForm->addElement('text', 'accountName', get_string('adminlabelaccusername', 'block_moodletxt'), array('maxlength' => 20));
     $installForm->setType('accountName', PARAM_ALPHANUMEXT);
     $installForm->addRule('accountName', get_string('errornousername', 'block_moodletxt'), 'required');
     $installForm->addElement('password', 'accountPassword1', get_string('adminlabelaccpassword', 'block_moodletxt'));
     $installForm->setType('accountPassword1', PARAM_ALPHANUMEXT);
     $installForm->addRule('accountPassword1', get_string('errornopassword', 'block_moodletxt'), 'required');
     $installForm->addRule('accountPassword1', get_string('errorpasswordtooshort', 'block_moodletxt'), 'minlength', 8);
     $installForm->addElement('password', 'accountPassword2', get_string('adminlabelaccpassword2', 'block_moodletxt'));
     $installForm->setType('accountPassword2', PARAM_ALPHANUMEXT);
     $installForm->addRule('accountPassword2', get_string('errornopassword', 'block_moodletxt'), 'required');
     $installForm->addRule('accountPassword2', get_string('errorpasswordtooshort', 'block_moodletxt'), 'minlength', 8);
     $installForm->addElement('text', 'accountDescription', get_string('adminlabelaccdesc', 'block_moodletxt'));
     $installForm->setType('accountDescription', PARAM_TEXT);
     $installForm->addElement('select', 'accountDefaultInbox', get_string('adminlabelaccinbox', 'block_moodletxt'), $defaultInboxList);
     $installForm->setType('accountDefaultInbox', PARAM_INT);
     // Buttons
     $buttonarray = array();
     $buttonarray[] =& $installForm->createElement('submit', 'submitButton', get_string('adminbutaddaccount', 'block_moodletxt'));
     $installForm->addGroup($buttonarray, 'buttonar', '', array(' '), false);
     $installForm->closeHeaderBefore('buttonar');
 }
 public function definition()
 {
     global $USER, $OUTPUT, $CFG;
     $mform = $this->_form;
     $instance = $this->_customdata;
     $this->instance = $instance;
     $plugin = enrol_get_plugin('boleto');
     $heading = $plugin->get_instance_name($instance);
     $mform->addElement('header', 'boletoheader', $heading);
     if ($instance->password) {
         // Change the id of boleto enrolment key input as there can be multiple boleto enrolment methods.
         $mform->addElement('passwordunmask', 'enrolpassword', get_string('password', 'enrol_boleto'), array('id' => 'enrolpassword_' . $instance->id));
         $context = context_course::instance($this->instance->courseid);
         $keyholders = get_users_by_capability($context, 'enrol/boleto:holdkey', user_picture::fields('u'));
         $keyholdercount = 0;
         foreach ($keyholders as $keyholder) {
             $keyholdercount++;
             if ($keyholdercount === 1) {
                 $mform->addElement('static', 'keyholder', '', get_string('keyholder', 'enrol_boleto'));
             }
             $keyholdercontext = context_user::instance($keyholder->id);
             if ($USER->id == $keyholder->id || has_capability('moodle/user:viewdetails', context_system::instance()) || has_coursecontact_role($keyholder->id)) {
                 $profilelink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $keyholder->id . '&amp;course=' . $this->instance->courseid . '">' . fullname($keyholder) . '</a>';
             } else {
                 $profilelink = fullname($keyholder);
             }
             $profilepic = $OUTPUT->user_picture($keyholder, array('size' => 35, 'courseid' => $this->instance->courseid));
             $mform->addElement('static', 'keyholder' . $keyholdercount, '', $profilepic . $profilelink);
         }
     }
     $boletourl = new moodle_url('/enrol/boleto/boleto.php', array('instanceid' => $this->instance->id));
     $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfo', 'enrol_boleto'));
     // customint8 == avista.
     if ($this->instance->customint8) {
         $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfodirectlinks', 'enrol_boleto', $boletourl->out(false)));
     } else {
         $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfoparceladolink0', 'enrol_boleto', $boletourl->out(false)));
         $boletourl->param('parcela', 1);
         $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfoparceladolink1', 'enrol_boleto', $boletourl->out(false)));
         $boletourl->param('parcela', 2);
         $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfoparceladolink2', 'enrol_boleto', $boletourl->out(false)));
     }
     $this->add_action_buttons(false, get_string('enrolme', 'enrol_boleto'));
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->setDefault('id', $instance->courseid);
     $mform->addElement('hidden', 'instance');
     $mform->setType('instance', PARAM_INT);
     $mform->setDefault('instance', $instance->id);
 }
Beispiel #9
0
function getallhiddenrecipients($cid, $bid)
{
    global $sid;
    $debug = false;
    if ($cid == 1) {
        $blockcontext = get_context_instance(CONTEXT_SYSTEM, $sid);
    } else {
        $blockcontext = get_context_instance(CONTEXT_BLOCK, $bid);
    }
    $hiddenrecipients = get_users_by_capability($blockcontext, 'block/contact_form:hiddenrecipient', 'u.id, u.firstname, u.lastname, u.email, u.mailformat', 'u.lastname ASC', '', '', '', '', false);
    if ($debug) {
        echo '****** Written from line ' . __LINE__ . ' of ' . __FILE__ . ' ********<br />';
        echo '<hr />';
        echo 'hiddencollector (block/contact_form:hiddenrecipients)<br />';
        print_object($hiddenrecipients);
    }
    return $hiddenrecipients;
}
 /**
  * Get information about which students to show in the report.
  * @param object $cm the coures module.
  * @return an array with four elements:
  *      0 => integer the current group id (0 for none).
  *      1 => array ids of all the students in this course.
  *      2 => array ids of all the students in the current group.
  *      3 => array ids of all the students to show in the report. Will be the
  *              same as either element 1 or 2.
  */
 protected function load_relevant_students($cm)
 {
     $currentgroup = groups_get_activity_group($cm, true);
     if (!($students = get_users_by_capability($this->context, array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), 'u.id, 1', '', '', '', '', '', false))) {
         $students = array();
     } else {
         $students = array_keys($students);
     }
     if (empty($currentgroup)) {
         return array($currentgroup, $students, array(), $students);
     }
     // We have a currently selected group.
     if (!($groupstudents = get_users_by_capability($this->context, array('mod/quiz:reviewmyattempts', 'mod/quiz:attempt'), 'u.id, 1', '', '', '', $currentgroup, '', false))) {
         $groupstudents = array();
     } else {
         $groupstudents = array_keys($groupstudents);
     }
     return array($currentgroup, $students, $groupstudents, $groupstudents);
 }
 function fetch_course_users($courseid)
 {
     global $CFG, $DB;
     //get course and require requester is logged in
     if (!($course = $DB->get_record('course', array('id' => $courseid)))) {
         print_error('invalidcourseid');
     }
     require_course_login($course);
     //fetch course context
     $coursecontext = \context_course::instance($courseid);
     //fetch user objects for all users in course
     //'u.id, u.username, u.firstname, u.lastname, u.picture'
     $users = get_users_by_capability($coursecontext, 'moodle/user:viewdetails');
     //usersummary variable
     $usersummary = "";
     //set up xml to return
     $xml_output = "<pairsets>\n";
     $pairstreamname = rand(1000000, 9999999);
     $xml_output .= "\t<pair name='{$pairstreamname}' dirty='false'>\n";
     //fill with user "pairelements"
     foreach ($users as $user) {
         $xml_output .= "\t\t<pairelement username='******' showname='" . fullname($user) . "' pictureurl='" . fetch_user_picture($user, 120) . "' />\n";
         if ($usersummary == "") {
             $usersummary .= $user->username;
         } else {
             $usersummary .= ";" . $user->username;
         }
     }
     //close our list of users in the pairset
     $xml_output .= "\t</pair>\n";
     //We also provide a summary of all the users in this course
     //so that the laszlo client doesn't need to xml divine it
     $xml_output .= "\t<usersummary>\n";
     $xml_output .= $usersummary;
     $xml_output .= "\t</usersummary>\n";
     $xml_output .= "</pairsets>";
     //Return the data
     return $xml_output;
 }
Beispiel #12
0
/**
 * get users which have the receivemail-capability
 *
 * @uses CONTEXT_MODULE
 * @param int $cmid
 * @param mixed $groups single groupid or array of groupids - group(s) user is in
 * @return object the userrecords
 */
function feedback_get_receivemail_users($cmid, $groups = false) {

    if (!$context = get_context_instance(CONTEXT_MODULE, $cmid)) {
            print_error('badcontext');
    }

    //description of the call below:
    //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='',
    //                          $limitnum='', $groups='', $exceptions='', $doanything=true)
    return get_users_by_capability($context,
                            'mod/feedback:receivemail',
                            '',
                            'lastname',
                            '',
                            '',
                            $groups,
                            '',
                            false);
}
Beispiel #13
0
 /**
  * Load all of the uses who have the capability into choice array
  *
  * @return bool Always returns true
  */
 function load_choices()
 {
     if (is_array($this->choices)) {
         return true;
     }
     $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
     $this->choices = array('$@NONE@$' => get_string('nobody'), '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)));
     if ($this->includeadmins) {
         $admins = get_admins();
         foreach ($admins as $user) {
             $this->choices[$user->id] = fullname($user);
         }
     }
     if (is_array($users)) {
         foreach ($users as $user) {
             $this->choices[$user->id] = fullname($user);
         }
     }
     return true;
 }
Beispiel #14
0
 /**
  * Add elements to grade form.
  *
  * @param MoodleQuickForm $mform
  * @param stdClass $data
  * @param array $params
  * @return void
  */
 public function add_grade_form_elements(MoodleQuickForm $mform, stdClass $data, $params)
 {
     global $USER, $CFG;
     $settings = $this->get_instance();
     $rownum = $params['rownum'];
     $last = $params['last'];
     $useridlistid = $params['useridlistid'];
     $userid = $params['userid'];
     $attemptnumber = $params['attemptnumber'];
     if (!$userid) {
         $cache = cache::make_from_params(cache_store::MODE_SESSION, 'mod_assign', 'useridlist');
         if (!($useridlist = $cache->get($this->get_course_module()->id . '_' . $useridlistid))) {
             $useridlist = $this->get_grading_userid_list();
             $cache->set($this->get_course_module()->id . '_' . $useridlistid, $useridlist);
         }
     } else {
         $useridlist = array($userid);
         $rownum = 0;
         $useridlistid = '';
     }
     $userid = $useridlist[$rownum];
     $grade = $this->get_user_grade($userid, false, $attemptnumber);
     $submission = null;
     if ($this->get_instance()->teamsubmission) {
         $submission = $this->get_group_submission($userid, 0, false, $attemptnumber);
     } else {
         $submission = $this->get_user_submission($userid, false, $attemptnumber);
     }
     // Add advanced grading.
     $gradingdisabled = $this->grading_disabled($userid);
     $gradinginstance = $this->get_grading_instance($userid, $grade, $gradingdisabled);
     $mform->addElement('header', 'gradeheader', get_string('grade'));
     if ($gradinginstance) {
         $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade') . ':', array('gradinginstance' => $gradinginstance));
         if ($gradingdisabled) {
             $gradingelement->freeze();
         } else {
             $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
             $mform->setType('advancedgradinginstanceid', PARAM_INT);
         }
     } else {
         // Use simple direct grading.
         if ($this->get_instance()->grade > 0) {
             $name = get_string('gradeoutof', 'assign', $this->get_instance()->grade);
             if (!$gradingdisabled) {
                 $gradingelement = $mform->addElement('text', 'grade', $name);
                 $mform->addHelpButton('grade', 'gradeoutofhelp', 'assign');
                 $mform->setType('grade', PARAM_RAW);
             } else {
                 $mform->addElement('hidden', 'grade', $name);
                 $mform->hardFreeze('grade');
                 $mform->setType('grade', PARAM_RAW);
                 $strgradelocked = get_string('gradelocked', 'assign');
                 $mform->addElement('static', 'gradedisabled', $name, $strgradelocked);
                 $mform->addHelpButton('gradedisabled', 'gradeoutofhelp', 'assign');
             }
         } else {
             $grademenu = array(-1 => get_string("nograde")) + make_grades_menu($this->get_instance()->grade);
             if (count($grademenu) > 1) {
                 $gradingelement = $mform->addElement('select', 'grade', get_string('grade') . ':', $grademenu);
                 // The grade is already formatted with format_float so it needs to be converted back to an integer.
                 if (!empty($data->grade)) {
                     $data->grade = (int) unformat_float($data->grade);
                 }
                 $mform->setType('grade', PARAM_INT);
                 if ($gradingdisabled) {
                     $gradingelement->freeze();
                 }
             }
         }
     }
     $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, $userid);
     if (!empty($CFG->enableoutcomes)) {
         foreach ($gradinginfo->outcomes as $index => $outcome) {
             $options = make_grades_menu(-$outcome->scaleid);
             if ($outcome->grades[$userid]->locked) {
                 $options[0] = get_string('nooutcome', 'grades');
                 $mform->addElement('static', 'outcome_' . $index . '[' . $userid . ']', $outcome->name . ':', $options[$outcome->grades[$userid]->grade]);
             } else {
                 $options[''] = get_string('nooutcome', 'grades');
                 $attributes = array('id' => 'menuoutcome_' . $index);
                 $mform->addElement('select', 'outcome_' . $index . '[' . $userid . ']', $outcome->name . ':', $options, $attributes);
                 $mform->setType('outcome_' . $index . '[' . $userid . ']', PARAM_INT);
                 $mform->setDefault('outcome_' . $index . '[' . $userid . ']', $outcome->grades[$userid]->grade);
             }
         }
     }
     $capabilitylist = array('gradereport/grader:view', 'moodle/grade:viewall');
     if (has_all_capabilities($capabilitylist, $this->get_course_context())) {
         $urlparams = array('id' => $this->get_course()->id);
         $url = new moodle_url('/grade/report/grader/index.php', $urlparams);
         $usergrade = '-';
         if (isset($gradinginfo->items[0]->grades[$userid]->str_grade)) {
             $usergrade = $gradinginfo->items[0]->grades[$userid]->str_grade;
         }
         $gradestring = $this->get_renderer()->action_link($url, $usergrade);
     } else {
         $usergrade = '-';
         if (isset($gradinginfo->items[0]->grades[$userid]) && !$gradinginfo->items[0]->grades[$userid]->hidden) {
             $usergrade = $gradinginfo->items[0]->grades[$userid]->str_grade;
         }
         $gradestring = $usergrade;
     }
     if ($this->get_instance()->markingworkflow) {
         $states = $this->get_marking_workflow_states_for_current_user();
         $options = array('' => get_string('markingworkflowstatenotmarked', 'assign')) + $states;
         $mform->addElement('select', 'workflowstate', get_string('markingworkflowstate', 'assign'), $options);
         $mform->addHelpButton('workflowstate', 'markingworkflowstate', 'assign');
     }
     if ($this->get_instance()->markingallocation && has_capability('mod/assign:manageallocations', $this->context)) {
         $markers = get_users_by_capability($this->context, 'mod/assign:grade');
         $markerlist = array('' => get_string('choosemarker', 'assign'));
         foreach ($markers as $marker) {
             $markerlist[$marker->id] = fullname($marker);
         }
         $mform->addElement('select', 'allocatedmarker', get_string('allocatedmarker', 'assign'), $markerlist);
         $mform->addHelpButton('allocatedmarker', 'allocatedmarker', 'assign');
         $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_READYFORREVIEW);
         $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_INREVIEW);
         $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_READYFORRELEASE);
         $mform->disabledIf('allocatedmarker', 'workflowstate', 'eq', ASSIGN_MARKING_WORKFLOW_STATE_RELEASED);
     }
     $mform->addElement('static', 'currentgrade', get_string('currentgrade', 'assign'), $gradestring);
     if (count($useridlist) > 1) {
         $strparams = array('current' => $rownum + 1, 'total' => count($useridlist));
         $name = get_string('outof', 'assign', $strparams);
         $mform->addElement('static', 'gradingstudent', get_string('gradingstudent', 'assign'), $name);
     }
     // Let feedback plugins add elements to the grading form.
     $this->add_plugin_grade_elements($grade, $mform, $data, $userid);
     // Hidden params.
     $mform->addElement('hidden', 'id', $this->get_course_module()->id);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'rownum', $rownum);
     $mform->setType('rownum', PARAM_INT);
     $mform->setConstant('rownum', $rownum);
     $mform->addElement('hidden', 'useridlistid', $useridlistid);
     $mform->setType('useridlistid', PARAM_INT);
     $mform->addElement('hidden', 'attemptnumber', $attemptnumber);
     $mform->setType('attemptnumber', PARAM_INT);
     $mform->addElement('hidden', 'ajax', optional_param('ajax', 0, PARAM_INT));
     $mform->setType('ajax', PARAM_INT);
     if ($this->get_instance()->teamsubmission) {
         $mform->addElement('header', 'groupsubmissionsettings', get_string('groupsubmissionsettings', 'assign'));
         $mform->addElement('selectyesno', 'applytoall', get_string('applytoteam', 'assign'));
         $mform->setDefault('applytoall', 1);
     }
     // Do not show if we are editing a previous attempt.
     if ($attemptnumber == -1 && $this->get_instance()->attemptreopenmethod != ASSIGN_ATTEMPT_REOPEN_METHOD_NONE) {
         $mform->addElement('header', 'attemptsettings', get_string('attemptsettings', 'assign'));
         $attemptreopenmethod = get_string('attemptreopenmethod_' . $this->get_instance()->attemptreopenmethod, 'assign');
         $mform->addElement('static', 'attemptreopenmethod', get_string('attemptreopenmethod', 'assign'), $attemptreopenmethod);
         $attemptnumber = 0;
         if ($submission) {
             $attemptnumber = $submission->attemptnumber;
         }
         $maxattempts = $this->get_instance()->maxattempts;
         if ($maxattempts == ASSIGN_UNLIMITED_ATTEMPTS) {
             $maxattempts = get_string('unlimitedattempts', 'assign');
         }
         $mform->addelement('static', 'maxattemptslabel', get_string('maxattempts', 'assign'), $maxattempts);
         $mform->addelement('static', 'attemptnumberlabel', get_string('attemptnumber', 'assign'), $attemptnumber + 1);
         $ismanual = $this->get_instance()->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL;
         $issubmission = !empty($submission);
         $isunlimited = $this->get_instance()->maxattempts == ASSIGN_UNLIMITED_ATTEMPTS;
         $islessthanmaxattempts = $issubmission && $submission->attemptnumber < $this->get_instance()->maxattempts - 1;
         if ($ismanual && (!$issubmission || $isunlimited || $islessthanmaxattempts)) {
             $mform->addElement('selectyesno', 'addattempt', get_string('addattempt', 'assign'));
             $mform->setDefault('addattempt', 0);
         }
     }
     $mform->addElement('hidden', 'action', 'submitgrade');
     $mform->setType('action', PARAM_ALPHA);
     $buttonarray = array();
     $name = get_string('savechanges', 'assign');
     $buttonarray[] = $mform->createElement('submit', 'savegrade', $name);
     if (!$last) {
         $name = get_string('savenext', 'assign');
         $buttonarray[] = $mform->createElement('submit', 'saveandshownext', $name);
     }
     $buttonarray[] = $mform->createElement('cancel', 'cancelbutton', get_string('cancel'));
     $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
     $mform->closeHeaderBefore('buttonar');
     $buttonarray = array();
     if ($rownum > 0) {
         $name = get_string('previous', 'assign');
         $buttonarray[] = $mform->createElement('submit', 'nosaveandprevious', $name);
     }
     if (!$last) {
         $name = get_string('nosavebutnext', 'assign');
         $buttonarray[] = $mform->createElement('submit', 'nosaveandnext', $name);
     }
     if (!empty($buttonarray)) {
         $mform->addGroup($buttonarray, 'navar', '', array(' '), false);
     }
     // The grading form does not work well with shortforms.
     $mform->setDisableShortforms();
 }
Beispiel #15
0
    /**
     * Returns a list of teachers that should be grading given submission
     *
     * @param object $user
     * @return array
     */
    function get_graders($user) {
        //potential graders
        $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);

        $graders = array();
        if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) {   // Separate groups are being used
            if ($groups = groups_get_all_groups($this->course->id, $user->id)) {  // Try to find all groups
                foreach ($groups as $group) {
                    foreach ($potgraders as $t) {
                        if ($t->id == $user->id) {
                            continue; // do not send self
                        }
                        if (groups_is_member($group->id, $t->id)) {
                            $graders[$t->id] = $t;
                        }
                    }
                }
            } else {
                // user not in group, try to find graders without group
                foreach ($potgraders as $t) {
                    if ($t->id == $user->id) {
                        continue; // do not send self
                    }
                    if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
                        $graders[$t->id] = $t;
                    }
                }
            }
        } else {
            foreach ($potgraders as $t) {
                if ($t->id == $user->id) {
                    continue; // do not send self
                }
                $graders[$t->id] = $t;
            }
        }
        return $graders;
    }
Beispiel #16
0
/**
 * Who has this capability in this context?
 *
 * This can be a very expensive call - use sparingly and keep
 * the results if you are going to need them again soon.
 *
 * Note if $fields is empty this function attempts to get u.*
 * which can get rather large - and has a serious perf impact
 * on some DBs.
 *
 * @param context $context
 * @param string|array $capability - capability name(s)
 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
 * @param string $sort - the sort order. Default is lastaccess time.
 * @param mixed $limitfrom - number of records to skip (offset)
 * @param mixed $limitnum - number of records to fetch
 * @param string|array $groups - single group or array of groups - only return
 *               users who are in one of these group(s).
 * @param string|array $exceptions - list of users to exclude, comma separated or array
 * @param bool $doanything_ignored not used any more, admin accounts are never returned
 * @param bool $view_ignored - use get_enrolled_sql() instead
 * @param bool $useviewallgroups if $groups is set the return users who
 *               have capability both $capability and moodle/site:accessallgroups
 *               in this context, as well as users who have $capability and who are
 *               in $groups.
 * @return mixed
 */
function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '', $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false)
{
    global $CFG, $DB;
    $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
    $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
    $ctxids = trim($context->path, '/');
    $ctxids = str_replace('/', ',', $ctxids);
    // Context is the frontpage
    $iscoursepage = false;
    // coursepage other than fp
    $isfrontpage = false;
    if ($context->contextlevel == CONTEXT_COURSE) {
        if ($context->instanceid == SITEID) {
            $isfrontpage = true;
        } else {
            $iscoursepage = true;
        }
    }
    $isfrontpage = $isfrontpage || is_inside_frontpage($context);
    $caps = (array) $capability;
    // construct list of context paths bottom-->top
    list($contextids, $paths) = get_context_info_list($context);
    // we need to find out all roles that have these capabilities either in definition or in overrides
    $defs = array();
    list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
    list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
    $params = array_merge($params, $params2);
    $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path\n              FROM {role_capabilities} rc\n              JOIN {context} ctx on rc.contextid = ctx.id\n             WHERE rc.contextid {$incontexts} AND rc.capability {$incaps}";
    $rcs = $DB->get_records_sql($sql, $params);
    foreach ($rcs as $rc) {
        $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
    }
    // go through the permissions bottom-->top direction to evaluate the current permission,
    // first one wins (prohibit is an exception that always wins)
    $access = array();
    foreach ($caps as $cap) {
        foreach ($paths as $path) {
            if (empty($defs[$cap][$path])) {
                continue;
            }
            foreach ($defs[$cap][$path] as $roleid => $perm) {
                if ($perm == CAP_PROHIBIT) {
                    $access[$cap][$roleid] = CAP_PROHIBIT;
                    continue;
                }
                if (!isset($access[$cap][$roleid])) {
                    $access[$cap][$roleid] = (int) $perm;
                }
            }
        }
    }
    // make lists of roles that are needed and prohibited in this context
    $needed = array();
    // one of these is enough
    $prohibited = array();
    // must not have any of these
    foreach ($caps as $cap) {
        if (empty($access[$cap])) {
            continue;
        }
        foreach ($access[$cap] as $roleid => $perm) {
            if ($perm == CAP_PROHIBIT) {
                unset($needed[$cap][$roleid]);
                $prohibited[$cap][$roleid] = true;
            } else {
                if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
                    $needed[$cap][$roleid] = true;
                }
            }
        }
        if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
            // easy, nobody has the permission
            unset($needed[$cap]);
            unset($prohibited[$cap]);
        } else {
            if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
                // everybody is disqualified on the frontapge
                unset($needed[$cap]);
                unset($prohibited[$cap]);
            }
        }
        if (empty($prohibited[$cap])) {
            unset($prohibited[$cap]);
        }
    }
    if (empty($needed)) {
        // there can not be anybody if no roles match this request
        return array();
    }
    if (empty($prohibited)) {
        // we can compact the needed roles
        $n = array();
        foreach ($needed as $cap) {
            foreach ($cap as $roleid => $unused) {
                $n[$roleid] = true;
            }
        }
        $needed = array('any' => $n);
        unset($n);
    }
    /// ***** Set up default fields ******
    if (empty($fields)) {
        if ($iscoursepage) {
            $fields = 'u.*, ul.timeaccess AS lastaccess';
        } else {
            $fields = 'u.*';
        }
    } else {
        if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
            debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
        }
    }
    /// Set up default sort
    if (empty($sort)) {
        // default to course lastaccess or just lastaccess
        if ($iscoursepage) {
            $sort = 'ul.timeaccess';
        } else {
            $sort = 'u.lastaccess';
        }
    }
    // Prepare query clauses
    $wherecond = array();
    $params = array();
    $joins = array();
    // User lastaccess JOIN
    if (strpos($sort, 'ul.timeaccess') === false and strpos($fields, 'ul.timeaccess') === false) {
        // user_lastaccess is not required MDL-13810
    } else {
        if ($iscoursepage) {
            $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
        } else {
            throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
        }
    }
    /// We never return deleted users or guest account.
    $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
    $params['guestid'] = $CFG->siteguest;
    /// Groups
    if ($groups) {
        $groups = (array) $groups;
        list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
        $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid {$grouptest})";
        $params = array_merge($params, $grpparams);
        if ($useviewallgroups) {
            $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
            if (!empty($viewallgroupsusers)) {
                $wherecond[] = "({$grouptest} OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
            } else {
                $wherecond[] = "({$grouptest})";
            }
        } else {
            $wherecond[] = "({$grouptest})";
        }
    }
    /// User exceptions
    if (!empty($exceptions)) {
        $exceptions = (array) $exceptions;
        list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
        $params = array_merge($params, $exparams);
        $wherecond[] = "u.id {$exsql}";
    }
    // now add the needed and prohibited roles conditions as joins
    if (!empty($needed['any'])) {
        // simple case - there are no prohibits involved
        if (!empty($needed['any'][$defaultuserroleid]) or $isfrontpage and !empty($needed['any'][$defaultfrontpageroleid])) {
            // everybody
        } else {
            $joins[] = "JOIN (SELECT DISTINCT userid\n                                FROM {role_assignments}\n                               WHERE contextid IN ({$ctxids})\n                                     AND roleid IN (" . implode(',', array_keys($needed['any'])) . ")\n                             ) ra ON ra.userid = u.id";
        }
    } else {
        $unions = array();
        $everybody = false;
        foreach ($needed as $cap => $unused) {
            if (empty($prohibited[$cap])) {
                if (!empty($needed[$cap][$defaultuserroleid]) or $isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid])) {
                    $everybody = true;
                    break;
                } else {
                    $unions[] = "SELECT userid\n                                   FROM {role_assignments}\n                                  WHERE contextid IN ({$ctxids})\n                                        AND roleid IN (" . implode(',', array_keys($needed[$cap])) . ")";
                }
            } else {
                if (!empty($prohibited[$cap][$defaultuserroleid]) or $isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
                    // nobody can have this cap because it is prevented in default roles
                    continue;
                } else {
                    if (!empty($needed[$cap][$defaultuserroleid]) or $isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid])) {
                        // everybody except the prohibitted - hiding does not matter
                        $unions[] = "SELECT id AS userid\n                                   FROM {user}\n                                  WHERE id NOT IN (SELECT userid\n                                                     FROM {role_assignments}\n                                                    WHERE contextid IN ({$ctxids})\n                                                          AND roleid IN (" . implode(',', array_keys($prohibited[$cap])) . "))";
                    } else {
                        $unions[] = "SELECT userid\n                                   FROM {role_assignments}\n                                  WHERE contextid IN ({$ctxids})\n                                        AND roleid IN (" . implode(',', array_keys($needed[$cap])) . ")\n                                        AND roleid NOT IN (" . implode(',', array_keys($prohibited[$cap])) . ")";
                    }
                }
            }
        }
        if (!$everybody) {
            if ($unions) {
                $joins[] = "JOIN (SELECT DISTINCT userid FROM ( " . implode(' UNION ', $unions) . " ) us) ra ON ra.userid = u.id";
            } else {
                // only prohibits found - nobody can be matched
                $wherecond[] = "1 = 2";
            }
        }
    }
    // Collect WHERE conditions and needed joins
    $where = implode(' AND ', $wherecond);
    if ($where !== '') {
        $where = 'WHERE ' . $where;
    }
    $joins = implode("\n", $joins);
    /// Ok, let's get the users!
    $sql = "SELECT {$fields}\n              FROM {user} u\n            {$joins}\n            {$where}\n          ORDER BY {$sort}";
    return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
}
Beispiel #17
0
 /**
  * Find our users who could be enrolled into the remote course
  *
  * Our users must have 'moodle/site:mnetlogintoremote' capability assigned.
  * Remote users, guests, deleted and not confirmed users are not returned.
  *
  * @param string $search
  * @return array
  */
 public function find_users($search)
 {
     global $CFG, $DB;
     $systemcontext = context_system::instance();
     $userids = get_users_by_capability($systemcontext, 'moodle/site:mnetlogintoremote', 'u.id');
     if (empty($userids)) {
         return array();
     }
     list($usql, $uparams) = $DB->get_in_or_equal(array_keys($userids), SQL_PARAMS_NAMED, 'uid');
     list($wherecondition, $params) = $this->search_sql($search, 'u');
     $params = array_merge($params, $uparams);
     $params['hostid'] = $this->hostid;
     $params['remotecourseid'] = $this->remotecourseid;
     $params['mnetlocalhostid'] = $CFG->mnet_localhost_id;
     $fields = "SELECT " . $this->required_fields_sql("u");
     $countfields = "SELECT COUNT(1)";
     $sql = "          FROM {user} u\n                         WHERE {$wherecondition}\n                               AND u.mnethostid = :mnetlocalhostid\n                               AND u.id {$usql}\n                               AND u.id NOT IN (SELECT e.userid\n                                                  FROM {mnetservice_enrol_enrolments} e\n                                                 WHERE (e.hostid = :hostid AND e.remotecourseid = :remotecourseid))";
     list($sort, $sortparams) = users_order_by_sql('u');
     $order = "    ORDER BY {$sort}";
     if (!$this->is_validating()) {
         $potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
         if ($potentialmemberscount > 100) {
             return $this->too_many_results($search, $potentialmemberscount);
         }
     }
     $availableusers = $DB->get_records_sql($fields . $sql . $order, array_merge($params, $sortparams));
     if (empty($availableusers)) {
         return array();
     }
     if ($search) {
         $groupname = get_string('enrolcandidatesmatching', 'enrol', $search);
     } else {
         $groupname = get_string('enrolcandidates', 'enrol');
     }
     return array($groupname => $availableusers);
 }
Beispiel #18
0
 /**
  * Prints the message telling you were to get the enrolment key
  * appropriate for the prevailing circumstances
  * A bit clunky because I didn't want to change the standard strings
  */
 function print_enrolmentkeyfrom($course)
 {
     global $CFG;
     global $USER;
     $context = get_context_instance(CONTEXT_SYSTEM);
     $guest = has_capability('moodle/legacy:guest', $context, $USER->id, false);
     // if a keyholder role is defined we list teachers in that role (if any exist)
     $contactslisted = false;
     $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
     if (!empty($CFG->enrol_manual_keyholderrole)) {
         if ($contacts = get_role_users($CFG->enrol_manual_keyholderrole, get_context_instance(CONTEXT_COURSE, $course->id), true, '', 'u.lastname ASC', $canseehidden)) {
             // guest user has a slightly different message
             if ($guest) {
                 print_string('enrolmentkeyfromguest', '', ':<br />');
             } else {
                 print_string('enrolmentkeyfrom', '', ':<br />');
             }
             foreach ($contacts as $contact) {
                 $contactname = "<a href=\"../user/view.php?id={$contact->id}&course=" . SITEID . "\">" . fullname($contact) . "</a>.";
                 echo "{$contactname}<br />";
             }
             $contactslisted = true;
         }
     }
     // if no keyholder role is defined OR nobody is in that role we do this the 'old' way
     // (show the first person with update rights)
     if (!$contactslisted) {
         if ($teachers = get_users_by_capability(get_context_instance(CONTEXT_COURSE, $course->id), 'moodle/course:update', 'u.*', 'u.id ASC', 0, 1, '', '', false, true)) {
             $teacher = array_shift($teachers);
         }
         if (!empty($teacher)) {
             $teachername = "<a href=\"../user/view.php?id={$teacher->id}&course=" . SITEID . "\">" . fullname($teacher) . "</a>.";
         } else {
             $teachername = strtolower(get_string('defaultcourseteacher'));
             //get_string('yourteacher', '', $course->teacher);
         }
         // guest user has a slightly different message
         if ($guest) {
             print_string('enrolmentkeyfromguest', '', $teachername);
         } else {
             print_string('enrolmentkeyfrom', '', $teachername);
         }
     }
 }
Beispiel #19
0
/**
 * Takes a bunch of information to format into an email and send
 * to the specified recipient.
 *
 * @param object $course the course
 * @param object $quiz the quiz
 * @param object $attempt this attempt just finished
 * @param object $context the quiz context
 * @param object $cm the coursemodule for this quiz
 *
 * @return int number of emails sent
 */
function quiz_send_notification_emails($course, $quiz, $attempt, $context, $cm)
{
    global $CFG, $USER;
    // we will count goods and bads for error logging
    $emailresult = array('good' => 0, 'block' => 0, 'fail' => 0);
    // do nothing if required objects not present
    if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
        debugging('quiz_send_notification_emails: Email(s) not sent due to program error.', DEBUG_DEVELOPER);
        return $emailresult['fail'];
    }
    // check for confirmation required
    $sendconfirm = false;
    $notifyexcludeusers = '';
    if (has_capability('mod/quiz:emailconfirmsubmission', $context, NULL, false)) {
        // exclude from notify emails later
        $notifyexcludeusers = $USER->id;
        // send the email
        $sendconfirm = true;
    }
    // check for notifications required
    $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.email, u.emailstop, u.lang, u.timezone, u.mailformat, u.maildisplay';
    $groups = groups_get_all_groups($course->id, $USER->id);
    if (is_array($groups) && count($groups) > 0) {
        $groups = array_keys($groups);
    } else {
        if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
            // If the user is not in a group, and the quiz is set to group mode,
            // then set $gropus to a non-existant id so that only users with
            // 'moodle/site:accessallgroups' get notified.
            $groups = -1;
        } else {
            $groups = '';
        }
    }
    $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission', $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
    // if something to send, then build $a
    if (!empty($userstonotify) or $sendconfirm) {
        $a = new stdClass();
        // course info
        $a->coursename = $course->fullname;
        $a->courseshortname = $course->shortname;
        // quiz info
        $a->quizname = $quiz->name;
        $a->quizreporturl = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id;
        $a->quizreportlink = '<a href="' . $a->quizreporturl . '">' . format_string($quiz->name) . ' report</a>';
        $a->quizreviewurl = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
        $a->quizreviewlink = '<a href="' . $a->quizreviewurl . '">' . format_string($quiz->name) . ' review</a>';
        $a->quizurl = $CFG->wwwroot . '/mod/quiz/view.php?q=' . $quiz->id;
        $a->quizlink = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
        // attempt info
        $a->submissiontime = userdate($attempt->timefinish);
        $a->timetaken = format_time($attempt->timefinish - $attempt->timestart);
        // student who sat the quiz info
        $a->studentidnumber = $USER->idnumber;
        $a->studentname = fullname($USER);
        $a->studentusername = $USER->username;
    }
    // send confirmation if required
    if ($sendconfirm) {
        // send the email and update stats
        switch (quiz_send_confirmation($a)) {
            case true:
                $emailresult['good']++;
                break;
            case false:
                $emailresult['fail']++;
                break;
            case 'emailstop':
                $emailresult['block']++;
                break;
        }
    }
    // send notifications if required
    if (!empty($userstonotify)) {
        // loop through recipients and send an email to each and update stats
        foreach ($userstonotify as $recipient) {
            switch (quiz_send_notification($recipient, $a)) {
                case true:
                    $emailresult['good']++;
                    break;
                case false:
                    $emailresult['fail']++;
                    break;
                case 'emailstop':
                    $emailresult['block']++;
                    break;
            }
        }
    }
    // log errors sending emails if any
    if (!empty($emailresult['fail'])) {
        debugging('quiz_send_notification_emails:: ' . $emailresult['fail'] . ' email(s) failed to be sent.', DEBUG_DEVELOPER);
    }
    if (!empty($emailresult['block'])) {
        debugging('quiz_send_notification_emails:: ' . $emailresult['block'] . ' email(s) were blocked by the user.', DEBUG_DEVELOPER);
    }
    // return the number of successfully sent emails
    return $emailresult['good'];
}
Beispiel #20
0
    /**
     * Prepare an individual workshop plan for the given user.
     *
     * @param workshop $workshop instance
     * @param int $userid whom the plan is prepared for
     */
    public function __construct(workshop $workshop, $userid) {
        global $DB;

        $this->workshop = $workshop;
        $this->userid   = $userid;

        //---------------------------------------------------------
        // * SETUP | submission | assessment | evaluation | closed
        //---------------------------------------------------------
        $phase = new stdclass();
        $phase->title = get_string('phasesetup', 'workshop');
        $phase->tasks = array();
        if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
            $task = new stdclass();
            $task->title = get_string('taskintro', 'workshop');
            $task->link = $workshop->updatemod_url();
            $task->completed = !(trim($workshop->intro) == '');
            $phase->tasks['intro'] = $task;
        }
        if (has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
            $task = new stdclass();
            $task->title = get_string('taskinstructauthors', 'workshop');
            $task->link = $workshop->updatemod_url();
            $task->completed = !(trim($workshop->instructauthors) == '');
            $phase->tasks['instructauthors'] = $task;
        }
        if (has_capability('mod/workshop:editdimensions', $workshop->context, $userid)) {
            $task = new stdclass();
            $task->title = get_string('editassessmentform', 'workshop');
            $task->link = $workshop->editform_url();
            if ($workshop->grading_strategy_instance()->form_ready()) {
                $task->completed = true;
            } elseif ($workshop->phase > workshop::PHASE_SETUP) {
                $task->completed = false;
            }
            $phase->tasks['editform'] = $task;
        }
        if ($workshop->useexamples and has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
            $task = new stdclass();
            $task->title = get_string('prepareexamples', 'workshop');
            if ($DB->count_records('workshop_submissions', array('example' => 1, 'workshopid' => $workshop->id)) > 0) {
                $task->completed = true;
            } elseif ($workshop->phase > workshop::PHASE_SETUP) {
                $task->completed = false;
            }
            $phase->tasks['prepareexamples'] = $task;
        }
        if (empty($phase->tasks) and $workshop->phase == workshop::PHASE_SETUP) {
            // if we are in the setup phase and there is no task (typical for students), let us
            // display some explanation what is going on
            $task = new stdclass();
            $task->title = get_string('undersetup', 'workshop');
            $task->completed = 'info';
            $phase->tasks['setupinfo'] = $task;
        }
        $this->phases[workshop::PHASE_SETUP] = $phase;

        //---------------------------------------------------------
        // setup | * SUBMISSION | assessment | evaluation | closed
        //---------------------------------------------------------
        $phase = new stdclass();
        $phase->title = get_string('phasesubmission', 'workshop');
        $phase->tasks = array();
        if (($workshop->usepeerassessment or $workshop->useselfassessment)
             and has_capability('moodle/course:manageactivities', $workshop->context, $userid)) {
            $task = new stdclass();
            $task->title = get_string('taskinstructreviewers', 'workshop');
            $task->link = $workshop->updatemod_url();
            if (trim($workshop->instructreviewers)) {
                $task->completed = true;
            } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
                $task->completed = false;
            }
            $phase->tasks['instructreviewers'] = $task;
        }
        if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_SUBMISSION
                and has_capability('mod/workshop:submit', $workshop->context, $userid, false)
                    and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
            $task = new stdclass();
            $task->title = get_string('exampleassesstask', 'workshop');
            $examples = $this->get_examples();
            $a = new stdclass();
            $a->expected = count($examples);
            $a->assessed = 0;
            foreach ($examples as $exampleid => $example) {
                if (!is_null($example->grade)) {
                    $a->assessed++;
                }
            }
            $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
            if ($a->assessed == $a->expected) {
                $task->completed = true;
            } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
                $task->completed = false;
            }
            $phase->tasks['examples'] = $task;
        }
        if (has_capability('mod/workshop:submit', $workshop->context, $userid, false)) {
            $task = new stdclass();
            $task->title = get_string('tasksubmit', 'workshop');
            $task->link = $workshop->submission_url();
            if ($DB->record_exists('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0, 'authorid'=>$userid))) {
                $task->completed = true;
            } elseif ($workshop->phase >= workshop::PHASE_ASSESSMENT) {
                $task->completed = false;
            } else {
                $task->completed = null;    // still has a chance to submit
            }
            $phase->tasks['submit'] = $task;
        }
        if (has_capability('mod/workshop:allocate', $workshop->context, $userid)) {
            $task = new stdclass();
            $task->title = get_string('allocate', 'workshop');
            $task->link = $workshop->allocation_url();
            $numofauthors = count(get_users_by_capability($workshop->context, 'mod/workshop:submit', 'u.id', '', '', '',
                    '', '', false, true));
            $numofsubmissions = $DB->count_records('workshop_submissions', array('workshopid'=>$workshop->id, 'example'=>0));
            $sql = 'SELECT COUNT(s.id) AS nonallocated
                      FROM {workshop_submissions} s
                 LEFT JOIN {workshop_assessments} a ON (a.submissionid=s.id)
                     WHERE s.workshopid = :workshopid AND s.example=0 AND a.submissionid IS NULL';
            $params['workshopid'] = $workshop->id;
            $numnonallocated = $DB->count_records_sql($sql, $params);
            if ($numofsubmissions == 0) {
                $task->completed = null;
            } elseif ($numnonallocated == 0) {
                $task->completed = true;
            } elseif ($workshop->phase > workshop::PHASE_SUBMISSION) {
                $task->completed = false;
            } else {
                $task->completed = null;    // still has a chance to allocate
            }
            $a = new stdclass();
            $a->expected    = $numofauthors;
            $a->submitted   = $numofsubmissions;
            $a->allocate    = $numnonallocated;
            $task->details  = get_string('allocatedetails', 'workshop', $a);
            unset($a);
            $phase->tasks['allocate'] = $task;

            if ($numofsubmissions < $numofauthors and $workshop->phase >= workshop::PHASE_SUBMISSION) {
                $task = new stdclass();
                $task->title = get_string('someuserswosubmission', 'workshop');
                $task->completed = 'info';
                $phase->tasks['allocateinfo'] = $task;
            }
        }
        if ($workshop->submissionstart) {
            $task = new stdclass();
            $task->title = get_string('submissionstartdatetime', 'workshop', workshop::timestamp_formats($workshop->submissionstart));
            $task->completed = 'info';
            $phase->tasks['submissionstartdatetime'] = $task;
        }
        if ($workshop->submissionend) {
            $task = new stdclass();
            $task->title = get_string('submissionenddatetime', 'workshop', workshop::timestamp_formats($workshop->submissionend));
            $task->completed = 'info';
            $phase->tasks['submissionenddatetime'] = $task;
        }
        if (($workshop->submissionstart < time()) and $workshop->latesubmissions) {
            $task = new stdclass();
            $task->title = get_string('latesubmissionsallowed', 'workshop');
            $task->completed = 'info';
            $phase->tasks['latesubmissionsallowed'] = $task;
        }
        $this->phases[workshop::PHASE_SUBMISSION] = $phase;

        //---------------------------------------------------------
        // setup | submission | * ASSESSMENT | evaluation | closed
        //---------------------------------------------------------
        $phase = new stdclass();
        $phase->title = get_string('phaseassessment', 'workshop');
        $phase->tasks = array();
        $phase->isreviewer = has_capability('mod/workshop:peerassess', $workshop->context, $userid);
        if ($workshop->useexamples and $workshop->examplesmode == workshop::EXAMPLES_BEFORE_ASSESSMENT
                and $phase->isreviewer and !has_capability('mod/workshop:manageexamples', $workshop->context, $userid)) {
            $task = new stdclass();
            $task->title = get_string('exampleassesstask', 'workshop');
            $examples = $workshop->get_examples_for_reviewer($userid);
            $a = new stdclass();
            $a->expected = count($examples);
            $a->assessed = 0;
            foreach ($examples as $exampleid => $example) {
                if (!is_null($example->grade)) {
                    $a->assessed++;
                }
            }
            $task->details = get_string('exampleassesstaskdetails', 'workshop', $a);
            if ($a->assessed == $a->expected) {
                $task->completed = true;
            } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
                $task->completed = false;
            }
            $phase->tasks['examples'] = $task;
        }
        if (empty($phase->tasks['examples']) or !empty($phase->tasks['examples']->completed)) {
            $phase->assessments = $workshop->get_assessments_by_reviewer($userid);
            $numofpeers     = 0;    // number of allocated peer-assessments
            $numofpeerstodo = 0;    // number of peer-assessments to do
            $numofself      = 0;    // number of allocated self-assessments - should be 0 or 1
            $numofselftodo  = 0;    // number of self-assessments to do - should be 0 or 1
            foreach ($phase->assessments as $a) {
                if ($a->authorid == $userid) {
                    $numofself++;
                    if (is_null($a->grade)) {
                        $numofselftodo++;
                    }
                } else {
                    $numofpeers++;
                    if (is_null($a->grade)) {
                        $numofpeerstodo++;
                    }
                }
            }
            unset($a);
            if ($workshop->usepeerassessment and $numofpeers) {
                $task = new stdclass();
                if ($numofpeerstodo == 0) {
                    $task->completed = true;
                } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
                    $task->completed = false;
                }
                $a = new stdclass();
                $a->total = $numofpeers;
                $a->todo  = $numofpeerstodo;
                $task->title = get_string('taskassesspeers', 'workshop');
                $task->details = get_string('taskassesspeersdetails', 'workshop', $a);
                unset($a);
                $phase->tasks['assesspeers'] = $task;
            }
            if ($workshop->useselfassessment and $numofself) {
                $task = new stdclass();
                if ($numofselftodo == 0) {
                    $task->completed = true;
                } elseif ($workshop->phase > workshop::PHASE_ASSESSMENT) {
                    $task->completed = false;
                }
                $task->title = get_string('taskassessself', 'workshop');
                $phase->tasks['assessself'] = $task;
            }
        }
        if ($workshop->assessmentstart) {
            $task = new stdclass();
            $task->title = get_string('assessmentstartdatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentstart));
            $task->completed = 'info';
            $phase->tasks['assessmentstartdatetime'] = $task;
        }
        if ($workshop->assessmentend) {
            $task = new stdclass();
            $task->title = get_string('assessmentenddatetime', 'workshop', workshop::timestamp_formats($workshop->assessmentend));
            $task->completed = 'info';
            $phase->tasks['assessmentenddatetime'] = $task;
        }
        $this->phases[workshop::PHASE_ASSESSMENT] = $phase;

        //---------------------------------------------------------
        // setup | submission | assessment | * EVALUATION | closed
        //---------------------------------------------------------
        $phase = new stdclass();
        $phase->title = get_string('phaseevaluation', 'workshop');
        $phase->tasks = array();
        if (has_capability('mod/workshop:overridegrades', $workshop->context)) {
            $expected = count($workshop->get_potential_authors(false));
            $calculated = $DB->count_records_select('workshop_submissions',
                    'workshopid = ? AND (grade IS NOT NULL OR gradeover IS NOT NULL)', array($workshop->id));
            $task = new stdclass();
            $task->title = get_string('calculatesubmissiongrades', 'workshop');
            $a = new stdclass();
            $a->expected    = $expected;
            $a->calculated  = $calculated;
            $task->details  = get_string('calculatesubmissiongradesdetails', 'workshop', $a);
            if ($calculated >= $expected) {
                $task->completed = true;
            } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
                $task->completed = false;
            }
            $phase->tasks['calculatesubmissiongrade'] = $task;

            $expected = count($workshop->get_potential_reviewers(false));
            $calculated = $DB->count_records_select('workshop_aggregations',
                    'workshopid = ? AND gradinggrade IS NOT NULL', array($workshop->id));
            $task = new stdclass();
            $task->title = get_string('calculategradinggrades', 'workshop');
            $a = new stdclass();
            $a->expected    = $expected;
            $a->calculated  = $calculated;
            $task->details  = get_string('calculategradinggradesdetails', 'workshop', $a);
            if ($calculated >= $expected) {
                $task->completed = true;
            } elseif ($workshop->phase > workshop::PHASE_EVALUATION) {
                $task->completed = false;
            }
            $phase->tasks['calculategradinggrade'] = $task;

        } elseif ($workshop->phase == workshop::PHASE_EVALUATION) {
            $task = new stdclass();
            $task->title = get_string('evaluategradeswait', 'workshop');
            $task->completed = 'info';
            $phase->tasks['evaluateinfo'] = $task;
        }
        $this->phases[workshop::PHASE_EVALUATION] = $phase;

        //---------------------------------------------------------
        // setup | submission | assessment | evaluation | * CLOSED
        //---------------------------------------------------------
        $phase = new stdclass();
        $phase->title = get_string('phaseclosed', 'workshop');
        $phase->tasks = array();
        $this->phases[workshop::PHASE_CLOSED] = $phase;

        // Polish data, set default values if not done explicitly
        foreach ($this->phases as $phasecode => $phase) {
            $phase->title       = isset($phase->title)      ? $phase->title     : '';
            $phase->tasks       = isset($phase->tasks)      ? $phase->tasks     : array();
            if ($phasecode == $workshop->phase) {
                $phase->active = true;
            } else {
                $phase->active = false;
            }
            if (!isset($phase->actions)) {
                $phase->actions = array();
            }

            foreach ($phase->tasks as $taskcode => $task) {
                $task->title        = isset($task->title)       ? $task->title      : '';
                $task->link         = isset($task->link)        ? $task->link       : null;
                $task->details      = isset($task->details)     ? $task->details    : '';
                $task->completed    = isset($task->completed)   ? $task->completed  : null;
            }
        }

        // Add phase switching actions
        if (has_capability('mod/workshop:switchphase', $workshop->context, $userid)) {
            foreach ($this->phases as $phasecode => $phase) {
                if (! $phase->active) {
                    $action = new stdclass();
                    $action->type = 'switchphase';
                    $action->url  = $workshop->switchphase_url($phasecode);
                    $phase->actions[] = $action;
                }
            }
        }
    }
Beispiel #21
0
 function definition()
 {
     global $USER, $CFG, $DB;
     $courseconfig = get_config('moodlecourse');
     $mform =& $this->_form;
     $course = $this->_customdata['course'];
     $category = $this->_customdata['category'];
     $systemcontext = get_context_instance(CONTEXT_SYSTEM);
     $categorycontext = get_context_instance(CONTEXT_COURSECAT, $category->id);
     $disable_meta = false;
     // basic meta course state protection; server-side security checks not needed
     if (!empty($course)) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
         $context = $coursecontext;
         if (course_in_meta($course)) {
             $disable_meta = get_string('metaalreadyinmeta');
         } else {
             if ($course->metacourse) {
                 if ($DB->count_records('course_meta', array('parent_course' => $course->id)) > 0) {
                     $disable_meta = get_string('metaalreadyhascourses');
                 }
             } else {
                 // if users already enrolled directly into coures, do not allow switching to meta,
                 // users with metacourse manage permission are exception
                 // please note that we do not need exact results - anything unexpected here prevents metacourse
                 $managers = get_users_by_capability($coursecontext, 'moodle/course:managemetacourse', 'u.id');
                 $enrolroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $coursecontext);
                 if ($users = get_role_users(array_keys($enrolroles), $coursecontext, false, 'u.id', 'u.id ASC')) {
                     foreach ($users as $user) {
                         if (!isset($managers[$user->id])) {
                             $disable_meta = get_string('metaalreadyhasenrolments');
                             break;
                         }
                     }
                 }
                 unset($managers);
                 unset($users);
                 unset($enrolroles);
             }
         }
     } else {
         $coursecontext = null;
         $context = $categorycontext;
     }
     /// form definition with new course defaults
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     // Must have create course capability in both categories in order to move course
     if (has_capability('moodle/course:create', $categorycontext)) {
         $displaylist = array();
         $parentlist = array();
         make_categories_list($displaylist, $parentlist, 'moodle/course:create');
         $mform->addElement('select', 'category', get_string('category'), $displaylist);
     } else {
         $mform->addElement('hidden', 'category', null);
     }
     $mform->setHelpButton('category', array('coursecategory', get_string('category')));
     $mform->setDefault('category', $category->id);
     $mform->setType('category', PARAM_INT);
     $fullname = get_string('defaultcoursefullname');
     $shortname = get_string('defaultcourseshortname');
     while ($DB->record_exists('course', array('fullname' => $fullname)) or $DB->record_exists('course', array('fullname' => $fullname))) {
         $fullname++;
         $shortname++;
     }
     $mform->addElement('text', 'fullname', get_string('fullnamecourse'), 'maxlength="254" size="50"');
     $mform->setHelpButton('fullname', array('coursefullname', get_string('fullnamecourse')), true);
     $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client');
     $mform->setType('fullname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changefullname', $coursecontext)) {
         $mform->hardFreeze('fullname');
         $mform->setConstant('fullname', $course->fullname);
     }
     $mform->setDefault('fullname', $fullname);
     $mform->addElement('text', 'shortname', get_string('shortnamecourse'), 'maxlength="100" size="20"');
     $mform->setHelpButton('shortname', array('courseshortname', get_string('shortnamecourse')), true);
     $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client');
     $mform->setType('shortname', PARAM_MULTILANG);
     if ($course and !has_capability('moodle/course:changeshortname', $coursecontext)) {
         $mform->hardFreeze('shortname');
         $mform->setConstant('shortname', $course->shortname);
     }
     $mform->setDefault('shortname', $shortname);
     $mform->addElement('text', 'idnumber', get_string('idnumbercourse'), 'maxlength="100"  size="10"');
     $mform->setHelpButton('idnumber', array('courseidnumber', get_string('idnumbercourse')), true);
     $mform->setType('idnumber', PARAM_RAW);
     if ($course and !has_capability('moodle/course:changeidnumber', $coursecontext)) {
         $mform->hardFreeze('idnumber');
         $mform->setConstants('idnumber', $course->idnumber);
     }
     $mform->addElement('htmleditor', 'summary', get_string('summary'), array('rows' => '10', 'cols' => '65'));
     $mform->setHelpButton('summary', array('text2', get_string('helptext')), true);
     $mform->setType('summary', PARAM_RAW);
     $courseformats = get_list_of_plugins('course/format');
     $formcourseformats = array();
     foreach ($courseformats as $courseformat) {
         $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}", "format_{$courseformat}");
         if ($formcourseformats["{$courseformat}"] == "[[format{$courseformat}]]") {
             $formcourseformats["{$courseformat}"] = get_string("format{$courseformat}");
         }
     }
     $mform->addElement('select', 'format', get_string('format'), $formcourseformats);
     $mform->setHelpButton('format', array('courseformats', get_string('courseformats')), true);
     $mform->setDefault('format', $courseconfig->format);
     for ($i = 1; $i <= 52; $i++) {
         $sectionmenu[$i] = "{$i}";
     }
     $mform->addElement('select', 'numsections', get_string('numberweeks'), $sectionmenu);
     $mform->setDefault('numsections', $courseconfig->numsections);
     $mform->addElement('date_selector', 'startdate', get_string('startdate'));
     $mform->setHelpButton('startdate', array('coursestartdate', get_string('startdate')), true);
     $mform->setDefault('startdate', time() + 3600 * 24);
     $choices = array();
     $choices['0'] = get_string('hiddensectionscollapsed');
     $choices['1'] = get_string('hiddensectionsinvisible');
     $mform->addElement('select', 'hiddensections', get_string('hiddensections'), $choices);
     $mform->setHelpButton('hiddensections', array('coursehiddensections', get_string('hiddensections')), true);
     $mform->setDefault('hiddensections', $courseconfig->hiddensections);
     $options = range(0, 10);
     $mform->addElement('select', 'newsitems', get_string('newsitemsnumber'), $options);
     $mform->setHelpButton('newsitems', array('coursenewsitems', get_string('newsitemsnumber')), true);
     $mform->setDefault('newsitems', $courseconfig->newsitems);
     $mform->addElement('selectyesno', 'showgrades', get_string('showgrades'));
     $mform->setHelpButton('showgrades', array('coursegrades', get_string('grades')), true);
     $mform->setDefault('showgrades', $courseconfig->showgrades);
     $mform->addElement('selectyesno', 'showreports', get_string('showreports'));
     $mform->setHelpButton('showreports', array('coursereports', get_string('activityreport')), true);
     $mform->setDefault('showreports', $courseconfig->showreports);
     $choices = get_max_upload_sizes($CFG->maxbytes);
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->setHelpButton('maxbytes', array('courseuploadsize', get_string('maximumupload')), true);
     $mform->setDefault('maxbytes', $courseconfig->maxbytes);
     if (!empty($CFG->allowcoursethemes)) {
         $themes = array();
         $themes[''] = get_string('forceno');
         $themes += get_list_of_themes();
         $mform->addElement('select', 'theme', get_string('forcetheme'), $themes);
     }
     $meta = array();
     $meta[0] = get_string('no');
     $meta[1] = get_string('yes');
     if ($disable_meta === false) {
         $mform->addElement('select', 'metacourse', get_string('managemeta'), $meta);
         $mform->setHelpButton('metacourse', array('metacourse', get_string('metacourse')), true);
         $mform->setDefault('metacourse', $courseconfig->metacourse);
     } else {
         // no metacourse element - we do not want to change it anyway!
         $mform->addElement('static', 'nometacourse', get_string('managemeta'), (empty($course->metacourse) ? $meta[0] : $meta[1]) . " - {$disable_meta} ");
         $mform->setHelpButton('nometacourse', array('metacourse', get_string('metacourse')), true);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'enrolhdr', get_string('enrolments'));
     $choices = array();
     $modules = explode(',', $CFG->enrol_plugins_enabled);
     foreach ($modules as $module) {
         $name = get_string('enrolname', "enrol_{$module}");
         $plugin = enrolment_factory::factory($module);
         if (method_exists($plugin, 'print_entry')) {
             $choices[$name] = $module;
         }
     }
     asort($choices);
     $choices = array_flip($choices);
     $choices = array_merge(array('' => get_string('sitedefault') . ' (' . get_string('enrolname', "enrol_{$CFG->enrol}") . ')'), $choices);
     $mform->addElement('select', 'enrol', get_string('enrolmentplugins'), $choices);
     $mform->setHelpButton('enrol', array('courseenrolmentplugins', get_string('enrolmentplugins')), true);
     $mform->setDefault('enrol', $courseconfig->enrol);
     $roles = get_assignable_roles($context);
     if (!empty($course)) {
         // add current default role, so that it is selectable even when user can not assign it
         if ($current_role = $DB->get_record('role', array('id' => $course->defaultrole))) {
             $roles[$current_role->id] = strip_tags(format_string($current_role->name, true));
         }
     }
     $choices = array();
     if ($sitedefaultrole = $DB->get_record('role', array('id' => $CFG->defaultcourseroleid))) {
         $choices[0] = get_string('sitedefault') . ' (' . $sitedefaultrole->name . ')';
     } else {
         $choices[0] = get_string('sitedefault');
     }
     $choices = $choices + $roles;
     // fix for MDL-9197
     foreach ($choices as $choiceid => $choice) {
         $choices[$choiceid] = format_string($choice);
     }
     $mform->addElement('select', 'defaultrole', get_string('defaultrole', 'role'), $choices);
     $mform->setDefault('defaultrole', 0);
     $radio = array();
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('no'), 0);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('yes'), 1);
     $radio[] =& MoodleQuickForm::createElement('radio', 'enrollable', null, get_string('enroldate'), 2);
     $mform->addGroup($radio, 'enrollable', get_string('enrollable'), ' ', false);
     $mform->setHelpButton('enrollable', array('courseenrollable2', get_string('enrollable')), true);
     $mform->setDefault('enrollable', $courseconfig->enrollable);
     $mform->addElement('date_selector', 'enrolstartdate', get_string('enrolstartdate'), array('optional' => true));
     $mform->setDefault('enrolstartdate', 0);
     $mform->disabledIf('enrolstartdate', 'enrollable', 'neq', 2);
     $mform->addElement('date_selector', 'enrolenddate', get_string('enrolenddate'), array('optional' => true));
     $mform->setDefault('enrolenddate', 0);
     $mform->disabledIf('enrolenddate', 'enrollable', 'neq', 2);
     $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod'), array('optional' => true, 'defaultunit' => 86400));
     $mform->setDefault('enrolperiod', $courseconfig->enrolperiod);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'expirynotifyhdr', get_string('expirynotify'));
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'expirynotify', get_string('notify'), $choices);
     $mform->setHelpButton('expirynotify', array('expirynotify', get_string('expirynotify')), true);
     $mform->setDefault('expirynotify', $courseconfig->expirynotify);
     $mform->addElement('select', 'notifystudents', get_string('expirynotifystudents'), $choices);
     $mform->setHelpButton('notifystudents', array('expirynotifystudents', get_string('expirynotifystudents')), true);
     $mform->setDefault('notifystudents', $courseconfig->notifystudents);
     $thresholdmenu = array();
     for ($i = 1; $i <= 30; $i++) {
         $seconds = $i * 86400;
         $thresholdmenu[$seconds] = get_string('numdays', '', $i);
     }
     $mform->addElement('select', 'expirythreshold', get_string('expirythreshold'), $thresholdmenu);
     $mform->setHelpButton('expirythreshold', array('expirythreshold', get_string('expirythreshold')), true);
     $mform->setDefault('expirythreshold', $courseconfig->expirythreshold);
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('groups', 'group'));
     $choices = array();
     $choices[NOGROUPS] = get_string('groupsnone', 'group');
     $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
     $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
     $mform->addElement('select', 'groupmode', get_string('groupmode'), $choices);
     $mform->setHelpButton('groupmode', array('groupmode', get_string('groupmode')), true);
     $mform->setDefault('groupmode', $courseconfig->groupmode);
     $choices = array();
     $choices['0'] = get_string('no');
     $choices['1'] = get_string('yes');
     $mform->addElement('select', 'groupmodeforce', get_string('force'), $choices);
     $mform->setHelpButton('groupmodeforce', array('groupmodeforce', get_string('groupmodeforce')), true);
     $mform->setDefault('groupmodeforce', $courseconfig->groupmodeforce);
     if (!empty($CFG->enablegroupings)) {
         //default groupings selector
         $options = array();
         $options[0] = get_string('none');
         $mform->addElement('select', 'defaultgroupingid', get_string('defaultgrouping', 'group'), $options);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('availability'));
     $choices = array();
     $choices['0'] = get_string('courseavailablenot');
     $choices['1'] = get_string('courseavailable');
     $mform->addElement('select', 'visible', get_string('availability'), $choices);
     $mform->setHelpButton('visible', array('courseavailability', get_string('availability')), true);
     $mform->setDefault('visible', $courseconfig->visible);
     if ($course and !has_capability('moodle/course:visibility', $coursecontext)) {
         $mform->hardFreeze('visible');
         $mform->setConstant('visible', $course->visible);
     }
     $mform->addElement('passwordunmask', 'enrolpassword', get_string('enrolmentkey'), 'size="25"');
     $mform->setHelpButton('enrolpassword', array('enrolmentkey', get_string('enrolmentkey')), true);
     $mform->setDefault('enrolpassword', '');
     $mform->setDefault('enrolpassword', $courseconfig->enrolpassword);
     $mform->setType('enrolpassword', PARAM_RAW);
     if (empty($course) or $course->password !== '' and $course->id != SITEID) {
         // do not require password in existing courses that do not have password yet - backwards compatibility ;-)
         if (!empty($CFG->enrol_manual_requirekey)) {
             $mform->addRule('enrolpassword', get_string('required'), 'required', null, 'client');
         }
     }
     $choices = array();
     $choices['0'] = get_string('guestsno');
     $choices['1'] = get_string('guestsyes');
     $choices['2'] = get_string('guestskey');
     $mform->addElement('select', 'guest', get_string('opentoguests'), $choices);
     $mform->setHelpButton('guest', array('guestaccess', get_string('opentoguests')), true);
     $mform->setDefault('guest', $courseconfig->guest);
     // If we are creating a course, its enrol method isn't yet chosen, BUT the site has a default enrol method which we can use here
     $enrol_object = $CFG;
     if (!empty($course)) {
         $enrol_object = $course;
     }
     // If the print_entry method exists and the course enrol method isn't manual (both set or inherited from site), show cost
     if (method_exists(enrolment_factory::factory($enrol_object->enrol), 'print_entry') && !($enrol_object->enrol == 'manual' || empty($enrol_object->enrol) && $CFG->enrol == 'manual')) {
         $costgroup = array();
         $currencies = get_list_of_currencies();
         $costgroup[] =& MoodleQuickForm::createElement('text', 'cost', '', 'maxlength="6" size="6"');
         $costgroup[] =& MoodleQuickForm::createElement('select', 'currency', '', $currencies);
         $mform->addGroup($costgroup, 'costgrp', get_string('cost'), '&nbsp;', false);
         //defining a rule for a form element within a group :
         $costgrprules = array();
         //set the message to null to tell Moodle to use a default message
         //available for most rules, fetched from language pack (err_{rulename}).
         $costgrprules['cost'][] = array(null, 'numeric', null, 'client');
         $mform->addGroupRule('costgrp', $costgrprules);
         $mform->setHelpButton('costgrp', array('cost', get_string('cost')), true);
         $mform->setDefault('cost', '');
         $mform->setDefault('currency', empty($CFG->enrol_currency) ? 'USD' : $CFG->enrol_currency);
     }
     //--------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('language'));
     $languages = array();
     $languages[''] = get_string('forceno');
     $languages += get_list_of_languages();
     $mform->addElement('select', 'lang', get_string('forcelanguage'), $languages);
     $mform->setDefault('lang', $courseconfig->lang);
     //--------------------------------------------------------------------------------
     require_once $CFG->libdir . '/completionlib.php';
     if (completion_info::is_enabled_for_site()) {
         $mform->addElement('header', '', get_string('progress', 'completion'));
         $mform->addElement('select', 'enablecompletion', get_string('completion', 'completion'), array(0 => get_string('completiondisabled', 'completion'), 1 => get_string('completionenabled', 'completion')));
         $mform->setDefault('enablecompletion', $courseconfig->enablecompletion);
     } else {
         $mform->addElement('hidden', 'enablecompletion');
         $mform->setDefault('enablecompletion', 0);
     }
     //--------------------------------------------------------------------------------
     if (has_capability('moodle/site:config', $systemcontext) && (!empty($course->requested) && $CFG->restrictmodulesfor == 'requested' || $CFG->restrictmodulesfor == 'all')) {
         $mform->addElement('header', '', get_string('restrictmodules'));
         $options = array();
         $options['0'] = get_string('no');
         $options['1'] = get_string('yes');
         $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
         $mods = array(0 => get_string('allownone'));
         $mods += $DB->get_records_menu('modules', array(), 'name', 'id, name');
         $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple' => 'multiple', 'size' => '10'));
         $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
     } else {
         $mform->addElement('hidden', 'restrictmodules', null);
     }
     if ($CFG->restrictmodulesfor == 'all') {
         $mform->setDefault('allowedmods', explode(',', $CFG->defaultallowedmodules));
         if (!empty($CFG->restrictbydefault)) {
             $mform->setDefault('restrictmodules', 1);
         }
     }
     $mform->setType('restrictmodules', PARAM_INT);
     /// customizable role names in this course
     //--------------------------------------------------------------------------------
     $mform->addElement('header', 'rolerenaming', get_string('rolerenaming'));
     $mform->setHelpButton('rolerenaming', array('rolerenaming', get_string('rolerenaming')), true);
     if ($roles = get_all_roles()) {
         if ($coursecontext) {
             $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS_RAW);
         }
         $assignableroles = get_roles_for_contextlevels(CONTEXT_COURSE);
         foreach ($roles as $role) {
             $mform->addElement('text', 'role_' . $role->id, get_string('yourwordforx', '', $role->name));
             if (isset($role->localname)) {
                 $mform->setDefault('role_' . $role->id, $role->localname);
             }
             $mform->setType('role_' . $role->id, PARAM_TEXT);
             if (!in_array($role->id, $assignableroles)) {
                 $mform->setAdvanced('role_' . $role->id);
             }
         }
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons();
     //--------------------------------------------------------------------------------
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
 }
 /**
  * Returns submissions by part (and unsubmitted users if appropriate)
  *
  * @global type $DB
  * @global type $USER
  * @param object $cm course module object
  * @param int $partid specific part id, includes all if 0
  * @param int $userid specific user id, includes all if 0
  * @param int $submissionsonly flag to include/remove non submitted students from results
  * @return array of submissions by part
  */
 public function get_submissions($cm, $partid = 0, $userid = 0, $submissionsonly = 0)
 {
     global $DB, $USER;
     // If no part id is specified then get them all.
     $sql = " turnitintooltwoid = ? ";
     $sqlparams = array($this->id);
     if ($partid == 0) {
         $parts = $this->get_parts();
     } else {
         $part = $this->get_part_details($partid);
         $parts[$partid] = $part;
         $sql .= " AND submission_part = ? ";
         $sqlparams[] = $partid;
     }
     $context = context_module::instance($cm->id);
     $istutor = has_capability('mod/turnitintooltwo:grade', $context);
     // If logged in as instructor then get for all users.
     if ($istutor && $userid == 0) {
         $users = get_users_by_capability($context, 'mod/turnitintooltwo:submit', 'u.id, u.firstname, u.lastname', '', '', '', groups_get_activity_group($cm), '');
         $users = !$users ? array() : $users;
     } else {
         if ($istutor) {
             $user = $DB->get_record('user', array('id' => $userid));
             $users = array($userid => $user);
             $sql .= " AND userid = ? ";
             $sqlparams[] = $userid;
         } else {
             $users = array($USER->id => $USER);
             $sql .= " AND userid = ? ";
             $sqlparams[] = $USER->id;
         }
     }
     // Populate the submissions array to show all users for all parts.
     $submissions = array();
     foreach ($parts as $part) {
         $submissions[$part->id] = array();
         foreach ($users as $user) {
             $emptysubmission = new stdClass();
             $emptysubmission->userid = $user->id;
             $emptysubmission->firstname = $user->firstname;
             $emptysubmission->lastname = $user->lastname;
             $emptysubmission->submission_unanon = 0;
             $emptysubmission->nmoodle = 0;
             if ($submissionsonly == 0) {
                 $submissions[$part->id][$user->id] = $emptysubmission;
             }
         }
     }
     // Get submissions that were made where a moodle userid is known.
     // Contains moodle users both enrolled or not enrolled.
     if ($submissionsdata = $DB->get_records_select("turnitintooltwo_submissions", " userid != 0 AND " . $sql, $sqlparams)) {
         foreach ($submissionsdata as $submission) {
             $user = new turnitintooltwo_user($submission->userid, 'Learner', false);
             $submission->firstname = $user->firstname;
             $submission->lastname = $user->lastname;
             $submission->tii_user_id = $user->tii_user_id;
             $submission->nmoodle = 0;
             if (isset($users[$user->id])) {
                 // User is a moodle user ie in array from moodle user call above.
                 $submissions[$submission->submission_part][$user->id] = $submission;
             } else {
                 if (groups_get_activity_group($cm) == 0) {
                     // User is not a moodle user ie not in array from moodle user call above and group list is set to all users.
                     $submission->nmoodle = 1;
                     $submissions[$submission->submission_part][$user->id] = $submission;
                 }
             }
         }
     }
     // Now get submissions that were made by a non moodle students.
     // These are unknown to moodle possibly non-enrolled on turnitin.
     // Possibly real but not yet linked Turnitin users. If group list is set do not get these non group users.
     if ($submissionsdata = $DB->get_records_select("turnitintooltwo_submissions", " userid = 0 AND " . $sql, $sqlparams) and groups_get_activity_group($cm) == 0) {
         foreach ($submissionsdata as $submission) {
             $submission->nmoodle = 1;
             $submission->userid = $submission->submission_nmuserid;
             $submission->firstname = $submission->submission_nmfirstname;
             $submission->lastname = $submission->submission_nmlastname;
             $submissions[$submission->submission_part][$submission->userid] = $submission;
         }
     }
     return $submissions;
 }
 /**
  * list current marker
  *
  * @param stdClass $row - The row of data
  * @return id the user->id of the marker.
  */
 public function col_allocatedmarker(stdClass $row)
 {
     static $markers = null;
     static $markerlist = array();
     if ($markers === null) {
         list($sort, $params) = users_order_by_sql();
         $markers = get_users_by_capability($this->assignment->get_context(), 'mod/assign:grade', '', $sort);
         $markerlist[0] = get_string('choosemarker', 'assign');
         foreach ($markers as $marker) {
             $markerlist[$marker->id] = fullname($marker);
         }
     }
     if (empty($markerlist)) {
         // TODO: add some form of notification here that no markers are available.
         return '';
     }
     if ($this->is_downloading()) {
         if (isset($markers[$row->allocatedmarker])) {
             return fullname($markers[$row->allocatedmarker]);
         } else {
             return '';
         }
     }
     if ($this->quickgrading && has_capability('mod/assign:manageallocations', $this->assignment->get_context()) && (empty($row->workflowstate) || $row->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_INMARKING || $row->workflowstate == ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED)) {
         $name = 'quickgrade_' . $row->id . '_allocatedmarker';
         return html_writer::select($markerlist, $name, $row->allocatedmarker, false);
     } else {
         if (!empty($row->allocatedmarker)) {
             $output = '';
             if ($this->quickgrading) {
                 // Add hidden field for quickgrading page.
                 $name = 'quickgrade_' . $row->id . '_allocatedmarker';
                 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $name, 'value' => $row->allocatedmarker));
             }
             $output .= $markerlist[$row->allocatedmarker];
             return $output;
         }
     }
 }
/**
 * Returns a list of issued certificates - sorted for report.
 *
 * @param int $certificateid
 * @param string $sort the sort order
 * @param boolean $groupmode are we in group mode ?
 * @param stdClass $cm the course module
 */
function certificate_get_issues($certificateid, $sort = "ci.certdate ASC", $groupmode, $cm)
{
    global $CFG, $DB;
    // get all users that can manage this certificate to exclude them from the report.
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $certmanagers = get_users_by_capability($context, 'mod/certificate:manage', 'u.id');
    // Get all the users that have certificates issued, first, create subsql
    // used in the main sql query, this is used so that we don't get an error
    // about the same u.id being returned multiple times due to being in the
    // certificate issues table multiple times.
    $subsql = "SELECT MAX(ci2.timecreated) as timecreated\n               FROM {certificate_issues} ci2\n               WHERE ci2.certificateid = :subsqlcertificateid\n               AND ci2.certdate > 0\n               AND ci2.userid = u.id";
    $users = $DB->get_records_sql("SELECT u.*, ci.code, ci.timecreated, ci.certdate, ci.studentname, ci.reportgrade\n                                   FROM {user} u\n                                   INNER JOIN {certificate_issues} ci\n                                   ON u.id = ci.userid\n                                   WHERE u.deleted = 0\n                                   AND ci.certificateid = :certificateid\n                                   AND ci.certdate > 0\n                                   AND ci.timecreated = ({$subsql})\n                                   ORDER BY {$sort}", array('certificateid' => $certificateid, 'subsqlcertificateid' => $certificateid));
    // now exclude all the certmanagers.
    foreach ($users as $id => $user) {
        if (isset($certmanagers[$id])) {
            //exclude certmanagers.
            unset($users[$id]);
        }
    }
    // if groupmembersonly used, remove users who are not in any group
    if (!empty($users) and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
        if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
            $users = array_intersect($users, array_keys($groupingusers));
        }
    }
    if (!$groupmode) {
        return $users;
    } else {
        $currentgroup = groups_get_activity_group($cm);
        if ($currentgroup) {
            $groupusers = groups_get_members($currentgroup, 'u.*');
            if (empty($groupusers)) {
                return array();
            }
            foreach ($groupusers as $id => $gpuser) {
                if (!isset($users[$id])) {
                    //remove this user as it isn't in the group!
                    unset($users[$id]);
                }
            }
        }
        return $users;
    }
}
Beispiel #25
0
function checklist_update_grades($checklist, $userid = 0)
{
    global $CFG, $DB;
    $items = $DB->get_records('checklist_item', array('checklist' => $checklist->id, 'userid' => 0, 'itemoptional' => CHECKLIST_OPTIONAL_NO, 'hidden' => CHECKLIST_HIDDEN_NO), '', 'id, grouping');
    if (!$items) {
        return;
    }
    if (!($course = $DB->get_record('course', array('id' => $checklist->course)))) {
        return;
    }
    if (!($cm = get_coursemodule_from_instance('checklist', $checklist->id, $course->id))) {
        return;
    }
    $checkgroupings = false;
    // Don't check items against groupings unless we really have to
    if (isset($CFG->enablegroupmembersonly) && $CFG->enablegroupmembersonly && $checklist->autopopulate) {
        foreach ($items as $item) {
            if ($item->grouping) {
                $checkgroupings = true;
                break;
            }
        }
    }
    if ($checklist->teacheredit == CHECKLIST_MARKING_STUDENT) {
        $date = ', MAX(c.usertimestamp) AS datesubmitted';
        $where = 'c.usertimestamp > 0';
    } else {
        $date = ', MAX(c.teachertimestamp) AS dategraded';
        $where = 'c.teachermark = ' . CHECKLIST_TEACHERMARK_YES;
    }
    if ($checkgroupings) {
        if ($userid) {
            $users = $DB->get_records('user', array('id' => $userid), null, 'id, firstname, lastname');
        } else {
            if ($CFG->version < 2011120100) {
                $context = get_context_instance(CONTEXT_MODULE, $cm->id);
            } else {
                $context = context_module::instance($cm->id);
            }
            if (!($users = get_users_by_capability($context, 'mod/checklist:updateown', 'u.id, u.firstname, u.lastname', '', '', '', '', '', false))) {
                return;
            }
        }
        $grades = array();
        // With groupings, need to update each user individually (as each has different groupings)
        foreach ($users as $userid => $user) {
            $groupings = checklist_class::get_user_groupings($userid, $course->id);
            $total = 0;
            $itemlist = '';
            foreach ($items as $item) {
                if ($item->grouping) {
                    if (!in_array($item->grouping, $groupings)) {
                        continue;
                    }
                }
                $itemlist .= $item->id . ',';
                $total++;
            }
            if (!$total) {
                // No items - set score to 0
                $ugrade = new stdClass();
                $ugrade->userid = $userid;
                $ugrade->rawgrade = 0;
                $ugrade->date = time();
            } else {
                $itemlist = substr($itemlist, 0, -1);
                // Remove trailing ','
                $sql = 'SELECT ? AS userid, (SUM(CASE WHEN ' . $where . ' THEN 1 ELSE 0 END) * ? / ? ) AS rawgrade' . $date;
                $sql .= " FROM {checklist_check} c ";
                $sql .= " WHERE c.item IN ({$itemlist})";
                $sql .= ' AND c.userid = ? ';
                $ugrade = $DB->get_record_sql($sql, array($userid, $checklist->maxgrade, $total, $userid));
                if (!$ugrade) {
                    $ugrade = new stdClass();
                    $ugrade->userid = $userid;
                    $ugrade->rawgrade = 0;
                    $ugrade->date = time();
                }
            }
            $ugrade->firstname = $user->firstname;
            $ugrade->lastname = $user->lastname;
            $grades[$userid] = $ugrade;
        }
    } else {
        // No need to check groupings, so update all student grades at once
        if ($userid) {
            $users = $userid;
        } else {
            if ($CFG->version < 2011120100) {
                $context = get_context_instance(CONTEXT_MODULE, $cm->id);
            } else {
                $context = context_module::instance($cm->id);
            }
            if (!($users = get_users_by_capability($context, 'mod/checklist:updateown', 'u.id', '', '', '', '', '', false))) {
                return;
            }
            $users = array_keys($users);
        }
        $total = count($items);
        list($usql, $uparams) = $DB->get_in_or_equal($users);
        list($isql, $iparams) = $DB->get_in_or_equal(array_keys($items));
        $sql = 'SELECT u.id AS userid, (SUM(CASE WHEN ' . $where . ' THEN 1 ELSE 0 END) * ? / ? ) AS rawgrade' . $date;
        $sql .= ' , u.firstname, u.lastname ';
        $sql .= ' FROM {user} u LEFT JOIN {checklist_check} c ON u.id = c.userid';
        $sql .= " WHERE u.id {$usql}";
        $sql .= " AND c.item {$isql}";
        $sql .= ' GROUP BY u.id, u.firstname, u.lastname';
        $params = array_merge($uparams, $iparams);
        $params = array_merge(array($checklist->maxgrade, $total), $params);
        $grades = $DB->get_records_sql($sql, $params);
    }
    foreach ($grades as $grade) {
        // Log completion of checklist
        if ($grade->rawgrade == $checklist->maxgrade) {
            if ($checklist->emailoncomplete) {
                $timelimit = time() - 1 * 60 * 60;
                // Do not send another email if this checklist was already 'completed' in the last hour
                $filter = "l.time > ? AND l.cmid = ? AND l.userid = ? AND l.action = 'complete'";
                get_logs($filter, array($timelimit, $cm->id, $grade->userid), '', 1, 1, $logcount);
                if ($logcount == 0) {
                    if (!isset($context)) {
                        if ($CFG->version < 2011120100) {
                            $context = get_context_instance(CONTEXT_MODULE, $cm->id);
                        } else {
                            $context = context_module::instance($cm->id);
                        }
                    }
                    if ($recipients = get_users_by_capability($context, 'mod/checklist:emailoncomplete', 'u.*', '', '', '', '', '', false)) {
                        foreach ($recipients as $recipient) {
                            $details = new stdClass();
                            $details->user = fullname($grade);
                            $details->checklist = s($checklist->name);
                            $subj = get_string('emailoncompletesubject', 'checklist', $details);
                            $content = get_string('emailoncompletebody', 'checklist', $details);
                            $content .= $CFG->wwwroot . '/mod/checklist/view.php?id=' . $cm->id;
                            email_to_user($recipient, $grade, $subj, $content, '', '', '', false);
                        }
                    }
                }
            }
            add_to_log($checklist->course, 'checklist', 'complete', "view.php?id={$cm->id}", $checklist->name, $cm->id, $grade->userid);
        }
        $ci = new completion_info($course);
        if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
            $ci->update_state($cm, COMPLETION_UNKNOWN, $grade->userid);
        }
    }
    checklist_grade_item_update($checklist, $grades);
}
/**
 * List conversations of either open or closed type for the current user
 * 
 * Called when a user clicks the "Current Dialogues" or "Closed Dialogues" tabs
 * rendering those out directly as HTML inside a print_table() showing who the
 * conversation is with, what the subject is, how many entries there are, 
 * how many are un-read and what the most recent post date is 
 *  
 * @param   object  $dialogue
 * @param   int     $groupid    of the group to filter conversations by (default: 0)
 * @param   string  $type       'open' (default) or 'closed'
 * @todo    remove the embedded style for 'th', make it a class driven thing in the theme
 */
function dialogue_list_conversations($dialogue, $groupid = 0, $type = 'open')
{
    global $USER, $CFG;
    $condition = $type == 'closed' ? " closed='1' " : " closed='0' ";
    $tabid = $type == 'closed' ? 3 : 1;
    if (!($course = get_record('course', 'id', $dialogue->course))) {
        error('Course is misconfigured');
    }
    if (!($cm = get_coursemodule_from_instance('dialogue', $dialogue->id, $course->id))) {
        error('Course Module ID was incorrect');
    }
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $dialoguemanagers = array_keys(get_users_by_capability($context, 'mod/dialogue:manage'));
    echo '<style>th.header { text-align: left; }</style>';
    require_once $CFG->libdir . '/tablelib.php';
    $tablecolumns = array('picture', 'subject', 'fullname', 'total', 'unread', 'lastentry');
    $tableheaders = array('', get_string('subject', 'dialogue'), get_string('fullname', ''), get_string('numberofentries', 'dialogue'), get_string('unread', 'dialogue'), get_string('lastentry', 'dialogue'));
    $table = new flexible_table('mod-dialogue-submissions');
    $table->define_columns($tablecolumns);
    $table->define_headers($tableheaders);
    $table->define_baseurl($CFG->wwwroot . '/mod/dialogue/view.php?id=' . $cm->id . '&amp;pane=' . $tabid);
    $table->sortable(true, 'subject');
    $table->collapsible(false);
    //$table->column_suppress('picture'); // supress multiple subsequent row entries
    //$table->column_suppress('fullname');
    $table->set_attribute('cellspacing', '0');
    $table->set_attribute('id', 'dialogue');
    $table->set_attribute('class', 'conversations');
    $table->set_attribute('width', '100%');
    $table->setup();
    $order = '';
    // so we can filter the get_conversations() call later
    $namesort = '';
    // if we want to sort by other calculated fields, e.g. first/last name
    if ($sort = $table->get_sql_sort('mod-dialogue-submissions')) {
        $sortparts = explode(',', $sort);
        $sqlsort = $sortparts[0];
        if (strpos($sqlsort, 'subject') !== false) {
            $order = $sqlsort;
        }
        if (strpos($sqlsort, 'total') !== false) {
            $order = $sqlsort;
        }
        if (strpos($sqlsort, 'lastentry') !== false) {
            $order = $sqlsort;
            $order = str_replace('lastentry', 'c.timemodified', $order);
        }
        if (strpos($sqlsort, 'firstname') !== false) {
            $namesort = $sqlsort;
        }
        if (strpos($sqlsort, 'lastname') !== false) {
            $namesort = $sqlsort;
        }
        if (strpos($sqlsort, 'unread') !== false) {
            $namesort = $sqlsort;
        }
    }
    // list the conversations requiring a resonse from this user in full
    if ($conversations = dialogue_get_conversations($dialogue, $USER, $condition, $order, $groupid)) {
        foreach ($conversations as $conversation) {
            if (in_array($USER->id, $dialoguemanagers)) {
                if (!in_array($conversation->userid, $dialoguemanagers)) {
                    if (!($with = get_record('user', 'id', $conversation->userid))) {
                        error("User's record not found");
                    }
                } else {
                    if (!($with = get_record('user', 'id', $conversation->recipientid))) {
                        error("User's record not found");
                    }
                }
            } else {
                if ($USER->id != $conversation->userid) {
                    if (!($with = get_record('user', 'id', $conversation->userid))) {
                        error("User's record not found");
                    }
                } else {
                    if (!($with = get_record('user', 'id', $conversation->recipientid))) {
                        error("User's record not found");
                    }
                }
            }
            // save sortable field values for each conversation so can sort by them later
            $names[$conversation->id] = fullname($with);
            $unread[$conversation->id] = $conversation->total - $conversation->readings;
            $names_firstlast[$conversation->id] = $with->firstname . ' ' . $with->lastname;
            $names_lastfirst[$conversation->id] = $with->lastname . ' ' . $with->firstname;
            $photos[$conversation->id] = print_user_picture($with, $course->id, true, 0, true);
            $ids[$conversation->id] = $with->id;
        }
        // sort an array of conversations based on which field user clicked to sort in the UI
        $sortedvalues = $names;
        // default is sort by fullname from above
        switch ($namesort) {
            case 'firstname ASC':
                $sortedvalues = $names_firstlast;
                natcasesort($sortedvalues);
                break;
            case 'firstname DESC':
                $sortedvalues = $names_firstlast;
                natcasesort($sortedvalues);
                $sortedvalues = array_reverse($sortedvalues, true);
                break;
            case 'lastname ASC':
                $sortedvalues = $names_lastfirst;
                natcasesort($sortedvalues);
                break;
            case 'lastname DESC':
                $sortedvalues = $names_lastfirst;
                natcasesort($sortedvalues);
                $sortedvalues = array_reverse($sortedvalues, true);
                break;
            case 'unread ASC':
                $sortedvalues = $unread;
                asort($sortedvalues);
                break;
            case 'unread DESC':
                $sortedvalues = $unread;
                arsort($sortedvalues);
                break;
        }
        foreach ($sortedvalues as $cid => $val) {
            $conversation = $conversations[$cid];
            if ($unread[$cid] > 0) {
                $unreadcount = '<span class="unread">' . $unread[$cid] . '</span>';
            } else {
                $unreadcount = 0;
            }
            $profileurl = "{$CFG->wwwroot}/user/view.php?id=" . $ids[$conversation->id] . "&amp;course={$dialogue->course}";
            $entryurl = "{$CFG->wwwroot}/mod/dialogue/dialogues.php?id=" . $cm->id . "&amp;action=printdialogue&amp;cid=" . $cid;
            $row = array($photos[$conversation->id], "<a href='{$entryurl}'>" . $conversation->subject . '</a>', "<a href='{$profileurl}'>" . $names[$conversation->id] . '</a>', $conversation->total, $unreadcount, userdate($conversation->timemodified));
            $table->add_data($row);
        }
        $table->print_html();
        /// Print the whole table
    }
}
 if (empty($subject) || empty($message)) {
     $_SESSION['embeddednotice'] = array("type" => "error");
     $_SESSION["embeddednotice"]["message"] = get_string('nonsubmitterserror', 'turnitintooltwo');
     $error = true;
     $do = "emailnonsubmittersform";
 }
 if ($error) {
     // Save data in session incase of error
     $_SESSION['form_data'] = new stdClass();
     $_SESSION['form_data']->nonsubmitters_subject = $subject;
     $_SESSION['form_data']->nonsubmitters_message = $message;
     $_SESSION['form_data']->nonsubmitters_sendtoself = $sendtoself;
 } else {
     // Get all users enrolled in the class.
     $context = context_module::instance($cm->id);
     $allusers = get_users_by_capability(context_module::instance($cm->id), 'mod/turnitintooltwo:submit', 'u.id', '', '', '', groups_get_activity_group($cm));
     // Get users who've submitted.
     $params = array('turnitintooltwoid' => $turnitintooltwo->id, 'submission_part' => $part);
     $submittedusers = $DB->get_records('turnitintooltwo_submissions', $params, '', 'userid');
     // Send message to all non submitted users.
     $nonsubmittedusers = array_diff_key((array) $allusers, (array) $submittedusers);
     foreach ($nonsubmittedusers as $nonsubmitteduser) {
         //Send a message to the user's Moodle inbox with the digital receipt.
         $nonsubmitters->send_message($nonsubmitteduser->id, $subject, $message);
     }
     // Send a copy of message to the instructor if appropriate.
     if (!empty($sendtoself)) {
         $nonsubmitters->send_message($USER->id, $subject, $message);
     }
     $do = "emailsent";
 }
 /**
  * MDL-27591 made this method obsolete.
  */
 public function get_users($groupid = 0, $page = 1)
 {
     global $DB, $CFG;
     // Fields we need from the user table.
     $userfields = user_picture::fields('u', array('username', 'idnumber', 'institution', 'department'));
     if (isset($this->pageparams->sort) and $this->pageparams->sort == ATT_SORT_FIRSTNAME) {
         $orderby = "u.firstname ASC, u.lastname ASC, u.idnumber ASC, u.institution ASC, u.department ASC";
     } else {
         $orderby = "u.lastname ASC, u.firstname ASC, u.idnumber ASC, u.institution ASC, u.department ASC";
     }
     if ($page) {
         $usersperpage = $this->pageparams->perpage;
         if (!empty($CFG->enablegroupmembersonly) and $this->cm->groupmembersonly) {
             $startusers = ($page - 1) * $usersperpage;
             if ($groupid == 0) {
                 $groups = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
             } else {
                 $groups = $groupid;
             }
             $users = get_users_by_capability($this->context, 'mod/attendance:canbelisted', $userfields . ',u.id, u.firstname, u.lastname, u.email', $orderby, $startusers, $usersperpage, $groups, '', false, true);
         } else {
             $startusers = ($page - 1) * $usersperpage;
             $users = get_enrolled_users($this->context, 'mod/attendance:canbelisted', $groupid, $userfields, $orderby, $startusers, $usersperpage);
         }
     } else {
         if (!empty($CFG->enablegroupmembersonly) and $this->cm->groupmembersonly) {
             if ($groupid == 0) {
                 $groups = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
             } else {
                 $groups = $groupid;
             }
             $users = get_users_by_capability($this->context, 'mod/attendance:canbelisted', $userfields . ',u.id, u.firstname, u.lastname, u.email', $orderby, '', '', $groups, '', false, true);
         } else {
             $users = get_enrolled_users($this->context, 'mod/attendance:canbelisted', $groupid, $userfields, $orderby);
         }
     }
     // Add a flag to each user indicating whether their enrolment is active.
     if (!empty($users)) {
         list($sql, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED, 'usid0');
         // See CONTRIB-4868.
         $mintime = 'MIN(CASE WHEN (ue.timestart > :zerotime) THEN ue.timestart ELSE ue.timecreated END)';
         $maxtime = 'CASE WHEN MIN(ue.timeend) = 0 THEN 0 ELSE MAX(ue.timeend) END';
         // See CONTRIB-3549.
         $sql = "SELECT ue.userid, MIN(ue.status) as status,\n                           {$mintime} AS mintime,\n                           {$maxtime} AS maxtime\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON e.id = ue.enrolid\n                     WHERE ue.userid {$sql}\n                           AND e.status = :estatus\n                           AND e.courseid = :courseid\n                  GROUP BY ue.userid";
         $params += array('zerotime' => 0, 'estatus' => ENROL_INSTANCE_ENABLED, 'courseid' => $this->course->id);
         $enrolments = $DB->get_records_sql($sql, $params);
         foreach ($users as $user) {
             $users[$user->id]->enrolmentstatus = $enrolments[$user->id]->status;
             $users[$user->id]->enrolmentstart = $enrolments[$user->id]->mintime;
             $users[$user->id]->enrolmentend = $enrolments[$user->id]->maxtime;
             $users[$user->id]->type = 'standard';
             // Mark as a standard (not a temporary) user.
         }
     }
     // Add the 'temporary' users to this list.
     $tempusers = $DB->get_records('attendance_tempusers', array('courseid' => $this->course->id));
     foreach ($tempusers as $tempuser) {
         $users[] = self::tempuser_to_user($tempuser);
     }
     return $users;
 }
     message_paypal_error_to_admin("Amount paid is not enough ({$data->payment_gross} < {$cost}))", $data);
     die;
 }
 // ALL CLEAR !
 $DB->insert_record("enrol_paypal", $data);
 if ($plugin_instance->enrolperiod) {
     $timestart = time();
     $timeend = $timestart + $plugin_instance->enrolperiod;
 } else {
     $timestart = 0;
     $timeend = 0;
 }
 // Enrol user
 $plugin->enrol_user($plugin_instance, $user->id, $plugin_instance->roleid, $timestart, $timeend);
 // Pass $view=true to filter hidden caps if the user cannot see them
 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC', '', '', '', '', false, true)) {
     $users = sort_by_roleassignment_authority($users, $context);
     $teacher = array_shift($users);
 } else {
     $teacher = false;
 }
 $mailstudents = $plugin->get_config('mailstudents');
 $mailteachers = $plugin->get_config('mailteachers');
 $mailadmins = $plugin->get_config('mailadmins');
 $shortname = format_string($course->shortname, true, array('context' => $context));
 if (!empty($mailstudents)) {
     $a->coursename = format_string($course->fullname, true, array('context' => $coursecontext));
     $a->profileurl = "{$CFG->wwwroot}/user/view.php?id={$user->id}";
     $eventdata = new stdClass();
     $eventdata->modulename = 'moodle';
     $eventdata->component = 'enrol_paypal';
Beispiel #30
0
 /**
  * Load all of the uses who have the capability into choice array
  *
  * @return bool Always returns true
  */
 function load_choices()
 {
     if (is_array($this->choices)) {
         return true;
     }
     list($sort, $sortparams) = users_order_by_sql('u');
     if (!empty($sortparams)) {
         throw new coding_exception('users_order_by_sql returned some query parameters. ' . 'This is unexpected, and a problem because there is no way to pass these ' . 'parameters to get_users_by_capability. See MDL-34657.');
     }
     $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
     $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
     $this->choices = array('$@NONE@$' => get_string('nobody'), '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)));
     if ($this->includeadmins) {
         $admins = get_admins();
         foreach ($admins as $user) {
             $this->choices[$user->id] = fullname($user);
         }
     }
     if (is_array($users)) {
         foreach ($users as $user) {
             $this->choices[$user->id] = fullname($user);
         }
     }
     return true;
 }