Пример #1
0
/**
 * Adds module specific settings to the settings block
 *
 * @param settings_navigation $settings The settings navigation object
 * @param navigation_node $questionnairenode The node to add module settings to
 */
function questionnaire_extend_settings_navigation(settings_navigation $settings, navigation_node $questionnairenode)
{
    global $PAGE, $DB, $USER, $CFG;
    $individualresponse = optional_param('individualresponse', false, PARAM_INT);
    $rid = optional_param('rid', false, PARAM_INT);
    // Response id.
    $currentgroupid = optional_param('group', 0, PARAM_INT);
    // Group id.
    require_once $CFG->dirroot . '/mod/questionnaire/questionnaire.class.php';
    $context = $PAGE->cm->context;
    $cmid = $PAGE->cm->id;
    $cm = $PAGE->cm;
    $course = $PAGE->course;
    if (!($questionnaire = $DB->get_record("questionnaire", array("id" => $cm->instance)))) {
        print_error('invalidcoursemodule');
    }
    $courseid = $course->id;
    $questionnaire = new questionnaire(0, $questionnaire, $course, $cm);
    if ($survey = $DB->get_record('questionnaire_survey', array('id' => $questionnaire->sid))) {
        $owner = trim($survey->owner) == trim($courseid);
    } else {
        $survey = false;
        $owner = true;
    }
    // We want to add these new nodes after the Edit settings node, and before the
    // Locally assigned roles node. Of course, both of those are controlled by capabilities.
    $keys = $questionnairenode->get_children_key_list();
    $beforekey = null;
    $i = array_search('modedit', $keys);
    if ($i === false and array_key_exists(0, $keys)) {
        $beforekey = $keys[0];
    } else {
        if (array_key_exists($i + 1, $keys)) {
            $beforekey = $keys[$i + 1];
        }
    }
    if (has_capability('mod/questionnaire:manage', $context) && $owner) {
        $url = '/mod/questionnaire/qsettings.php';
        $node = navigation_node::create(get_string('advancedsettings'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'advancedsettings', new pix_icon('t/edit', ''));
        $questionnairenode->add_node($node, $beforekey);
    }
    if (has_capability('mod/questionnaire:editquestions', $context) && $owner) {
        $url = '/mod/questionnaire/questions.php';
        $node = navigation_node::create(get_string('questions', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'questions', new pix_icon('t/edit', ''));
        $questionnairenode->add_node($node, $beforekey);
    }
    if (has_capability('mod/questionnaire:preview', $context) && $owner) {
        $url = '/mod/questionnaire/preview.php';
        $node = navigation_node::create(get_string('preview_label', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'preview', new pix_icon('t/preview', ''));
        $questionnairenode->add_node($node, $beforekey);
    }
    if ($questionnaire->user_can_take($USER->id)) {
        $url = '/mod/questionnaire/complete.php';
        $node = navigation_node::create(get_string('answerquestions', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, '', new pix_icon('i/info', 'answerquestions'));
        $questionnairenode->add_node($node, $beforekey);
    }
    $usernumresp = $questionnaire->count_submissions($USER->id);
    if ($questionnaire->capabilities->readownresponses && $usernumresp > 0) {
        $url = '/mod/questionnaire/myreport.php';
        $node = navigation_node::create(get_string('yourresponses', 'questionnaire'), new moodle_url($url, array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'summary')), navigation_node::TYPE_SETTING, null, 'yourresponses');
        $myreportnode = $questionnairenode->add_node($node, $beforekey);
        $summary = $myreportnode->add(get_string('summary', 'questionnaire'), new moodle_url('/mod/questionnaire/myreport.php', array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'summary')));
        $byresponsenode = $myreportnode->add(get_string('viewbyresponse', 'questionnaire'), new moodle_url('/mod/questionnaire/myreport.php', array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 1, 'action' => 'vresp')));
        $allmyresponsesnode = $myreportnode->add(get_string('myresponses', 'questionnaire'), new moodle_url('/mod/questionnaire/myreport.php', array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'vall')));
        if ($questionnaire->capabilities->downloadresponses) {
            $downloadmyresponsesnode = $myreportnode->add(get_string('downloadtext'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'user' => $USER->id, 'action' => 'dwnpg', 'group' => $currentgroupid)));
        }
    }
    $numresp = $questionnaire->count_submissions();
    // Number of responses in currently selected group (or all participants etc.).
    if (isset($SESSION->questionnaire->numselectedresps)) {
        $numselectedresps = $SESSION->questionnaire->numselectedresps;
    } else {
        $numselectedresps = $numresp;
    }
    // If questionnaire is set to separate groups, prevent user who is not member of any group
    // to view All responses.
    $canviewgroups = true;
    $groupmode = groups_get_activity_groupmode($cm, $course);
    if ($groupmode == 1) {
        $canviewgroups = groups_has_membership($cm, $USER->id);
    }
    if ($questionnaire->capabilities->readallresponseanytime && $numresp > 0 && $owner && $numselectedresps > 0 || $questionnaire->capabilities->readallresponses && $numresp > 0 && $canviewgroups && ($questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS || $questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $questionnaire->is_closed() || $questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && $usernumresp > 0) && $questionnaire->is_survey_owner()) {
        $url = '/mod/questionnaire/report.php';
        $node = navigation_node::create(get_string('viewallresponses', 'questionnaire'), new moodle_url($url, array('instance' => $questionnaire->id, 'action' => 'vall')), navigation_node::TYPE_SETTING, null, 'vall');
        $reportnode = $questionnairenode->add_node($node, $beforekey);
        if ($questionnaire->capabilities->viewsingleresponse) {
            $summarynode = $reportnode->add(get_string('summary', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vall')));
        } else {
            $summarynode = $reportnode;
        }
        $defaultordernode = $summarynode->add(get_string('order_default', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vall', 'group' => $currentgroupid)));
        $ascendingordernode = $summarynode->add(get_string('order_ascending', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vallasort', 'group' => $currentgroupid)));
        $descendingordernode = $summarynode->add(get_string('order_descending', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vallarsort', 'group' => $currentgroupid)));
        if ($questionnaire->capabilities->deleteresponses) {
            $deleteallnode = $summarynode->add(get_string('deleteallresponses', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'delallresp', 'group' => $currentgroupid)));
        }
        if ($questionnaire->capabilities->downloadresponses) {
            $downloadresponsesnode = $summarynode->add(get_string('downloadtextformat', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'dwnpg', 'group' => $currentgroupid)));
        }
        if ($questionnaire->capabilities->viewsingleresponse && $questionnaire->respondenttype != 'anonymous') {
            $byresponsenode = $reportnode->add(get_string('viewbyresponse', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vresp', 'byresponse' => 1, 'group' => $currentgroupid)));
            $viewindividualresponsenode = $byresponsenode->add(get_string('view', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vresp', 'byresponse' => 1, 'group' => $currentgroupid)));
            if ($individualresponse) {
                $deleteindividualresponsenode = $byresponsenode->add(get_string('deleteresp', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'dresp', 'byresponse' => 1, 'rid' => $rid, 'group' => $currentgroupid, 'individualresponse' => 1)));
            }
        }
    }
    if ($questionnaire->capabilities->viewsingleresponse) {
        $url = '/mod/questionnaire/show_nonrespondents.php';
        $node = navigation_node::create(get_string('show_nonrespondents', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'nonrespondents');
        $nonrespondentsnode = $questionnairenode->add_node($node, $beforekey);
    }
}
 public function can_view_all_responses($usernumresp = null)
 {
     global $USER, $DB, $SESSION;
     if ($owner = $DB->get_field('questionnaire_survey', 'owner', array('id' => $this->sid))) {
         $owner = trim($owner) == trim($this->course->id);
     } else {
         $owner = true;
     }
     $numresp = $this->count_submissions();
     if ($usernumresp === null) {
         $usernumresp = $questionnaire->count_submissions($USER->id);
     }
     // Number of Responses in currently selected group (or all participants etc.).
     if (isset($SESSION->questionnaire->numselectedresps)) {
         $numselectedresps = $SESSION->questionnaire->numselectedresps;
     } else {
         $numselectedresps = $numresp;
     }
     // If questionnaire is set to separate groups, prevent user who is not member of any group
     // to view All responses.
     $canviewgroups = true;
     $groupmode = groups_get_activity_groupmode($this->cm, $this->course);
     if ($groupmode == 1) {
         $canviewgroups = groups_has_membership($this->cm, $USER->id);
     }
     $canviewallgroups = has_capability('moodle/site:accessallgroups', $this->context);
     return ($canviewallgroups || $canviewgroups && $this->capabilities->readallresponseanytime) && $numresp > 0 && $owner && $numselectedresps > 0 || $this->capabilities->readallresponses && $numresp > 0 && $canviewgroups && ($this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS || $this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $this->is_closed() || $this->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && $usernumresp > 0) && $this->is_survey_owner();
 }
Пример #3
0
 /**
  * Returns a list of teachers that should be grading given submission.
  *
  * @param int $userid The submission to grade
  * @return array
  */
 protected function get_graders($userid)
 {
     // Potential graders should be active users only.
     $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade", null, 'u.*', null, null, null, true);
     $graders = array();
     if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {
         if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) {
             foreach ($groups as $group) {
                 foreach ($potentialgraders as $grader) {
                     if ($grader->id == $userid) {
                         // Do not send self.
                         continue;
                     }
                     if (groups_is_member($group->id, $grader->id)) {
                         $graders[$grader->id] = $grader;
                     }
                 }
             }
         } else {
             // User not in group, try to find graders without group.
             foreach ($potentialgraders as $grader) {
                 if ($grader->id == $userid) {
                     // Do not send self.
                     continue;
                 }
                 if (!groups_has_membership($this->get_course_module(), $grader->id)) {
                     $graders[$grader->id] = $grader;
                 }
             }
         }
     } else {
         foreach ($potentialgraders as $grader) {
             if ($grader->id == $userid) {
                 // Do not send self.
                 continue;
             }
             // Must be enrolled.
             if (is_enrolled($this->get_course_context(), $grader->id)) {
                 $graders[$grader->id] = $grader;
             }
         }
     }
     return $graders;
 }
Пример #4
0
/**
 * Determine if a course module is currently visible to a user
 *
 * $USER If $userid is null, use the global object.
 *
 * @global object
 * @global object
 * @param int $cm The course module
 * @param int $userid The user to check against the group.
 * @return boolean True if the user can view the course module, false otherwise.
 */
function groups_course_module_visible($cm, $userid = null)
{
    global $CFG, $USER;
    if (empty($userid)) {
        $userid = $USER->id;
    }
    if (empty($CFG->enablegroupmembersonly)) {
        return true;
    }
    if (empty($cm->groupmembersonly)) {
        return true;
    }
    if (has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id), $userid) or groups_has_membership($cm, $userid)) {
        return true;
    }
    return false;
}
Пример #5
0
    /**
     * Returns a list of teachers that should be grading given submission
     *
     * @param int $userid
     * @return array
     */
    private function get_graders($userid) {
        //potential graders
        $potentialgraders = get_enrolled_users($this->context, "mod/assign:grade");

        $graders = array();
        if (groups_get_activity_groupmode($this->get_course_module()) == SEPARATEGROUPS) {   // Separate groups are being used
            if ($groups = groups_get_all_groups($this->get_course()->id, $userid)) {  // Try to find all groups
                foreach ($groups as $group) {
                    foreach ($potentialgraders as $grader) {
                        if ($grader->id == $userid) {
                            continue; // do not send self
                        }
                        if (groups_is_member($group->id, $grader->id)) {
                            $graders[$grader->id] = $grader;
                        }
                    }
                }
            } else {
                // user not in group, try to find graders without group
                foreach ($potentialgraders as $grader) {
                    if ($grader->id == $userid) {
                        continue; // do not send self
                    }
                    if (!groups_has_membership($this->get_course_module(), $grader->id)) {
                        $graders[$grader->id] = $grader;
                    }
                }
            }
        } else {
            foreach ($potentialgraders as $grader) {
                if ($grader->id == $userid) {
                    continue; // do not send self
                }
                // must be enrolled
                if (is_enrolled($this->get_course_context(), $grader->id)) {
                    $graders[$grader->id] = $grader;
                }
            }
        }
        return $graders;
    }
Пример #6
0
    echo '<a href="' . $CFG->wwwroot . htmlspecialchars('/mod/questionnaire/myreport.php?' . $argstr) . '">' . $titletext . '</a>';
    echo $OUTPUT->box_end();
}
if ($survey = $DB->get_record('questionnaire_survey', array('id' => $questionnaire->sid))) {
    $owner = trim($survey->owner) == trim($course->id);
} else {
    $survey = false;
    $owner = true;
}
$numresp = $questionnaire->count_submissions();
// Number of Responses in currently selected group (or all participants etc.).
if (isset($SESSION->questionnaire->numselectedresps)) {
    $numselectedresps = $SESSION->questionnaire->numselectedresps;
} else {
    $numselectedresps = $numresp;
}
// If questionnaire is set to separate groups, prevent user who is not member of any group
// to view All responses.
$canviewgroups = true;
$groupmode = groups_get_activity_groupmode($cm, $course);
if ($groupmode == 1) {
    $canviewgroups = groups_has_membership($cm, $USER->id);
}
$canviewallgroups = has_capability('moodle/site:accessallgroups', $context);
if (($canviewallgroups || $canviewgroups && $questionnaire->capabilities->readallresponseanytime) && $numresp > 0 && $owner && $numselectedresps > 0 || $questionnaire->capabilities->readallresponses && $numresp > 0 && $canviewgroups && ($questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS || $questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $questionnaire->is_closed() || $questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && $usernumresp > 0) && $questionnaire->is_survey_owner()) {
    echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
    $argstr = 'instance=' . $questionnaire->id . '&group=' . $currentgroupid;
    echo '<a href="' . $CFG->wwwroot . htmlspecialchars('/mod/questionnaire/report.php?' . $argstr) . '">' . get_string('viewallresponses', 'questionnaire') . '</a>';
    echo $OUTPUT->box_end();
}
echo $OUTPUT->footer();
Пример #7
0
/**
 * This function checks that the current user is logged in and has the
 * required privileges
 *
 * This function checks that the current user is logged in, and optionally
 * whether they are allowed to be in a particular course and view a particular
 * course module.
 * If they are not logged in, then it redirects them to the site login unless
 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
 * case they are automatically logged in as guests.
 * If $courseid is given and the user is not enrolled in that course then the
 * user is redirected to the course enrolment page.
 * If $cm is given and the coursemodule is hidden and the user is not a teacher
 * in the course then the user is redirected to the course home page.
 *
 * @uses $CFG
 * @uses $SESSION
 * @uses $USER
 * @uses $FULLME
 * @uses SITEID
 * @uses $COURSE
 * @param mixed $courseorid id of the course or course object
 * @param bool $autologinguest
 * @param object $cm course module object
 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
 *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
 *             in order to keep redirects working properly. MDL-14495
 */
function require_login($courseorid = 0, $autologinguest = true, $cm = null, $setwantsurltome = true)
{
    global $CFG, $SESSION, $USER, $COURSE, $FULLME;
    /// setup global $COURSE, themes, language and locale
    course_setup($courseorid);
    /// If the user is not even logged in yet then make sure they are
    if (!isloggedin()) {
        //NOTE: $USER->site check was obsoleted by session test cookie,
        //      $USER->confirmed test is in login/index.php
        if ($setwantsurltome) {
            $SESSION->wantsurl = $FULLME;
        }
        if (!empty($_SERVER['HTTP_REFERER'])) {
            $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
        }
        if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest)) {
            $loginguest = '?loginguest=true';
        } else {
            $loginguest = '';
        }
        if (empty($CFG->loginhttps) or $loginguest) {
            //do not require https for guest logins
            redirect($CFG->wwwroot . '/login/index.php' . $loginguest);
        } else {
            $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
            redirect($wwwroot . '/login/index.php');
        }
        exit;
    }
    /// loginas as redirection if needed
    if ($COURSE->id != SITEID and !empty($USER->realuser)) {
        if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
            if ($USER->loginascontext->instanceid != $COURSE->id) {
                print_error('loginasonecourse', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid);
            }
        }
    }
    /// check whether the user should be changing password (but only if it is REALLY them)
    if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
        $userauth = get_auth_plugin($USER->auth);
        if ($userauth->can_change_password()) {
            $SESSION->wantsurl = $FULLME;
            if ($changeurl = $userauth->change_password_url()) {
                //use plugin custom url
                redirect($changeurl);
            } else {
                //use moodle internal method
                if (empty($CFG->loginhttps)) {
                    redirect($CFG->wwwroot . '/login/change_password.php');
                } else {
                    $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
                    redirect($wwwroot . '/login/change_password.php');
                }
            }
        } else {
            print_error('nopasswordchangeforced', 'auth');
        }
    }
    /// Check that the user account is properly set up
    if (user_not_fully_set_up($USER)) {
        $SESSION->wantsurl = $FULLME;
        redirect($CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&amp;course=' . SITEID);
    }
    /// Make sure current IP matches the one for this session (if required)
    if (!empty($CFG->tracksessionip)) {
        if ($USER->sessionIP != md5(getremoteaddr())) {
            print_error('sessionipnomatch', 'error');
        }
    }
    /// Make sure the USER has a sesskey set up.  Used for checking script parameters.
    sesskey();
    // Check that the user has agreed to a site policy if there is one
    if (!empty($CFG->sitepolicy)) {
        if (!$USER->policyagreed) {
            $SESSION->wantsurl = $FULLME;
            redirect($CFG->wwwroot . '/user/policy.php');
        }
    }
    // Fetch the system context, we are going to use it a lot.
    $sysctx = get_context_instance(CONTEXT_SYSTEM);
    /// If the site is currently under maintenance, then print a message
    if (!has_capability('moodle/site:config', $sysctx)) {
        if (file_exists($CFG->dataroot . '/' . SITEID . '/maintenance.html')) {
            print_maintenance_message();
            exit;
        }
    }
    /// groupmembersonly access control
    if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
        if (isguestuser() or !groups_has_membership($cm)) {
            print_error('groupmembersonlyerror', 'group', $CFG->wwwroot . '/course/view.php?id=' . $cm->course);
        }
    }
    // Fetch the course context, and prefetch its child contexts
    if (!isset($COURSE->context)) {
        if (!($COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id))) {
            print_error('nocontext');
        }
    }
    if (!empty($cm) && !isset($cm->context)) {
        if (!($cm->context = get_context_instance(CONTEXT_MODULE, $cm->id))) {
            print_error('nocontext');
        }
    }
    if ($COURSE->id == SITEID) {
        /// Eliminate hidden site activities straight away
        if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
            redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
        }
        user_accesstime_log($COURSE->id);
        /// Access granted, update lastaccess times
        return;
    } else {
        /// Check if the user can be in a particular course
        if (empty($USER->access['rsw'][$COURSE->context->path])) {
            //
            // MDL-13900 - If the course or the parent category are hidden
            // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
            //
            if (!($COURSE->visible && course_parent_visible($COURSE)) && !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
                print_header_simple();
                notice(get_string('coursehidden'), $CFG->wwwroot . '/');
            }
        }
        /// Non-guests who don't currently have access, check if they can be allowed in as a guest
        if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
            if ($COURSE->guest == 1) {
                // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
                $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
            }
        }
        /// If the user is a guest then treat them according to the course policy about guests
        if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
            if (has_capability('moodle/site:doanything', $sysctx)) {
                // administrators must be able to access any course - even if somebody gives them guest access
                user_accesstime_log($COURSE->id);
                /// Access granted, update lastaccess times
                return;
            }
            switch ($COURSE->guest) {
                /// Check course policy about guest access
                case 1:
                    /// Guests always allowed
                    if (!has_capability('moodle/course:view', $COURSE->context)) {
                        // Prohibited by capability
                        print_header_simple();
                        notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "{$CFG->wwwroot}/login/index.php");
                    }
                    if (!empty($cm) and !$cm->visible) {
                        // Not allowed to see module, send to course page
                        redirect($CFG->wwwroot . '/course/view.php?id=' . $cm->course, get_string('activityiscurrentlyhidden'));
                    }
                    user_accesstime_log($COURSE->id);
                    /// Access granted, update lastaccess times
                    return;
                    // User is allowed to see this course
                    break;
                case 2:
                    /// Guests allowed with key
                    if (!empty($USER->enrolkey[$COURSE->id])) {
                        // Set by enrol/manual/enrol.php
                        user_accesstime_log($COURSE->id);
                        /// Access granted, update lastaccess times
                        return true;
                    }
                    //  otherwise drop through to logic below (--> enrol.php)
                    break;
                default:
                    /// Guests not allowed
                    $strloggedinasguest = get_string('loggedinasguest');
                    print_header_simple('', '', build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
                    if (empty($USER->access['rsw'][$COURSE->context->path])) {
                        // Normal guest
                        notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "{$CFG->wwwroot}/login/index.php");
                    } else {
                        notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
                        echo '<div class="notifyproblem">' . switchroles_form($COURSE->id) . '</div>';
                        print_footer($COURSE);
                        exit;
                    }
                    break;
            }
            /// For non-guests, check if they have course view access
        } else {
            if (has_capability('moodle/course:view', $COURSE->context)) {
                if (!empty($USER->realuser)) {
                    // Make sure the REAL person can also access this course
                    if (!has_capability('moodle/course:view', $COURSE->context, $USER->realuser)) {
                        print_header_simple();
                        notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot . '/');
                    }
                }
                /// Make sure they can read this activity too, if specified
                if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
                    redirect($CFG->wwwroot . '/course/view.php?id=' . $cm->course, get_string('activityiscurrentlyhidden'));
                }
                user_accesstime_log($COURSE->id);
                /// Access granted, update lastaccess times
                return;
                // User is allowed to see this course
            }
        }
        /// Currently not enrolled in the course, so see if they want to enrol
        $SESSION->wantsurl = $FULLME;
        redirect($CFG->wwwroot . '/course/enrol.php?id=' . $COURSE->id);
        die;
    }
}
Пример #8
0
$groupurl = new moodle_url('/group/overview.php', array('id' => $cm->course));
$overridedeleteurl = new moodle_url('/mod/quiz/overridedelete.php');
$overrideediturl = new moodle_url('/mod/quiz/overrideedit.php');
$hasinactive = false;
// Whether there are any inactive overrides.
foreach ($overrides as $override) {
    $fields = array();
    $values = array();
    $active = true;
    // Check for inactive overrides.
    if (!$groupmode) {
        if (!has_capability('mod/quiz:attempt', $context, $override->userid)) {
            // User not allowed to take the quiz.
            $active = false;
        } else {
            if (!empty($CFG->enablegroupmembersonly) && $cm->groupmembersonly && !groups_has_membership($cm, $override->userid)) {
                // User does not belong to the current grouping.
                $active = false;
            }
        }
    }
    // Format timeopen.
    if (isset($override->timeopen)) {
        $fields[] = get_string('quizopens', 'quiz');
        $values[] = $override->timeopen > 0 ? userdate($override->timeopen) : get_string('noopen', 'quiz');
    }
    // Format timeclose.
    if (isset($override->timeclose)) {
        $fields[] = get_string('quizcloses', 'quiz');
        $values[] = $override->timeclose > 0 ? userdate($override->timeclose) : get_string('noclose', 'quiz');
    }
Пример #9
0
function hotpot_is_visible(&$cm)
{
    global $CFG, $COURSE;
    // check grouping
    $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
    if (empty($CFG->enablegroupings) || empty($cm->groupmembersonly) || has_capability('moodle/site:accessallgroups', $modulecontext)) {
        // groupings not applicable
    } else {
        if (!isguestuser() && groups_has_membership($cm)) {
            // user is in one of the groups in the allowed grouping
        } else {
            // user is not in the required grouping and does not have sufficiently privileges to view this hotpot activity
            return false;
        }
    }
    // check if user can view hidden activities
    if (isset($COURSE->context)) {
        $coursecontext =& $COURSE->context;
    } else {
        $coursecontext = get_context_instance(CONTEXT_COURSE, $cm->course);
    }
    if (has_capability('moodle/course:viewhiddenactivities', $coursecontext)) {
        return true;
        // user can view hidden activities
    }
    if (!isset($cm->sectionvisible)) {
        if (!($section = get_record('course_sections', 'id', $cm->section))) {
            error('Course module record contains invalid section');
        }
        $cm->sectionvisible = $section->visible;
    }
    if (empty($cm->sectionvisible)) {
        $visible = HOTPOT_NO;
    } else {
        $visible = HOTPOT_YES;
        if (empty($cm->visible)) {
            if ($chain = hotpot_get_chain($cm)) {
                $startofchain = array_shift($chain);
                $visible = $startofchain->visible;
            }
        }
    }
    return $visible;
}
Пример #10
0
/**
 * Extends the global navigation tree by adding grouptool nodes if there is a relevant content
 *
 * This can be called by an AJAX request so do not rely on $PAGE as it might not be set up properly.
 *
 * @param navigation_node $navref Object representing the nav tree node of the grouptool mod instance
 * @param stdClass $course course object
 * @param stdClass $module module object
 * @param cm_info $cm cousre module info object
 */
function grouptool_extend_navigation(navigation_node $navref, stdClass $course, stdClass $module, cm_info $cm)
{
    global $DB;
    $context = context_module::instance($cm->id);
    $creategrps = has_capability('mod/grouptool:create_groups', $context);
    $creategrpgs = has_capability('mod/grouptool:create_groupings', $context);
    $admingrps = has_capability('mod/grouptool:administrate_groups', $context);
    if ($creategrps || $creategrpgs || $admingrps) {
        if ($creategrps && ($admingrps || $creategrpgs)) {
            $admin = $navref->add(get_string('administration', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'administration')));
            $admin->add(get_string('group_administration', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'group_admin')));
            $admin->add(get_string('group_creation', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'group_creation')));
        } else {
            if ($creategrps) {
                $navref->add(get_string('group_creation', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'group_creation')));
            } else {
                if ($creategrpgs || $admingrps) {
                    $navref->add(get_string('group_administration', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'group_admin')));
                }
            }
        }
    }
    if (has_capability('mod/grouptool:grade', $context) || has_capability('mod/grouptool:grade_own_group', $context)) {
        $navref->add(get_string('grading', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'grading')));
    }
    // Groupmode?
    $gmok = true;
    if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
        $gmok = $gmok && groups_has_membership($cm);
    }
    $gt = $DB->get_record('grouptool', array('id' => $cm->instance));
    $regopen = $gt->allow_reg && ($gt->timedue == 0 || time() < $gt->timedue) && $gt->timeavailable < time();
    if (has_capability('mod/grouptool:register_students', $context) || $regopen && $gmok && has_capability('mod/grouptool:register', $context)) {
        $tmp = $navref->add(get_string('selfregistration', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'selfregistration')));
    }
    if (has_capability('mod/grouptool:register_students', $context)) {
        $navref->add(get_string('import', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'import')));
    }
    if (has_capability('mod/grouptool:view_regs_course_view', $context) && has_capability('mod/grouptool:view_regs_group_view', $context)) {
        $userstab = $navref->add(get_string('users_tab', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'overview')));
        $userstab->add(get_string('overview_tab', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'overview')));
        $userstab->add(get_string('userlist_tab', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'userlist')));
    } else {
        if (has_capability('mod/grouptool:view_regs_group_view', $context)) {
            $navref->add(get_string('users_tab', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'overview')));
        } else {
            if (has_capability('mod/grouptool:view_regs_course_view', $context)) {
                $navref->add(get_string('users_tab', 'grouptool'), new moodle_url('/mod/grouptool/view.php', array('id' => $cm->id, 'tab' => 'userlist')));
            }
        }
    }
    $navref->nodetype = navigation_node::NODETYPE_BRANCH;
}
Пример #11
0
$hasinactive = false; // Whether there are any inactive overrides.

foreach ($overrides as $override) {

    $fields = array();
    $values = array();
    $active = true;

    // Check for inactive overrides.
    if (!$groupmode) {
        if (!has_capability('mod/quiz:attempt', $context, $override->userid)) {
            // User not allowed to take the quiz.
            $active = false;
        } else if (!empty($CFG->enablegroupmembersonly) && $cm->groupmembersonly &&
                !groups_has_membership($cm, $override->userid)) {
            // User does not belong to the current grouping.
            $active = false;
        }
    }

    // Format timeopen.
    if (isset($override->timeopen)) {
        $fields[] = get_string('quizopens', 'quiz');
        $values[] = $override->timeopen > 0 ?
                userdate($override->timeopen) : get_string('noopen', 'quiz');
    }

    // Format timeclose.
    if (isset($override->timeclose)) {
        $fields[] = get_string('quizcloses', 'quiz');
         $currentsessiongroupid = -1;
     }
     // all members of any group
     $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                    FROM " . $CFG->prefix . "questionnaire_response R,\n                        " . $CFG->prefix . "groups_members GM\n                     WHERE R.survey_id=" . $sid . " AND\n                       R.complete='y' AND\n                       GM.groupid>0 AND\n                       R.username=GM.userid\n                    ORDER BY R.id";
     if (!($respsallgroupmembers = get_records_sql($sql))) {
         $respsallgroupmembers = array();
     }
     $SESSION->questionnaire->numrespsallgroupmembers = count($respsallgroupmembers);
     // not members of any group
     $sql = "SELECT R.id, R.survey_id, R.submitted, R.username, U.id AS user\n                    FROM " . $CFG->prefix . "questionnaire_response R,\n                        " . $CFG->prefix . "user U\n                     WHERE R.survey_id=" . $sid . " AND\n                       R.complete='y' AND\n                       R.username=U.id\n                    ORDER BY user";
     if (!($respsnongroupmembers = get_records_sql($sql))) {
         $respsnongroupmembers = array();
     }
     foreach ($respsnongroupmembers as $resp => $key) {
         $userid = $key->user;
         if (groups_has_membership($cm, $userid)) {
             unset($respsnongroupmembers[$resp]);
         }
     }
     if (!$respsnongroupmembers) {
         $respsnongroupmembers = array();
     }
     $SESSION->questionnaire->numrespsnongroupmembers = count($respsnongroupmembers);
     // current group members
     $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                FROM " . $CFG->prefix . "questionnaire_response R,\n                    " . $CFG->prefix . "groups_members GM\n                 WHERE R.survey_id=" . $sid . " AND\n                   R.complete='y' AND\n                   GM.groupid=" . $currentgroupid . " AND\n                   R.username=GM.userid\n                ORDER BY R.id";
     if (!($currentgroupresps = get_records_sql($sql))) {
         $currentgroupresps = array();
     }
     $SESSION->questionnaire->numcurrentgroupresps = count($currentgroupresps);
 } else {
     //groupmode = separate groups but user is not member of any group
Пример #13
0
/**
 * This function checks that the current user is logged in and has the
 * required privileges
 *
 * This function checks that the current user is logged in, and optionally
 * whether they are allowed to be in a particular course and view a particular
 * course module.
 * If they are not logged in, then it redirects them to the site login unless
 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
 * case they are automatically logged in as guests.
 * If $courseid is given and the user is not enrolled in that course then the
 * user is redirected to the course enrolment page.
 * If $cm is given and the course module is hidden and the user is not a teacher
 * in the course then the user is redirected to the course home page.
 *
 * When $cm parameter specified, this function sets page layout to 'module'.
 * You need to change it manually later if some other layout needed.
 *
 * @param mixed $courseorid id of the course or course object
 * @param bool $autologinguest default true
 * @param object $cm course module object
 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
 *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
 *             in order to keep redirects working properly. MDL-14495
 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
 * @return mixed Void, exit, and die depending on path
 */
function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false)
{
    global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
    // setup global $COURSE, themes, language and locale
    if (!empty($courseorid)) {
        if (is_object($courseorid)) {
            $course = $courseorid;
        } else {
            if ($courseorid == SITEID) {
                $course = clone $SITE;
            } else {
                $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
            }
        }
        if ($cm) {
            if ($cm->course != $course->id) {
                throw new coding_exception('course and cm parameters in require_login() call do not match!!');
            }
            $PAGE->set_cm($cm, $course);
            // set's up global $COURSE
            $PAGE->set_pagelayout('incourse');
        } else {
            $PAGE->set_course($course);
            // set's up global $COURSE
        }
    } else {
        // do not touch global $COURSE via $PAGE->set_course(),
        // the reasons is we need to be able to call require_login() at any time!!
        $course = $SITE;
        if ($cm) {
            throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
        }
    }
    // If the user is not even logged in yet then make sure they are
    if (!isloggedin()) {
        if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
            if (!($guest = get_complete_user_data('id', $CFG->siteguest))) {
                // misconfigured site guest, just redirect to login page
                redirect(get_login_url());
                exit;
                // never reached
            }
            $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
            complete_user_login($guest, false);
            $USER->autologinguest = true;
            $SESSION->lang = $lang;
        } else {
            //NOTE: $USER->site check was obsoleted by session test cookie,
            //      $USER->confirmed test is in login/index.php
            if ($preventredirect) {
                throw new require_login_exception('You are not logged in');
            }
            if ($setwantsurltome) {
                // TODO: switch to PAGE->url
                $SESSION->wantsurl = $FULLME;
            }
            if (!empty($_SERVER['HTTP_REFERER'])) {
                $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
            }
            redirect(get_login_url());
            exit;
            // never reached
        }
    }
    // loginas as redirection if needed
    if ($course->id != SITEID and session_is_loggedinas()) {
        if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
            if ($USER->loginascontext->instanceid != $course->id) {
                print_error('loginasonecourse', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid);
            }
        }
    }
    // check whether the user should be changing password (but only if it is REALLY them)
    if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
        $userauth = get_auth_plugin($USER->auth);
        if ($userauth->can_change_password() and !$preventredirect) {
            $SESSION->wantsurl = $FULLME;
            if ($changeurl = $userauth->change_password_url()) {
                //use plugin custom url
                redirect($changeurl);
            } else {
                //use moodle internal method
                if (empty($CFG->loginhttps)) {
                    redirect($CFG->wwwroot . '/login/change_password.php');
                } else {
                    $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
                    redirect($wwwroot . '/login/change_password.php');
                }
            }
        } else {
            print_error('nopasswordchangeforced', 'auth');
        }
    }
    // Check that the user account is properly set up
    if (user_not_fully_set_up($USER)) {
        if ($preventredirect) {
            throw new require_login_exception('User not fully set-up');
        }
        $SESSION->wantsurl = $FULLME;
        redirect($CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&amp;course=' . SITEID);
    }
    // Make sure the USER has a sesskey set up. Used for CSRF protection.
    sesskey();
    // Do not bother admins with any formalities
    if (is_siteadmin()) {
        //set accesstime or the user will appear offline which messes up messaging
        user_accesstime_log($course->id);
        return;
    }
    // Check that the user has agreed to a site policy if there is one - do not test in case of admins
    if (!$USER->policyagreed and !is_siteadmin()) {
        if (!empty($CFG->sitepolicy) and !isguestuser()) {
            if ($preventredirect) {
                throw new require_login_exception('Policy not agreed');
            }
            $SESSION->wantsurl = $FULLME;
            redirect($CFG->wwwroot . '/user/policy.php');
        } else {
            if (!empty($CFG->sitepolicyguest) and isguestuser()) {
                if ($preventredirect) {
                    throw new require_login_exception('Policy not agreed');
                }
                $SESSION->wantsurl = $FULLME;
                redirect($CFG->wwwroot . '/user/policy.php');
            }
        }
    }
    // Fetch the system context, the course context, and prefetch its child contexts
    $sysctx = get_context_instance(CONTEXT_SYSTEM);
    $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
    if ($cm) {
        $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
    } else {
        $cmcontext = null;
    }
    // If the site is currently under maintenance, then print a message
    if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
        if ($preventredirect) {
            throw new require_login_exception('Maintenance in progress');
        }
        print_maintenance_message();
    }
    // make sure the course itself is not hidden
    if ($course->id == SITEID) {
        // frontpage can not be hidden
    } else {
        if (is_role_switched($course->id)) {
            // when switching roles ignore the hidden flag - user had to be in course to do the switch
        } else {
            if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
                // originally there was also test of parent category visibility,
                // BUT is was very slow in complex queries involving "my courses"
                // now it is also possible to simply hide all courses user is not enrolled in :-)
                if ($preventredirect) {
                    throw new require_login_exception('Course is hidden');
                }
                notice(get_string('coursehidden'), $CFG->wwwroot . '/');
            }
        }
    }
    // is the user enrolled?
    if ($course->id == SITEID) {
        // everybody is enrolled on the frontpage
    } else {
        if (session_is_loggedinas()) {
            // Make sure the REAL person can access this course first
            $realuser = session_get_realuser();
            if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
                if ($preventredirect) {
                    throw new require_login_exception('Invalid course login-as access');
                }
                echo $OUTPUT->header();
                notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot . '/');
            }
        }
        // very simple enrolment caching - changes in course setting are not reflected immediately
        if (!isset($USER->enrol)) {
            $USER->enrol = array();
            $USER->enrol['enrolled'] = array();
            $USER->enrol['tempguest'] = array();
        }
        $access = false;
        if (is_viewing($coursecontext, $USER)) {
            // ok, no need to mess with enrol
            $access = true;
        } else {
            if (isset($USER->enrol['enrolled'][$course->id])) {
                if ($USER->enrol['enrolled'][$course->id] == 0) {
                    $access = true;
                } else {
                    if ($USER->enrol['enrolled'][$course->id] > time()) {
                        $access = true;
                    } else {
                        //expired
                        unset($USER->enrol['enrolled'][$course->id]);
                    }
                }
            }
            if (isset($USER->enrol['tempguest'][$course->id])) {
                if ($USER->enrol['tempguest'][$course->id] == 0) {
                    $access = true;
                } else {
                    if ($USER->enrol['tempguest'][$course->id] > time()) {
                        $access = true;
                    } else {
                        //expired
                        unset($USER->enrol['tempguest'][$course->id]);
                        $USER->access = remove_temp_roles($coursecontext, $USER->access);
                    }
                }
            }
            if ($access) {
                // cache ok
            } else {
                if (is_enrolled($coursecontext, $USER, '', true)) {
                    // active participants may always access
                    // TODO: refactor this into some new function
                    $now = time();
                    $sql = "SELECT MAX(ue.timeend)\n                          FROM {user_enrolments} ue\n                          JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)\n                          JOIN {user} u ON u.id = ue.userid\n                         WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0\n                               AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
                    $params = array('enabled' => ENROL_INSTANCE_ENABLED, 'active' => ENROL_USER_ACTIVE, 'userid' => $USER->id, 'courseid' => $coursecontext->instanceid, 'now1' => $now, 'now2' => $now);
                    $until = $DB->get_field_sql($sql, $params);
                    if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) {
                        $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD;
                    }
                    $USER->enrol['enrolled'][$course->id] = $until;
                    $access = true;
                    // remove traces of previous temp guest access
                    $USER->access = remove_temp_roles($coursecontext, $USER->access);
                } else {
                    $instances = $DB->get_records('enrol', array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
                    $enrols = enrol_get_plugins(true);
                    // first ask all enabled enrol instances in course if they want to auto enrol user
                    foreach ($instances as $instance) {
                        if (!isset($enrols[$instance->enrol])) {
                            continue;
                        }
                        // Get a duration for the guestaccess, a timestamp in the future or false.
                        $until = $enrols[$instance->enrol]->try_autoenrol($instance);
                        if ($until !== false) {
                            $USER->enrol['enrolled'][$course->id] = $until;
                            $USER->access = remove_temp_roles($coursecontext, $USER->access);
                            $access = true;
                            break;
                        }
                    }
                    // if not enrolled yet try to gain temporary guest access
                    if (!$access) {
                        foreach ($instances as $instance) {
                            if (!isset($enrols[$instance->enrol])) {
                                continue;
                            }
                            // Get a duration for the guestaccess, a timestamp in the future or false.
                            $until = $enrols[$instance->enrol]->try_guestaccess($instance);
                            if ($until !== false) {
                                $USER->enrol['tempguest'][$course->id] = $until;
                                $access = true;
                                break;
                            }
                        }
                    }
                }
            }
        }
        if (!$access) {
            if ($preventredirect) {
                throw new require_login_exception('Not enrolled');
            }
            $SESSION->wantsurl = $FULLME;
            redirect($CFG->wwwroot . '/enrol/index.php?id=' . $course->id);
        }
    }
    // test visibility
    if ($cm && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
        if ($preventredirect) {
            throw new require_login_exception('Activity is hidden');
        }
        redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
    }
    // groupmembersonly access control
    if (!empty($CFG->enablegroupmembersonly) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
        if (isguestuser() or !groups_has_membership($cm)) {
            if ($preventredirect) {
                throw new require_login_exception('Not member of a group');
            }
            print_error('groupmembersonlyerror', 'group', $CFG->wwwroot . '/course/view.php?id=' . $cm->course);
        }
    }
    // Conditional activity access control
    if (!empty($CFG->enableavailability) and $cm) {
        // TODO: this is going to work with login-as-user, sorry!
        // We cache conditional access in session
        if (!isset($SESSION->conditionaccessok)) {
            $SESSION->conditionaccessok = array();
        }
        // If you have been allowed into the module once then you are allowed
        // in for rest of session, no need to do conditional checks
        if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
            // Get condition info (does a query for the availability table)
            require_once $CFG->libdir . '/conditionlib.php';
            $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
            // Check condition for user (this will do a query if the availability
            // information depends on grade or completion information)
            if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cmcontext)) {
                $SESSION->conditionaccessok[$cm->id] = true;
            } else {
                print_error('activityiscurrentlyhidden');
            }
        }
    }
    // Finally access granted, update lastaccess times
    user_accesstime_log($course->id);
}
 function generate_csv($rid = '', $userid = '')
 {
     global $CFG, $SESSION;
     if (isset($SESSION->questionnaire->currentgroupid)) {
         $groupid = $SESSION->questionnaire->currentgroupid;
     } else {
         $groupid = -1;
     }
     $output = array();
     $nbinfocols = 9;
     // change this if you want more info columns
     $stringother = get_string('other', 'questionnaire');
     $columns = array(get_string('response', 'questionnaire'), get_string('submitted', 'questionnaire'), get_string('institution'), get_string('department'), get_string('course'), get_string('group'), get_string('id', 'questionnaire'), get_string('fullname'), get_string('username'));
     $types = array(0, 0, 1, 1, 1, 1, 0, 1, 1);
     // get extra user_info_field columns names
     // 		$uifs = get_records('user_info_field');
     // 		foreach ($uifs as $uif) {
     // 			array_push($columns,$uif->shortname);
     // 			array_push($types,1);
     // 			$nbinfocols++;
     // 		}
     $arr = array();
     // 0 = number; 1 = text
     $id_to_csv_map = array('0', '0', '1', '1', '0', '0', '0', '0', '0', '1', '0');
     if (!($survey = get_record('questionnaire_survey', 'id', $this->survey->id))) {
         error(get_string('surveynotexists', 'questionnaire'));
     }
     $select = 'survey_id = ' . $this->survey->id . ' AND deleted = \'n\' AND type_id < 50';
     $fields = 'id,name,type_id,position';
     if (!($records = get_records_select('questionnaire_question', $select, 'position', $fields))) {
         $records = array();
     }
     global $CFG;
     $num = 1;
     foreach ($records as $record) {
         // establish the table's field names
         $qid = $record->id;
         $qpos = $record->position;
         if ($record->name == '') {
         }
         $col = $record->name;
         $type = $record->type_id;
         if ($type == 4 || $type == 5 || $type == 8) {
             /* single or multiple or rate */
             $sql = "SELECT c.id as cid, q.id as qid, q.precise AS precise, q.name, c.content\n                FROM " . $CFG->prefix . "questionnaire_question q " . 'LEFT JOIN ' . $CFG->prefix . "questionnaire_quest_choice c ON question_id = q.id " . 'WHERE q.id = ' . $qid . ' ORDER BY cid ASC';
             if (!($records2 = get_records_sql($sql))) {
                 $records2 = array();
             }
             $subqnum = 0;
             switch ($type) {
                 case 4:
                     // single
                     $columns[][$qpos] = $col;
                     array_push($types, $id_to_csv_map[$type]);
                     $thisnum = 1;
                     foreach ($records2 as $record2) {
                         $content = $record2->content;
                         if (ereg('^!other', $content)) {
                             $col = $record2->name . '_' . $stringother;
                             $columns[][$qpos] = $col;
                             array_push($types, '0');
                         }
                     }
                     break;
                 case 5:
                     // multiple
                     $thisnum = 1;
                     foreach ($records2 as $record2) {
                         $content = $record2->content;
                         $modality = '';
                         if (ereg('^!other', $content)) {
                             $content = $stringother;
                             $col = $record2->name . '->[' . $content . ']';
                             $columns[][$qpos] = $col;
                             array_push($types, '0');
                         }
                         $contents = choice_values($content);
                         if ($contents->modname) {
                             $modality = $contents->modname;
                         } elseif ($contents->title) {
                             $modality = $contents->title;
                         } else {
                             $modality = html_to_text($contents->text);
                         }
                         $col = $record2->name . '->' . $modality;
                         $columns[][$qpos] = $col;
                         array_push($types, '0');
                     }
                     break;
                 case 8:
                     // rate
                     foreach ($records2 as $record2) {
                         $nameddegrees = 0;
                         $modality = '';
                         $content = $record2->content;
                         $osgood = false;
                         if ($record2->precise == 3) {
                             $osgood = true;
                         }
                         if (ereg("^[0-9]{1,3}", $content, $ndd)) {
                             $nameddegrees++;
                         } else {
                             if ($osgood) {
                                 list($contentleft, $contentright) = split('[|]', $content);
                                 $contents = choice_values($contentleft);
                                 if ($contents->title) {
                                     $contentleft = $contents->title;
                                 }
                                 $contents = choice_values($contentright);
                                 if ($contents->title) {
                                     $contentright = $contents->title;
                                 }
                                 $modality = html_to_text($contentleft . '|' . $contentright);
                             } else {
                                 $contents = choice_values($content);
                                 if ($contents->modname) {
                                     $modality = $contents->modname;
                                 } elseif ($contents->title) {
                                     $modality = $contents->title;
                                 } else {
                                     $modality = html_to_text($contents->text);
                                     $modality = ereg_replace("[\r\n\t]", ' ', $modality);
                                 }
                             }
                             $col = $record2->name . '->' . $modality;
                             $columns[][$qpos] = $col;
                             array_push($types, $id_to_csv_map[$type]);
                         }
                     }
                     break;
             }
         } else {
             if (in_array($col, $columns)) {
                 $col = $col . $num;
             }
             $columns[][$qpos] = $col;
             array_push($types, $id_to_csv_map[$type]);
         }
         $num++;
     }
     array_push($output, $columns);
     $numcols = count($output[0]);
     if ($rid) {
         // send e-mail for a unique response ($rid)
         $select = 'survey_id = ' . $this->survey->id . ' AND complete=\'y\' AND id = ' . $rid;
         $fields = 'id,submitted,username';
         if (!($records = get_records_select('questionnaire_response', $select, 'submitted', $fields))) {
             $records = array();
         }
     } else {
         if ($userid) {
             // download CSV for one user's own responses'
             $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                          FROM " . $CFG->prefix . "questionnaire_response R\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y' AND\n                               R.username='******'\n                         ORDER BY R.id";
             if (!($records = get_records_sql($sql))) {
                 $records = array();
             }
         } else {
             // download CSV for all participants (or groups if enabled)
             if ($groupid == -1) {
                 // all participants
                 $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                          FROM " . $CFG->prefix . "questionnaire_response R\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y'\n                         ORDER BY R.id";
             } else {
                 if ($groupid == -2) {
                     // all members of any group
                     $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                          FROM " . $CFG->prefix . "questionnaire_response R,\n                                " . $CFG->prefix . "groups_members GM\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y' AND\n                               GM.groupid>0 AND\n                               R.username=GM.userid\n                         ORDER BY R.id";
                 } else {
                     if ($groupid == -3) {
                         // not members of any group
                         $sql = "SELECT R.id, R.survey_id, R.submitted,  U.id AS username\n                          FROM " . $CFG->prefix . "questionnaire_response R,\n                                " . $CFG->prefix . "user U\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y' AND\n                               R.username=U.id\n                         ORDER BY username";
                     } else {
                         // members of a specific group
                         $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                          FROM " . $CFG->prefix . "questionnaire_response R,\n                                " . $CFG->prefix . "groups_members GM\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y' AND\n                               GM.groupid=" . $groupid . " AND\n                               R.username=GM.userid\n                         ORDER BY R.id";
                     }
                 }
             }
             if (!($records = get_records_sql($sql))) {
                 $records = array();
             }
             if ($groupid == -3) {
                 // members of no group
                 foreach ($records as $row => $key) {
                     $userid = $key->username;
                     if (groups_has_membership($this->cm, $userid)) {
                         unset($records[$row]);
                     }
                 }
             }
         }
     }
     $isanonymous = $this->respondenttype == 'anonymous';
     foreach ($records as $record) {
         // get the response
         $response = $this->response_select_name($record->id);
         $qid = $record->id;
         //JR for better compabitility & readability with Excel
         $submitted = date(get_string('strfdateformatcsv', 'questionnaire'), $record->submitted);
         $institution = '';
         $department = '';
         $username = $record->username;
         if ($user = get_record('user', 'id', $username)) {
             $institution = $user->institution;
             $department = $user->department;
         }
         if ($isanonymous) {
             $username = get_string('anonymous', 'questionnaire');
         }
         /// Moodle:
         //  Get the course name that this questionnaire belongs to.
         if ($survey->realm != 'public') {
             $courseid = $this->course->id;
             $coursename = $this->course->fullname;
         } else {
             /// For a public questionnaire, look for the course that used it.
             $sql = 'SELECT q.id, q.course, c.fullname ' . 'FROM ' . $CFG->prefix . 'questionnaire q, ' . $CFG->prefix . 'questionnaire_attempts qa, ' . $CFG->prefix . 'course c ' . 'WHERE qa.rid = ' . $qid . ' AND q.id = qa.qid AND c.id = q.course';
             if ($record = get_record_sql($sql)) {
                 $courseid = $record->course;
                 $coursename = $record->fullname;
             } else {
                 $courseid = $this->course->id;
                 $coursename = $this->course->fullname;
             }
         }
         /// Moodle:
         //  If the username is numeric, try it as a Moodle user id.
         if (is_numeric($username)) {
             if ($user = get_record('user', 'id', $username)) {
                 $uid = $username;
                 $fullname = fullname($user);
                 $username = $user->username;
             } else {
                 $uid = '';
                 $fullname = get_string('anonymous', 'questionnaire');
                 $username = '';
             }
         } else {
             $uid = '';
             $fullname = get_string('anonymous', 'questionnaire');
             $username = '';
         }
         /// Moodle:
         //  Determine if the user is a member of a group in this course or not.
         $groupname = '';
         if ($this->cm->groupmode > 0) {
             if ($groupid > 0) {
                 $groupname = groups_get_group_name($groupid);
             } else {
                 if ($uid) {
                     if ($groups = groups_get_all_groups($courseid, $uid)) {
                         foreach ($groups as $group) {
                             $groupname .= $group->name . ', ';
                         }
                         $groupname = substr($groupname, 0, strlen($groupname) - 2);
                     } else {
                         $groupname = ' (' . get_string('groupnonmembers') . ')';
                     }
                 }
             }
         }
         $arr = array();
         array_push($arr, $qid);
         array_push($arr, $submitted);
         array_push($arr, $institution);
         array_push($arr, $department);
         array_push($arr, $coursename);
         array_push($arr, $groupname);
         array_push($arr, $uid);
         array_push($arr, $fullname);
         array_push($arr, $username);
         // get extra user_info_field user's data
         // 			$uifs = get_records('user_info_field');
         // 			foreach ($uifs as $uif) {
         // 				$tempuifd = get_field('user_info_data', 'data', 'userid', $record->username, 'fieldid', $uif->id);
         // 				array_push($arr,$tempuifd);
         // 				unset($tempuifd);
         // 			}
         // merge it
         for ($i = $nbinfocols; $i < $numcols; $i++) {
             /*if (isset($response[$columns[$i]]) && is_array($response[$columns[$i]])) {
                   $response[$columns[$i]] = join(',', $response[$columns[$i]]);
               }*/
             $qpos = key($columns[$i]);
             $qname = current($columns[$i]);
             if (isset($response[$qpos][$qname]) && $response[$qpos][$qname] != '') {
                 $thisresponse = $response[$qpos][$qname];
             } else {
                 $thisresponse = '';
             }
             switch ($types[$i]) {
                 case 1:
                     //string
                     // Excel seems to allow "\n" inside a quoted string, but
                     // "\r\n" is used as a record separator and so "\r" may
                     // not occur within a cell. So if one would like to preserve
                     // new-lines in a response, remove the "\n" from the
                     // regex below.
                     // email format text is plain text for being displayed in Excel, etc. added by JR
                     // but it must be stripped of carriage returns
                     if ($thisresponse) {
                         $thisresponse = format_text_email($thisresponse, FORMAT_HTML);
                         $thisresponse = ereg_replace("[\r\n\t]", ' ', $thisresponse);
                         $thisresponse = ereg_replace('"', '""', $thisresponse);
                     }
                     // fall through
                 // fall through
                 case 0:
                     //number
                     //array_push($arr,$thisresponse);
                     break;
             }
             array_push($arr, $thisresponse);
         }
         array_push($output, $arr);
     }
     // change table headers to incorporate actual question numbers
     $numcol = 0;
     $numquestion = 0;
     $out = '';
     $nbrespcols = count($output[0]);
     $oldkey = 0;
     for ($i = $nbinfocols; $i < $nbrespcols; $i++) {
         $sep = '';
         $thisoutput = current($output[0][$i]);
         $thiskey = key($output[0][$i]);
         // case of unnamed rate single possible answer (full stop char is used for support)
         if (strstr($thisoutput, '->.')) {
             $thisoutput = str_replace('->.', '', $thisoutput);
         }
         // if variable is not named no separator needed between Question number and potential sub-variables
         if ($thisoutput == '' || strstr($thisoutput, '->.') || substr($thisoutput, 0, 2) == '->' || substr($thisoutput, 0, 1) == '_') {
             $sep = '';
         } else {
             $sep = '_';
         }
         if ($thiskey > $oldkey) {
             $oldkey = $thiskey;
             $numquestion++;
         }
         // abbreviated modality name in multiple or rate questions (COLORS->blue=the color of the sky...)
         $pos = strpos($thisoutput, '=');
         if ($pos) {
             $thisoutput = substr($thisoutput, 0, $pos);
         }
         $other = $sep . $stringother;
         $out = 'Q' . sprintf("%02d", $numquestion) . $sep . $thisoutput;
         $output[0][$i] = $out;
     }
     return $output;
 }
Пример #15
0
/**
 * Adds module specific settings to the settings block
 *
 * @param settings_navigation $settings The settings navigation object
 * @param navigation_node $questionnairenode The node to add module settings to
 *
 * $settings is unused, but API requires it. Suppress PHPMD warning.
 *
 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 */
function questionnaire_extend_settings_navigation(settings_navigation $settings, navigation_node $questionnairenode)
{
    global $PAGE, $DB, $USER, $CFG;
    $individualresponse = optional_param('individualresponse', false, PARAM_INT);
    $rid = optional_param('rid', false, PARAM_INT);
    // Response id.
    $currentgroupid = optional_param('group', 0, PARAM_INT);
    // Group id.
    require_once $CFG->dirroot . '/mod/questionnaire/questionnaire.class.php';
    $context = $PAGE->cm->context;
    $cmid = $PAGE->cm->id;
    $cm = $PAGE->cm;
    $course = $PAGE->course;
    if (!($questionnaire = $DB->get_record("questionnaire", array("id" => $cm->instance)))) {
        print_error('invalidcoursemodule');
    }
    $courseid = $course->id;
    $questionnaire = new questionnaire(0, $questionnaire, $course, $cm);
    if ($owner = $DB->get_field('questionnaire_survey', 'owner', array('id' => $questionnaire->sid))) {
        $owner = trim($owner) == trim($courseid);
    } else {
        $owner = true;
    }
    // On view page, currentgroupid is not yet sent as an optional_param, so get it.
    $groupmode = groups_get_activity_groupmode($cm, $course);
    if ($groupmode > 0 && $currentgroupid == 0) {
        $currentgroupid = groups_get_activity_group($questionnaire->cm);
        if (!groups_is_member($currentgroupid, $USER->id)) {
            $currentgroupid = 0;
        }
    }
    // We want to add these new nodes after the Edit settings node, and before the
    // Locally assigned roles node. Of course, both of those are controlled by capabilities.
    $keys = $questionnairenode->get_children_key_list();
    $beforekey = null;
    $i = array_search('modedit', $keys);
    if ($i === false && array_key_exists(0, $keys)) {
        $beforekey = $keys[0];
    } else {
        if (array_key_exists($i + 1, $keys)) {
            $beforekey = $keys[$i + 1];
        }
    }
    if (has_capability('mod/questionnaire:manage', $context) && $owner) {
        $url = '/mod/questionnaire/qsettings.php';
        $node = navigation_node::create(get_string('advancedsettings'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'advancedsettings', new pix_icon('t/edit', ''));
        $questionnairenode->add_node($node, $beforekey);
    }
    if (has_capability('mod/questionnaire:editquestions', $context) && $owner) {
        $url = '/mod/questionnaire/questions.php';
        $node = navigation_node::create(get_string('questions', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'questions', new pix_icon('t/edit', ''));
        $questionnairenode->add_node($node, $beforekey);
    }
    if (has_capability('mod/questionnaire:preview', $context)) {
        $url = '/mod/questionnaire/preview.php';
        $node = navigation_node::create(get_string('preview_label', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'preview', new pix_icon('t/preview', ''));
        $questionnairenode->add_node($node, $beforekey);
    }
    if ($questionnaire->user_can_take($USER->id)) {
        $url = '/mod/questionnaire/complete.php';
        if ($questionnaire->user_has_saved_response($USER->id)) {
            $args = ['id' => $cmid, 'resume' => 1];
            $text = get_string('resumesurvey', 'questionnaire');
        } else {
            $args = ['id' => $cmid];
            $text = get_string('answerquestions', 'questionnaire');
        }
        $node = navigation_node::create($text, new moodle_url($url, $args), navigation_node::TYPE_SETTING, null, '', new pix_icon('i/info', 'answerquestions'));
        $questionnairenode->add_node($node, $beforekey);
    }
    $usernumresp = $questionnaire->count_submissions($USER->id);
    if ($questionnaire->capabilities->readownresponses && $usernumresp > 0) {
        $url = '/mod/questionnaire/myreport.php';
        if ($usernumresp > 1) {
            $urlargs = array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'summary', 'group' => $currentgroupid);
            $node = navigation_node::create(get_string('yourresponses', 'questionnaire'), new moodle_url($url, $urlargs), navigation_node::TYPE_SETTING, null, 'yourresponses');
            $myreportnode = $questionnairenode->add_node($node, $beforekey);
            $urlargs = array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'summary', 'group' => $currentgroupid);
            $myreportnode->add(get_string('summary', 'questionnaire'), new moodle_url($url, $urlargs));
            $urlargs = array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 1, 'action' => 'vresp', 'group' => $currentgroupid);
            $byresponsenode = $myreportnode->add(get_string('viewindividualresponse', 'questionnaire'), new moodle_url($url, $urlargs));
            $urlargs = array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 0, 'action' => 'vall', 'group' => $currentgroupid);
            $myreportnode->add(get_string('myresponses', 'questionnaire'), new moodle_url($url, $urlargs));
            if ($questionnaire->capabilities->downloadresponses) {
                $urlargs = array('instance' => $questionnaire->id, 'user' => $USER->id, 'action' => 'dwnpg', 'group' => $currentgroupid);
                $myreportnode->add(get_string('downloadtext'), new moodle_url('/mod/questionnaire/report.php', $urlargs));
            }
        } else {
            $urlargs = array('instance' => $questionnaire->id, 'userid' => $USER->id, 'byresponse' => 1, 'action' => 'vresp', 'group' => $currentgroupid);
            $node = navigation_node::create(get_string('yourresponse', 'questionnaire'), new moodle_url($url, $urlargs), navigation_node::TYPE_SETTING, null, 'yourresponse');
            $myreportnode = $questionnairenode->add_node($node, $beforekey);
        }
    }
    // If questionnaire is set to separate groups, prevent user who is not member of any group
    // and is not a non-editing teacher to view All responses.
    if ($questionnaire->can_view_all_responses($usernumresp)) {
        $url = '/mod/questionnaire/report.php';
        $node = navigation_node::create(get_string('viewallresponses', 'questionnaire'), new moodle_url($url, array('instance' => $questionnaire->id, 'action' => 'vall')), navigation_node::TYPE_SETTING, null, 'vall');
        $reportnode = $questionnairenode->add_node($node, $beforekey);
        if ($questionnaire->capabilities->viewsingleresponse) {
            $summarynode = $reportnode->add(get_string('summary', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vall')));
        } else {
            $summarynode = $reportnode;
        }
        $summarynode->add(get_string('order_default', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vall', 'group' => $currentgroupid)));
        $summarynode->add(get_string('order_ascending', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vallasort', 'group' => $currentgroupid)));
        $summarynode->add(get_string('order_descending', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vallarsort', 'group' => $currentgroupid)));
        if ($questionnaire->capabilities->deleteresponses) {
            $summarynode->add(get_string('deleteallresponses', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'delallresp', 'group' => $currentgroupid)));
        }
        if ($questionnaire->capabilities->downloadresponses) {
            $summarynode->add(get_string('downloadtextformat', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'dwnpg', 'group' => $currentgroupid)));
        }
        if ($questionnaire->capabilities->viewsingleresponse) {
            $byresponsenode = $reportnode->add(get_string('viewbyresponse', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vresp', 'byresponse' => 1, 'group' => $currentgroupid)));
            $byresponsenode->add(get_string('view', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'vresp', 'byresponse' => 1, 'group' => $currentgroupid)));
            if ($individualresponse) {
                $byresponsenode->add(get_string('deleteresp', 'questionnaire'), new moodle_url('/mod/questionnaire/report.php', array('instance' => $questionnaire->id, 'action' => 'dresp', 'byresponse' => 1, 'rid' => $rid, 'group' => $currentgroupid, 'individualresponse' => 1)));
            }
        }
    }
    $canviewgroups = true;
    $groupmode = groups_get_activity_groupmode($cm, $course);
    if ($groupmode == 1) {
        $canviewgroups = groups_has_membership($cm, $USER->id);
    }
    $canviewallgroups = has_capability('moodle/site:accessallgroups', $context);
    if ($questionnaire->capabilities->viewsingleresponse && ($canviewallgroups || $canviewgroups)) {
        $url = '/mod/questionnaire/show_nonrespondents.php';
        $node = navigation_node::create(get_string('show_nonrespondents', 'questionnaire'), new moodle_url($url, array('id' => $cmid)), navigation_node::TYPE_SETTING, null, 'nonrespondents');
        $questionnairenode->add_node($node, $beforekey);
    }
}
Пример #16
0
 /**
  * Checks if two users are in the same Moodle group, returns true if:
  *  - mode is "no groups"
  *  - mode is "visible groups"
  *  - mode is "separate groups" and users are in the same group
  *
  * @param int $userid1 Moodle user ID of user 1
  * @param int $userid2 Moodle user ID of user 2
  *
  * @return boolean see method description
  */
 public static function checkSameGroup($userid1, $userid2)
 {
     global $CFG, $course, $cm;
     if (!$userid1 || !$userid2) {
         // make sure we have two actual user ID's
         return false;
     }
     require_once $CFG->dirroot . '/group/lib.php';
     $groupmode = groups_get_activity_groupmode($cm, $course);
     if ($groupmode == NOGROUPS) {
         // activity mode is "no groups", so people can't be in the same group
         return false;
     } else {
         if ($groupmode == VISIBLEGROUPS) {
             // Impossible to restrict to not use this particular setting in course AJAX editing, so if VISIBLEGROUPS is set, everyone sees everything.
             return true;
         } else {
             if ($groupmode == SEPARATEGROUPS) {
                 if (!groups_has_membership($cm, $userid1)) {
                     return false;
                 }
                 $groups_user1 = groups_get_all_groups($course->id, $userid1);
                 foreach ($groups_user1 as $group_user1) {
                     if (groups_is_member($group_user1->id, $userid2)) {
                         return true;
                     }
                 }
             }
         }
     }
     return false;
 }