public function get_content()
 {
     global $COURSE, $USER;
     if ($this->content !== null) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->text = var_export($this->context, true);
     $coursecontext = context_course::instance($COURSE->id);
     if (has_capability('block/demostudent:addinstance', $coursecontext)) {
         // If DemoStudent has not yet been enrolled, allow user to create/enrol one.
         $demostudentusername = generate_demostudent_name($USER->username);
         $demostudentuser = get_complete_user_data('username', $demostudentusername);
         if (!$demostudentuser || !is_enrolled($coursecontext, $demostudentuser)) {
             $this->render_view('firstuse');
         } else {
             $this->render_view('instructor');
         }
     } else {
         if (has_capability('block/demostudent:seedemostudentblock', $coursecontext)) {
             $this->render_view('demostudent');
         } else {
             // If the user does not need to see the block, do not display it at all.
             $this->content->text = '';
             $this->content->footer = '';
         }
     }
     return $this->content;
 }
Exemplo n.º 2
0
/**
 * Add a "Compile" menu link to the Course Admin block as the top link.
 *
 * @author Gerald Albion
 * date 2014-10-31
 * @copyright 2014 Royal Roads University
 * @param object $settingsnav Main navigation object.
 * @param object $context Course context.
 */
function local_compile_extends_settings_navigation($settingsnav, $context)
{
    // Context must be course.
    if ($context->contextlevel != CONTEXT_COURSE) {
        return;
    }
    // Must be in a valid course: Cannot be course id 0.
    if ($context->instanceid == 0) {
        return;
    }
    // Must be in a valid course: Course must be retrievable.
    if (!($course = get_course($context->instanceid))) {
        return;
    }
    // Must be enrolled or otherwise allowed to view the course.
    if (!(is_enrolled($context) || is_viewing($context))) {
        return;
    }
    // Must have a course admin menu in which to add link.
    if (!($coursenode = $settingsnav->find('courseadmin', navigation_node::TYPE_COURSE))) {
        return;
    }
    // Good to go.  Build the menu item.
    $url = new moodle_url('/local/compile/list_modules.php', array('id' => $course->id));
    $newnode = navigation_node::create(get_string('menucaption', 'local_compile'), $url, navigation_node::NODETYPE_LEAF, 'compile', 'compile', new pix_icon('i/settings', ''));
    // We want to put this link at the top: find the existing top (first) node.
    $firstnode = $coursenode->get_children_key_list()[0];
    // Add the menu item to the menu, before the first node.
    $coursenode->add_node($newnode, $firstnode);
}
Exemplo n.º 3
0
 /**
  * Return information about this specific context level
  *
  * @param $component
  * @param $filearea
  * @param $itemid
  * @param $filepath
  * @param $filename
  */
 public function get_file_info($component, $filearea, $itemid, $filepath, $filename)
 {
     if (!is_enrolled($this->context) and !is_viewing($this->context)) {
         // no peaking here if not enrolled or inspector
         return null;
     }
     if (empty($component)) {
         return $this;
     }
     if ($component == 'mod_' . $this->modname and $filearea === 'intro') {
         return $this->get_area_intro($itemid, $filepath, $filename);
     } else {
         if ($component == 'backup' and $filearea === 'activity') {
             return $this->get_area_backup($itemid, $filepath, $filename);
         }
     }
     $functionname = 'mod_' . $this->modname . '_get_file_info';
     $functionname_old = $this->modname . '_get_file_info';
     if (function_exists($functionname)) {
         return $functionname($this->browser, $this->areas, $this->course, $this->cm, $this->context, $filearea, $itemid, $filepath, $filename);
     } else {
         if (function_exists($functionname_old)) {
             return $functionname_old($this->browser, $this->areas, $this->course, $this->cm, $this->context, $filearea, $itemid, $filepath, $filename);
         }
     }
     return null;
 }
 /**
  * Test get_enrolled_users
  */
 public function test_enrol_users()
 {
     global $DB;
     $this->resetAfterTest(true);
     $user = self::getDataGenerator()->create_user();
     $this->setUser($user);
     $course1 = self::getDataGenerator()->create_course();
     $course2 = self::getDataGenerator()->create_course();
     $user1 = self::getDataGenerator()->create_user();
     $user2 = self::getDataGenerator()->create_user();
     $context1 = context_course::instance($course1->id);
     $context2 = context_course::instance($course2->id);
     $instance1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'manual'), '*', MUST_EXIST);
     $instance2 = $DB->get_record('enrol', array('courseid' => $course2->id, 'enrol' => 'manual'), '*', MUST_EXIST);
     // Set the required capabilities by the external function.
     $roleid = $this->assignUserCapability('enrol/manual:enrol', $context1->id);
     $this->assignUserCapability('moodle/course:view', $context1->id, $roleid);
     $this->assignUserCapability('moodle/role:assign', $context1->id, $roleid);
     $this->assignUserCapability('enrol/manual:enrol', $context2->id, $roleid);
     $this->assignUserCapability('moodle/course:view', $context2->id, $roleid);
     $this->assignUserCapability('moodle/role:assign', $context2->id, $roleid);
     allow_assign($roleid, 3);
     // Call the external function.
     enrol_manual_external::enrol_users(array(array('roleid' => 3, 'userid' => $user1->id, 'courseid' => $course1->id), array('roleid' => 3, 'userid' => $user2->id, 'courseid' => $course1->id)));
     $this->assertEquals(2, $DB->count_records('user_enrolments', array('enrolid' => $instance1->id)));
     $this->assertEquals(0, $DB->count_records('user_enrolments', array('enrolid' => $instance2->id)));
     $this->assertTrue(is_enrolled($context1, $user1));
     $this->assertTrue(is_enrolled($context1, $user2));
     // Call without required capability.
     $DB->delete_records('user_enrolments');
     $this->unassignUserCapability('enrol/manual:enrol', $context1->id, $roleid);
     try {
         enrol_manual_external::enrol_users(array(array('roleid' => 3, 'userid' => $user1->id, 'courseid' => $course1->id)));
         $this->fail('Exception expected if not having capability to enrol');
     } catch (moodle_exception $e) {
         $this->assertInstanceOf('required_capability_exception', $e);
         $this->assertSame('nopermissions', $e->errorcode);
     }
     $this->assignUserCapability('enrol/manual:enrol', $context1->id, $roleid);
     $this->assertEquals(0, $DB->count_records('user_enrolments'));
     // Call with forbidden role.
     try {
         enrol_manual_external::enrol_users(array(array('roleid' => 1, 'userid' => $user1->id, 'courseid' => $course1->id)));
         $this->fail('Exception expected if not allowed to assign role.');
     } catch (moodle_exception $e) {
         $this->assertSame('wsusercannotassign', $e->errorcode);
     }
     $this->assertEquals(0, $DB->count_records('user_enrolments'));
     // Call for course without manual instance.
     $DB->delete_records('user_enrolments');
     $DB->delete_records('enrol', array('courseid' => $course2->id));
     try {
         enrol_manual_external::enrol_users(array(array('roleid' => 3, 'userid' => $user1->id, 'courseid' => $course1->id), array('roleid' => 3, 'userid' => $user1->id, 'courseid' => $course2->id)));
         $this->fail('Exception expected if course does not have manual instance');
     } catch (moodle_exception $e) {
         $this->assertSame('wsnoinstance', $e->errorcode);
     }
 }
Exemplo n.º 5
0
 function execute($userid, $context, $data)
 {
     global $DB, $CFG;
     // Everyone should be enrolled at the system level.
     if ($context == context_system::instance()) {
         return true;
     }
     return is_enrolled($context, $userid);
 }
Exemplo n.º 6
0
/**
 * Adds a specified user to a group
 *
 * @param mixed $grouporid  The group id or group object
 * @param mixed $userorid   The user id or user object
 * @param string $component Optional component name e.g. 'enrol_imsenterprise'
 * @param int $itemid Optional itemid associated with component
 * @return bool True if user added successfully or the user is already a
 * member of the group, false otherwise.
 */
function groups_add_member($grouporid, $userorid, $component = null, $itemid = 0)
{
    global $DB;
    if (is_object($userorid)) {
        $userid = $userorid->id;
        $user = $userorid;
    } else {
        $userid = $userorid;
        $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
    }
    if (is_object($grouporid)) {
        $groupid = $grouporid->id;
        $group = $grouporid;
    } else {
        $groupid = $grouporid;
        $group = $DB->get_record('groups', array('id' => $groupid), '*', MUST_EXIST);
    }
    //check if the user a participant of the group course
    if (!is_enrolled(context_course::instance($group->courseid), $userid)) {
        return false;
    }
    if (groups_is_member($groupid, $userid)) {
        return true;
    }
    $member = new stdClass();
    $member->groupid = $groupid;
    $member->userid = $userid;
    $member->timeadded = time();
    $member->component = '';
    $member->itemid = 0;
    // Check the component exists if specified
    if (!empty($component)) {
        $dir = get_component_directory($component);
        if ($dir && is_dir($dir)) {
            // Component exists and can be used
            $member->component = $component;
            $member->itemid = $itemid;
        } else {
            throw new coding_exception('Invalid call to groups_add_member(). An invalid component was specified');
        }
    }
    if ($itemid !== 0 && empty($member->component)) {
        // An itemid can only be specified if a valid component was found
        throw new coding_exception('Invalid call to groups_add_member(). A component must be specified if an itemid is given');
    }
    $DB->insert_record('groups_members', $member);
    //update group info
    $DB->set_field('groups', 'timemodified', $member->timeadded, array('id' => $groupid));
    //trigger groups events
    $eventdata = new stdClass();
    $eventdata->groupid = $groupid;
    $eventdata->userid = $userid;
    $eventdata->component = $member->component;
    $eventdata->itemid = $member->itemid;
    events_trigger('groups_member_added', $eventdata);
    return true;
}
Exemplo n.º 7
0
 /**
  * Loads the data required to render the report.
  *
  * @param int $courseid The course id
  * @param int $userid The user id
  * @return \stdClass
  */
 public static function data_for_report($courseid, $userid)
 {
     global $PAGE;
     $params = self::validate_parameters(self::data_for_report_parameters(), array('courseid' => $courseid, 'userid' => $userid));
     $context = context_course::instance($params['courseid']);
     self::validate_context($context);
     if (!is_enrolled($context, $params['userid'], 'moodle/competency:coursecompetencygradable')) {
         throw new coding_exception('invaliduser');
     }
     $renderable = new output\report($params['courseid'], $params['userid']);
     $renderer = $PAGE->get_renderer('report_competency');
     $data = $renderable->export_for_template($renderer);
     return $data;
 }
 public function is_available($not, \core_availability\info $info, $grabthelot, $userid)
 {
     $allow = true;
     if ($this->expectedpublicprivate == PUBLICPRIVATE_PRIVATE) {
         $modinfo = $info->get_modinfo();
         $course = $modinfo->get_course();
         $context = \context_course::instance($course->id);
         $allow = is_enrolled($context, $userid, '', true) || has_capability('moodle/course:view', $context);
     }
     if ($not) {
         $allow = !$allow;
     }
     return $allow;
 }
Exemplo n.º 9
0
/**
 * Adds a specified user to a group
 *
 * @param mixed $grouporid  The group id or group object
 * @param mixed $userorid   The user id or user object
 * @return bool True if user added successfully or the user is already a
 * member of the group, false otherwise.
 */
function groups_add_member($grouporid, $userorid) {
    global $DB;

    if (is_object($userorid)) {
        $userid = $userorid->id;
        $user   = $userorid;
    } else {
        $userid = $userorid;
        $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
    }

    if (is_object($grouporid)) {
        $groupid = $grouporid->id;
        $group   = $grouporid;
    } else {
        $groupid = $grouporid;
        $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
    }

    //check if the user a participant of the group course
    if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $group->courseid), $userid)) {
        return false;
    }

    if (groups_is_member($groupid, $userid)) {
        return true;
    }

    $member = new stdClass();
    $member->groupid   = $groupid;
    $member->userid    = $userid;
    $member->timeadded = time();

    $DB->insert_record('groups_members', $member);

    //update group info
    $DB->set_field('groups', 'timemodified', $member->timeadded, array('id'=>$groupid));

    //trigger groups events
    $eventdata = new stdClass();
    $eventdata->groupid = $groupid;
    $eventdata->userid  = $userid;
    events_trigger('groups_member_added', $eventdata);

    return true;
}
Exemplo n.º 10
0
function block_csv_enrol_enrol_users($courseid, $csvcontent)
{
    global $DB, $CFG;
    require_once $CFG->libdir . '/enrollib.php';
    //get enrolment instance (manual and student)
    $instances = enrol_get_instances($courseid, false);
    $enrolment = "";
    foreach ($instances as $instance) {
        if ($instance->enrol === 'manual') {
            $enrolment = $instance;
            break;
        }
    }
    //get enrolment plugin
    $manual = enrol_get_plugin('manual');
    $context = get_context_instance(CONTEXT_COURSE, $courseid);
    $stats = new StdClass();
    $stats->success = $stats->failed = 0;
    //init counters
    $log = get_string('enrolling', 'block_csv_enrol') . "\r\n";
    $lines = explode("\n", $csvcontent);
    foreach ($lines as $line) {
        if ($line == "") {
            continue;
        }
        $user = $DB->get_record('user', array('email' => trim($line)));
        if ($user && !$user->deleted) {
            if (is_enrolled($context, $user)) {
                $log .= get_string('enrollinguser', 'block_csv_enrol', fullname($user) . ' (' . $user->username . ')') . "\r\n";
            } else {
                $log .= get_string('alreadyenrolled', 'block_csv_enrol', fullname($user) . ' (' . $user->username . ')') . "\r\n";
                $manual->enrol_user($enrolment, $user->id, $enrolment->roleid, time());
            }
            $stats->success++;
        } else {
            $log .= get_string('emailnotfound', 'block_csv_enrol', trim($line)) . "\r\n";
            $stats->failed++;
        }
    }
    $log .= get_string('done', 'block_csv_enrol') . "\r\n";
    $log = get_string('status', 'block_csv_enrol', $stats) . ' ' . get_string('enrolmentlog', 'block_csv_enrol') . "\r\n\r\n" . $log;
    return $log;
}
 /**
  * Return information about this specific context level
  *
  * @param $component
  * @param $filearea
  * @param $itemid
  * @param $filepath
  * @param $filename
  */
 public function get_file_info($component, $filearea, $itemid, $filepath, $filename)
 {
     // try to emulate require_login() tests here
     if (!isloggedin()) {
         return null;
     }
     $coursecontext = get_course_context($this->context);
     if (!$this->course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
         return null;
     }
     if (!is_viewing($this->context) and !is_enrolled($this->context)) {
         // no peaking here if not enrolled or inspector
         return null;
     }
     $modinfo = get_fast_modinfo($this->course);
     $cminfo = $modinfo->get_cm($this->cm->id);
     if (!$cminfo->uservisible) {
         // activity hidden sorry
         return null;
     }
     if (empty($component)) {
         return $this;
     }
     if ($component == 'mod_' . $this->modname and $filearea === 'intro') {
         return $this->get_area_intro($itemid, $filepath, $filename);
     } else {
         if ($component == 'backup' and $filearea === 'activity') {
             return $this->get_area_backup($itemid, $filepath, $filename);
         }
     }
     $functionname = 'mod_' . $this->modname . '_get_file_info';
     $functionname_old = $this->modname . '_get_file_info';
     if (function_exists($functionname)) {
         return $functionname($this->browser, $this->areas, $this->course, $this->cm, $this->context, $filearea, $itemid, $filepath, $filename);
     } else {
         if (function_exists($functionname_old)) {
             return $functionname_old($this->browser, $this->areas, $this->course, $this->cm, $this->context, $filearea, $itemid, $filepath, $filename);
         }
     }
     return null;
 }
Exemplo n.º 12
0
/**
 * Is current user allowed to access this report
 *
 * @private defined in lib.php for performance reasons
 *
 * @param stdClass $user
 * @param stdClass $course
 * @return bool
 */
function report_outline_can_access_user_report($user, $course)
{
    global $USER;
    $coursecontext = context_course::instance($course->id);
    $personalcontext = context_user::instance($user->id);
    if (has_capability('report/outline:view', $coursecontext)) {
        return true;
    }
    if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
        if ($course->showreports and (is_viewing($coursecontext, $user) or is_enrolled($coursecontext, $user))) {
            return true;
        }
    } else {
        if ($user->id == $USER->id) {
            if ($course->showreports and (is_viewing($coursecontext, $USER) or is_enrolled($coursecontext, $USER))) {
                return true;
            }
        }
    }
    return false;
}
Exemplo n.º 13
0
 /**
  * Return information about this specific context level
  *
  * @param string $component component
  * @param string $filearea file area
  * @param int $itemid item ID
  * @param string $filepath file path
  * @param string $filename file name
  * @return file_info|null file_info instance or null if not found or access not allowed
  */
 public function get_file_info($component, $filearea, $itemid, $filepath, $filename)
 {
     // try to emulate require_login() tests here
     if (!isloggedin()) {
         return null;
     }
     if (!$this->course->visible and !has_capability('moodle/course:viewhiddencourses', $this->context)) {
         return null;
     }
     if (!is_viewing($this->context) and !is_enrolled($this->context)) {
         // no peaking here if not enrolled or inspector
         return null;
     }
     if (empty($component)) {
         return $this;
     }
     $methodname = "get_area_{$component}_{$filearea}";
     if (method_exists($this, $methodname)) {
         return $this->{$methodname}($itemid, $filepath, $filename);
     }
     return null;
 }
Exemplo n.º 14
0
             if ($duration > 0) {
                 // sanity check
                 $timeend = $today + $duration;
             }
         }
         $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend);
         $a = new stdClass();
         $a->course = $shortname;
         $a->role = $rolecache[$rid]->name;
         $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
     }
 }
 // find group to add to
 if (!empty($user->{'group' . $i})) {
     // make sure user is enrolled into course before adding into groups
     if (!is_enrolled($coursecontext, $user->id)) {
         $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group' . $i}), 'error');
         continue;
     }
     //build group cache
     if (is_null($ccache[$shortname]->groups)) {
         $ccache[$shortname]->groups = array();
         if ($groups = groups_get_all_groups($courseid)) {
             foreach ($groups as $gid => $group) {
                 $ccache[$shortname]->groups[$gid] = new stdClass();
                 $ccache[$shortname]->groups[$gid]->id = $gid;
                 $ccache[$shortname]->groups[$gid]->name = $group->name;
                 if (!is_numeric($group->name)) {
                     // only non-numeric names are supported!!!
                     $ccache[$shortname]->groups[$group->name] = new stdClass();
                     $ccache[$shortname]->groups[$group->name]->id = $gid;
Exemplo n.º 15
0
$digestoptions = forum_get_user_digest_options();
$digestoptions_selector = new single_select(new moodle_url('/mod/forum/maildigest.php', array('backtoindex' => 1)), 'maildigest', $digestoptions, null, '');
$digestoptions_selector->method = 'post';
// Start of the table for General Forums
$generaltable = new html_table();
$generaltable->head = array($strforum, $strdescription, $strdiscussions);
$generaltable->align = array('left', 'left', 'center');
if ($usetracking = forum_tp_can_track_forums()) {
    $untracked = forum_tp_get_untracked_forums($USER->id, $course->id);
    $generaltable->head[] = $strunreadposts;
    $generaltable->align[] = 'center';
    $generaltable->head[] = $strtracking;
    $generaltable->align[] = 'center';
}
$subscribed_forums = forum_get_subscribed_forums($course);
$can_subscribe = is_enrolled($coursecontext);
if ($can_subscribe) {
    $generaltable->head[] = $strsubscribed;
    $generaltable->align[] = 'center';
    $generaltable->head[] = $stremaildigest . ' ' . $OUTPUT->help_icon('emaildigesttype', 'mod_forum');
    $generaltable->align[] = 'center';
}
if ($show_rss = ($can_subscribe || $course->id == SITEID) && isset($CFG->enablerssfeeds) && isset($CFG->forum_enablerssfeeds) && $CFG->enablerssfeeds && $CFG->forum_enablerssfeeds) {
    $generaltable->head[] = $strrss;
    $generaltable->align[] = 'center';
}
$usesections = course_format_uses_sections($course->format);
$table = new html_table();
// Parse and organise all the forums.  Most forums are course modules but
// some special ones are not.  These get placed in the general forums
// category with the forums in section 0.
Exemplo n.º 16
0
if ((!$current or $choice->allowupdate) and $choiceopen and is_enrolled($context, NULL, 'mod/choice:choose')) {
    // They haven't made their choice yet or updates allowed and choice is open
    $options = choice_prepare_options($choice, $USER, $cm, $allresponses);
    $renderer = $PAGE->get_renderer('mod_choice');
    echo $renderer->display_options($options, $cm->id, $choice->display, $choice->allowmultiple);
    $choiceformshown = true;
} else {
    $choiceformshown = false;
}
if (!$choiceformshown) {
    $sitecontext = context_system::instance();
    if (isguestuser()) {
        // Guest account
        echo $OUTPUT->confirm(get_string('noguestchoose', 'choice') . '<br /><br />' . get_string('liketologin'), get_login_url(), new moodle_url('/course/view.php', array('id' => $course->id)));
    } else {
        if (!is_enrolled($context)) {
            // Only people enrolled can make a choice
            $SESSION->wantsurl = qualified_me();
            $SESSION->enrolcancel = get_local_referer(false);
            $coursecontext = context_course::instance($course->id);
            $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
            echo $OUTPUT->box_start('generalbox', 'notice');
            echo '<p align="center">' . get_string('notenrolledchoose', 'choice') . '</p>';
            echo $OUTPUT->container_start('continuebutton');
            echo $OUTPUT->single_button(new moodle_url('/enrol/index.php?', array('id' => $course->id)), get_string('enrolme', 'core_enrol', $courseshortname));
            echo $OUTPUT->container_end();
            echo $OUTPUT->box_end();
        }
    }
}
// print the results at the bottom of the screen
Exemplo n.º 17
0
    $node->add(format_string($post->subject), $PAGE->url);
}
$PAGE->set_title("{$course->shortname}: " . format_string($discussion->name));
$PAGE->set_heading($course->fullname);
$PAGE->set_button($searchform);
echo $OUTPUT->header();
echo $OUTPUT->heading(format_string($forum->name), 2);
/// Check to see if groups are being used in this forum
/// If so, make sure the current person is allowed to see this discussion
/// Also, if we know they should be able to reply, then explicitly set $canreply for performance reasons
$canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
if (!$canreply and $forum->type !== 'news') {
    if (isguestuser() or !isloggedin()) {
        $canreply = true;
    }
    if (!is_enrolled($modcontext) and !is_viewing($modcontext)) {
        // allow guests and not-logged-in to see the link - they are prompted to log in after clicking the link
        // normal users with temporary guest access see this link too, they are asked to enrol instead
        $canreply = enrol_selfenrol_available($course->id);
    }
}
/// Print the controls across the top
echo '<div class="discussioncontrols clearfix">';
if (!empty($CFG->enableportfolios) && has_capability('mod/forum:exportdiscussion', $modcontext)) {
    require_once $CFG->libdir . '/portfoliolib.php';
    $button = new portfolio_add_button();
    $button->set_callback_options('forum_portfolio_caller', array('discussionid' => $discussion->id), 'mod_forum');
    $button = $button->to_html(PORTFOLIO_ADD_FULL_FORM, get_string('exportdiscussion', 'mod_forum'));
    $buttonextraclass = '';
    if (empty($button)) {
        // no portfolio plugin available.
Exemplo n.º 18
0
 protected function define_execution()
 {
     global $CFG, $DB;
     if (!($userid = $this->task->get_userid())) {
         return;
     }
     if (empty($CFG->restorernewroleid)) {
         // Bad luck, no fallback role for restorers specified
         return;
     }
     $courseid = $this->get_courseid();
     $context = context_course::instance($courseid);
     if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
         // Current user may access the course (admin, category manager or restored teacher enrolment usually)
         return;
     }
     // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
     role_assign($CFG->restorernewroleid, $userid, $context);
     if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
         // Extra role is enough, yay!
         return;
     }
     // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
     // hopefully admin selected suitable $CFG->restorernewroleid ...
     if (!enrol_is_enabled('manual')) {
         return;
     }
     if (!($enrol = enrol_get_plugin('manual'))) {
         return;
     }
     if (!$DB->record_exists('enrol', array('enrol' => 'manual', 'courseid' => $courseid))) {
         $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
         $fields = array('status' => ENROL_INSTANCE_ENABLED, 'enrolperiod' => $enrol->get_config('enrolperiod', 0), 'roleid' => $enrol->get_config('roleid', 0));
         $enrol->add_instance($course, $fields);
     }
     enrol_try_internal_enrol($courseid, $userid);
 }
Exemplo n.º 19
0
    /**
     * Parse moss result page and store to DB
     *
     * @param string $url moss result page url
     * @param int $configid
     * @return true or false
     */
    protected function save_results($url, $configid) {
        global $DB, $UNITTEST;

        mtrace("\tProcessing $url");

        if (!$result_page = download_file_content($url)) {
            mtrace("\tcan not read $url");
            return false;
        }

        preg_match_all(
            '/(?P<link>http:\/\/moss\.stanford\.edu\/results\/\d+\/match\d+\.html)">.+\/(?P<user1>\d+)\/ \((?P<percentage1>\d+)%\).+\/(?P<user2>\d+)\/ \((?P<percentage2>\d+)%\).+right>(?P<linesmatched>\d+)\\n/Us',
            $result_page,
            $matches,
            PREG_SET_ORDER
        );

        if (empty($matches)) {
            mtrace("\tcan not parse $url");
            return false;
        }

        if (!isset($UNITTEST)) { // testcase can not construct course structure
            $context = get_context_instance(CONTEXT_COURSE, $this->moss->course);
        }

        $filepatterns = $DB->get_field('moss_configs', 'filepatterns', array('id' => $configid));
        $filepatterns = explode(' ', $filepatterns);
        $fs = get_file_storage();
        $rank = 1;
        foreach ($matches as $result) {
            $result['moss'] = $this->moss->id;
            $result['config'] = $configid;
            $result['rank'] = $rank + 1;
            $result1 = (object)$result;
            $result1->userid = $result['user1'];
            $result1->percentage = $result['percentage1'];
            $result2 = (object)$result;
            $result2->userid = $result['user2'];
            $result2->percentage = $result['percentage2'];

            if (!isset($UNITTEST)) { // testcase can not construct course structure
                // skip unenrolled users
                if (!is_enrolled($context, $result1->userid) and !is_enrolled($context, $result2->userid)) {
                    continue;
                }
            }

            $result1->id = $DB->insert_record('moss_results', $result1);
            $result2->pair = $result1->id;
            $result2->id = $DB->insert_record('moss_results', $result2);
            $result1->pair = $result2->id;
            $DB->update_record('moss_results', $result1);

            // update moss_matched_files db
            for ($i=1; $i<=2; $i++) {
                $userid = eval('return $result'.$i.'->userid;');
                $resultid = eval('return $result'.$i.'->id;');

                $files = $fs->get_directory_files(get_system_context()->id, 'plagiarism_moss', 'files', $this->moss->cmid, "/$userid/");
                foreach ($files as $file) {
                    foreach ($filepatterns as $pattern) {
                        if (fnmatch($pattern, $file->get_filename())) {
                            $obj = new stdClass();
                            $obj->result = $resultid;
                            $obj->contenthash = $file->get_contenthash();
                            $DB->insert_record('moss_matched_files', $obj);
                        }
                    }
                }
            }

            $rank++;
        }

        mtrace("\tGot $rank pairs");

        return true;
    }
Exemplo n.º 20
0
 /**
  * Save the extension date for a single user.
  *
  * @param int $userid The user id
  * @param mixed $extensionduedate Either an integer date or null
  * @return boolean
  */
 public function save_user_extension($userid, $extensionduedate)
 {
     global $DB;
     // Need submit permission to submit an assignment.
     require_capability('mod/assign:grantextension', $this->context);
     if (!is_enrolled($this->get_course_context(), $userid)) {
         return false;
     }
     if (!has_capability('mod/assign:submit', $this->context, $userid)) {
         return false;
     }
     if ($this->get_instance()->duedate && $extensionduedate) {
         if ($this->get_instance()->duedate > $extensionduedate) {
             return false;
         }
     }
     if ($this->get_instance()->allowsubmissionsfromdate && $extensionduedate) {
         if ($this->get_instance()->allowsubmissionsfromdate > $extensionduedate) {
             return false;
         }
     }
     $flags = $this->get_user_flags($userid, true);
     $flags->extensionduedate = $extensionduedate;
     $result = $this->update_user_flags($flags);
     if ($result) {
         $addtolog = $this->add_to_log('grant extension', $userid, '', true);
         $params = array('context' => $this->context, 'objectid' => $flags->assignment, 'relateduserid' => $userid);
         $event = \mod_assign\event\extension_granted::create($params);
         $event->set_legacy_logdata($addtolog);
         $event->trigger();
     }
     return $result;
 }
Exemplo n.º 21
0
 public function assertIsNotEnrolled($courseid, $userid)
 {
     $context = context_course::instance($courseid);
     $this->assertFalse(is_enrolled($context, $userid));
 }
Exemplo n.º 22
0
    /**
     * Display the feedback to the student
     *
     * This default method prints the teacher picture and name, date when marked,
     * grade and teacher submissioncomment.
     *
     * @global object
     * @global object
     * @global object
     * @param object $submission The submission object or NULL in which case it will be loaded
     */
    function view_feedback($submission=NULL) {
        global $USER, $CFG, $DB, $OUTPUT;
        require_once($CFG->libdir.'/gradelib.php');

        if (!is_enrolled($this->context, $USER, 'mod/assignment:view')) {
            // can not submit assignments -> no feedback
            return;
        }

        if (!$submission) { /// Get submission for this assignment
            $submission = $this->get_submission($USER->id);
        }
        // Check the user can submit
        $cansubmit = has_capability('mod/assignment:submit', $this->context, $USER->id, false);
        // If not then check if the user still has the view cap and has a previous submission
        $cansubmit = $cansubmit || (!empty($submission) && has_capability('mod/assignment:view', $this->context, $USER->id, false));

        if (!$cansubmit) {
            // can not submit assignments -> no feedback
            return;
        }

        $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
        $item = $grading_info->items[0];
        $grade = $item->grades[$USER->id];

        if ($grade->hidden or $grade->grade === false) { // hidden or error
            return;
        }

        if ($grade->grade === null and empty($grade->str_feedback)) {   /// Nothing to show yet
            return;
        }

        $graded_date = $grade->dategraded;
        $graded_by   = $grade->usermodified;

    /// We need the teacher info
        if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
            print_error('cannotfindteacher');
        }

    /// Print the feedback
        echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));

        echo '<table cellspacing="0" class="feedback">';

        echo '<tr>';
        echo '<td class="left picture">';
        if ($teacher) {
            echo $OUTPUT->user_picture($teacher);
        }
        echo '</td>';
        echo '<td class="topic">';
        echo '<div class="from">';
        if ($teacher) {
            echo '<div class="fullname">'.fullname($teacher).'</div>';
        }
        echo '<div class="time">'.userdate($graded_date).'</div>';
        echo '</div>';
        echo '</td>';
        echo '</tr>';

        echo '<tr>';
        echo '<td class="left side">&nbsp;</td>';
        echo '<td class="content">';
        echo '<div class="grade">';
        echo get_string("grade").': '.$grade->str_long_grade;
        echo '</div>';
        echo '<div class="clearer"></div>';

        echo '<div class="comment">';
        echo $grade->str_feedback;
        echo '</div>';
        echo '</tr>';

         if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
            $responsefiles = $this->print_responsefiles($submission->userid, true);
            if (!empty($responsefiles)) {
                echo '<tr>';
                echo '<td class="left side">&nbsp;</td>';
                echo '<td class="content">';
                echo $responsefiles;
                echo '</tr>';
            }
         }

        echo '</table>';
    }
Exemplo n.º 23
0
                 unset($newgroup->courseid);
                 //unset so 0 doesn't get written to database
             }
             $newgroup->courseid = $mycourse->id;
         } else {
             //else use use current id
             $newgroup->courseid = $id;
         }
     }
     //if courseid is set
     if (isset($newgroup->courseid)) {
         $linenum++;
         $groupname = $newgroup->name;
         $newgrpcoursecontext = get_context_instance(CONTEXT_COURSE, $newgroup->courseid);
         ///Users cannot upload groups in courses they cannot update.
         if (!has_capability('moodle/course:managegroups', $newgrpcoursecontext) or !is_enrolled($newgrpcoursecontext) and !has_capability('moodle/course:view', $newgrpcoursecontext)) {
             echo $OUTPUT->notification(get_string('nopermissionforcreation', 'group', $groupname));
         } else {
             if ($groupid = groups_get_group_by_name($newgroup->courseid, $groupname)) {
                 echo $OUTPUT->notification("{$groupname} :" . get_string('groupexistforcourse', 'error', $groupname));
             } else {
                 if (groups_create_group($newgroup)) {
                     echo $OUTPUT->notification(get_string('groupaddedsuccesfully', 'group', $groupname), 'notifysuccess');
                 } else {
                     echo $OUTPUT->notification(get_string('groupnotaddederror', 'error', $groupname));
                 }
             }
         }
     }
     unset($newgroup);
 }
Exemplo n.º 24
0
/**
 * Adds module specific settings to the settings block
 *
 * @param settings_navigation $settings The settings navigation object
 * @param navigation_node $forumnode The node to add module settings to
 */
function forum_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $forumnode) {
    global $USER, $PAGE, $CFG, $DB, $OUTPUT;

    $forumobject = $DB->get_record("forum", array("id" => $PAGE->cm->instance));
    if (empty($PAGE->cm->context)) {
        $PAGE->cm->context = get_context_instance(CONTEXT_MODULE, $PAGE->cm->instance);
    }

    // for some actions you need to be enrolled, beiing admin is not enough sometimes here
    $enrolled = is_enrolled($PAGE->cm->context, $USER, '', false);
    $activeenrolled = is_enrolled($PAGE->cm->context, $USER, '', true);

    $canmanage  = has_capability('mod/forum:managesubscriptions', $PAGE->cm->context);
    $subscriptionmode = forum_get_forcesubscribed($forumobject);
    $cansubscribe = ($activeenrolled && $subscriptionmode != FORUM_FORCESUBSCRIBE && ($subscriptionmode != FORUM_DISALLOWSUBSCRIBE || $canmanage));

    if ($canmanage) {
        $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node::TYPE_CONTAINER);

        $allowchoice = $mode->add(get_string('subscriptionoptional', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_CHOOSESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
        $forceforever = $mode->add(get_string("subscriptionforced", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_FORCESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
        $forceinitially = $mode->add(get_string("subscriptionauto", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_INITIALSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
        $disallowchoice = $mode->add(get_string('subscriptiondisabled', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_DISALLOWSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);

        switch ($subscriptionmode) {
            case FORUM_CHOOSESUBSCRIBE : // 0
                $allowchoice->action = null;
                $allowchoice->add_class('activesetting');
                break;
            case FORUM_FORCESUBSCRIBE : // 1
                $forceforever->action = null;
                $forceforever->add_class('activesetting');
                break;
            case FORUM_INITIALSUBSCRIBE : // 2
                $forceinitially->action = null;
                $forceinitially->add_class('activesetting');
                break;
            case FORUM_DISALLOWSUBSCRIBE : // 3
                $disallowchoice->action = null;
                $disallowchoice->add_class('activesetting');
                break;
        }

    } else if ($activeenrolled) {

        switch ($subscriptionmode) {
            case FORUM_CHOOSESUBSCRIBE : // 0
                $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
                break;
            case FORUM_FORCESUBSCRIBE : // 1
                $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
                break;
            case FORUM_INITIALSUBSCRIBE : // 2
                $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
                break;
            case FORUM_DISALLOWSUBSCRIBE : // 3
                $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
                break;
        }
    }

    if ($cansubscribe) {
        if (forum_is_subscribed($USER->id, $forumobject)) {
            $linktext = get_string('unsubscribe', 'forum');
        } else {
            $linktext = get_string('subscribe', 'forum');
        }
        $url = new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'sesskey'=>sesskey()));
        $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
    }

    if (has_capability('mod/forum:viewsubscribers', $PAGE->cm->context)){
        $url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$forumobject->id));
        $forumnode->add(get_string('showsubscribers', 'forum'), $url, navigation_node::TYPE_SETTING);
    }

    if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
        if ($forumobject->trackingtype != FORUM_TRACKING_OPTIONAL) {
            //tracking forced on or off in forum settings so dont provide a link here to change it
            //could add unclickable text like for forced subscription but not sure this justifies adding another menu item
        } else {
            if (forum_tp_is_tracked($forumobject)) {
                $linktext = get_string('notrackforum', 'forum');
            } else {
                $linktext = get_string('trackforum', 'forum');
            }
            $url = new moodle_url('/mod/forum/settracking.php', array('id'=>$forumobject->id));
            $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
        }
    }

    if ($enrolled && !empty($CFG->enablerssfeeds) && !empty($CFG->forum_enablerssfeeds) && $forumobject->rsstype && $forumobject->rssarticles) {

        if (!function_exists('rss_get_url')) {
            require_once("$CFG->libdir/rsslib.php");
        }

        if ($forumobject->rsstype == 1) {
            $string = get_string('rsssubscriberssdiscussions','forum');
        } else {
            $string = get_string('rsssubscriberssposts','forum');
        }
        if (!isloggedin()) {
            $userid = 0;
        } else {
            $userid = $USER->id;
        }
        $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $userid, "mod_forum", $forumobject->id));
        $forumnode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
    }
}
Exemplo n.º 25
0
 /**
  * Checks to see if the userid supplied has a tracked role in
  * this course
  *
  * @param int $userid User id
  * @return bool
  */
 public function is_tracked_user($userid)
 {
     return is_enrolled(context_course::instance($this->course->id), $userid, '', true);
 }
Exemplo n.º 26
0
/**
 * Actual implementation of the reset course functionality, delete all the
 * data responses for course $data->courseid.
 *
 * @global object
 * @global object
 * @param object $data the data submitted from the reset course.
 * @return array status array
 */
function data_reset_userdata($data) {
    global $CFG, $DB;
    require_once($CFG->libdir.'/filelib.php');
    require_once($CFG->dirroot.'/rating/lib.php');

    $componentstr = get_string('modulenameplural', 'data');
    $status = array();

    $allrecordssql = "SELECT r.id
                        FROM {data_records} r
                             INNER JOIN {data} d ON r.dataid = d.id
                       WHERE d.course = ?";

    $alldatassql = "SELECT d.id
                      FROM {data} d
                     WHERE d.course=?";

    $rm = new rating_manager();
    $ratingdeloptions = new stdClass;
    $ratingdeloptions->component = 'mod_data';
    $ratingdeloptions->ratingarea = 'entry';

    // delete entries if requested
    if (!empty($data->reset_data)) {
        $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
        $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
        $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));

        if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
            foreach ($datas as $dataid=>$unused) {
                fulldelete("$CFG->dataroot/$data->courseid/moddata/data/$dataid");

                if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
                    continue;
                }
                $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);

                $ratingdeloptions->contextid = $datacontext->id;
                $rm->delete_ratings($ratingdeloptions);
            }
        }

        if (empty($data->reset_gradebook_grades)) {
            // remove all grades from gradebook
            data_reset_gradebook($data->courseid);
        }
        $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
    }

    // remove entries by users not enrolled into course
    if (!empty($data->reset_data_notenrolled)) {
        $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
                         FROM {data_records} r
                              JOIN {data} d ON r.dataid = d.id
                              LEFT JOIN {user} u ON r.userid = u.id
                        WHERE d.course = ? AND r.userid > 0";

        $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
        $notenrolled = array();
        $fields = array();
        $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
        foreach ($rs as $record) {
            if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
              or !is_enrolled($course_context, $record->userid)) {
                //delete ratings
                if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
                    continue;
                }
                $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);
                $ratingdeloptions->contextid = $datacontext->id;
                $ratingdeloptions->itemid = $record->id;
                $rm->delete_ratings($ratingdeloptions);

                $DB->delete_records('comments', array('itemid'=>$record->id, 'commentarea'=>'database_entry'));
                $DB->delete_records('data_content', array('recordid'=>$record->id));
                $DB->delete_records('data_records', array('id'=>$record->id));
                // HACK: this is ugly - the recordid should be before the fieldid!
                if (!array_key_exists($record->dataid, $fields)) {
                    if ($fs = $DB->get_records('data_fields', array('dataid'=>$record->dataid))) {
                        $fields[$record->dataid] = array_keys($fs);
                    } else {
                        $fields[$record->dataid] = array();
                    }
                }
                foreach($fields[$record->dataid] as $fieldid) {
                    fulldelete("$CFG->dataroot/$data->courseid/moddata/data/$record->dataid/$fieldid/$record->id");
                }
                $notenrolled[$record->userid] = true;
            }
        }
        $rs->close();
        $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
    }

    // remove all ratings
    if (!empty($data->reset_data_ratings)) {
        if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
            foreach ($datas as $dataid=>$unused) {
                if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
                    continue;
                }
                $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);

                $ratingdeloptions->contextid = $datacontext->id;
                $rm->delete_ratings($ratingdeloptions);
            }
        }

        if (empty($data->reset_gradebook_grades)) {
            // remove all grades from gradebook
            data_reset_gradebook($data->courseid);
        }

        $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
    }

    // remove all comments
    if (!empty($data->reset_data_comments)) {
        $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
        $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
    }

    // updating dates - shift may be negative too
    if ($data->timeshift) {
        shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
        $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
    }

    return $status;
}
Exemplo n.º 27
0
/**
 * Returns posts made by the selected user in the requested courses.
 *
 * This method can be used to return all of the posts made by the requested user
 * within the given courses.
 * For each course the access of the current user and requested user is checked
 * and then for each post access to the post and forum is checked as well.
 *
 * This function is safe to use with usercapabilities.
 *
 * @global moodle_database $DB
 * @param stdClass $user The user whose posts we want to get
 * @param array $courses The courses to search
 * @param bool $musthaveaccess If set to true errors will be thrown if the user
 *                             cannot access one or more of the courses to search
 * @param bool $discussionsonly If set to true only discussion starting posts
 *                              will be returned.
 * @param int $limitfrom The offset of records to return
 * @param int $limitnum The number of records to return
 * @return stdClass An object the following properties
 *               ->totalcount: the total number of posts made by the requested user
 *                             that the current user can see.
 *               ->courses: An array of courses the current user can see that the
 *                          requested user has posted in.
 *               ->forums: An array of forums relating to the posts returned in the
 *                         property below.
 *               ->posts: An array containing the posts to show for this request.
 */
function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
    global $DB, $USER, $CFG;

    $return = new stdClass;
    $return->totalcount = 0;    // The total number of posts that the current user is able to view
    $return->courses = array(); // The courses the current user can access
    $return->forums = array();  // The forums that the current user can access that contain posts
    $return->posts = array();   // The posts to display

    // First up a small sanity check. If there are no courses to check we can
    // return immediately, there is obviously nothing to search.
    if (empty($courses)) {
        return $return;
    }

    // A couple of quick setups
    $isloggedin = isloggedin();
    $isguestuser = $isloggedin && isguestuser();
    $iscurrentuser = $isloggedin && $USER->id == $user->id;

    // Checkout whether or not the current user has capabilities over the requested
    // user and if so they have the capabilities required to view the requested
    // users content.
    $usercontext = context_user::instance($user->id, MUST_EXIST);
    $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
    $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);

    // Before we actually search each course we need to check the user's access to the
    // course. If the user doesn't have the appropraite access then we either throw an
    // error if a particular course was requested or we just skip over the course.
    foreach ($courses as $course) {
        $coursecontext = context_course::instance($course->id, MUST_EXIST);
        if ($iscurrentuser || $hascapsonuser) {
            // If it is the current user, or the current user has capabilities to the
            // requested user then all we need to do is check the requested users
            // current access to the course.
            // Note: There is no need to check group access or anything of the like
            // as either the current user is the requested user, or has granted
            // capabilities on the requested user. Either way they can see what the
            // requested user posted, although its VERY unlikely in the `parent` situation
            // that the current user will be able to view the posts in context.
            if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
                // Need to have full access to a course to see the rest of own info
                if ($musthaveaccess) {
                    print_error('errorenrolmentrequired', 'forum');
                }
                continue;
            }
        } else {
            // Check whether the current user is enrolled or has access to view the course
            // if they don't we immediately have a problem.
            if (!can_access_course($course)) {
                if ($musthaveaccess) {
                    print_error('errorenrolmentrequired', 'forum');
                }
                continue;
            }

            // Check whether the requested user is enrolled or has access to view the course
            // if they don't we immediately have a problem.
            if (!can_access_course($course, $user)) {
                if ($musthaveaccess) {
                    print_error('notenrolled', 'forum');
                }
                continue;
            }

            // If groups are in use and enforced throughout the course then make sure
            // we can meet in at least one course level group.
            // Note that we check if either the current user or the requested user have
            // the capability to access all groups. This is because with that capability
            // a user in group A could post in the group B forum. Grrrr.
            if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
              && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
                // If its the guest user to bad... the guest user cannot access groups
                if (!$isloggedin or $isguestuser) {
                    // do not use require_login() here because we might have already used require_login($course)
                    if ($musthaveaccess) {
                        redirect(get_login_url());
                    }
                    continue;
                }
                // Get the groups of the current user
                $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
                // Get the groups the requested user is a member of
                $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
                // Check whether they are members of the same group. If they are great.
                $intersect = array_intersect($mygroups, $usergroups);
                if (empty($intersect)) {
                    // But they're not... if it was a specific course throw an error otherwise
                    // just skip this course so that it is not searched.
                    if ($musthaveaccess) {
                        print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
                    }
                    continue;
                }
            }
        }
        // Woo hoo we got this far which means the current user can search this
        // this course for the requested user. Although this is only the course accessibility
        // handling that is complete, the forum accessibility tests are yet to come.
        $return->courses[$course->id] = $course;
    }
    // No longer beed $courses array - lose it not it may be big
    unset($courses);

    // Make sure that we have some courses to search
    if (empty($return->courses)) {
        // If we don't have any courses to search then the reality is that the current
        // user doesn't have access to any courses is which the requested user has posted.
        // Although we do know at this point that the requested user has posts.
        if ($musthaveaccess) {
            print_error('permissiondenied');
        } else {
            return $return;
        }
    }

    // Next step: Collect all of the forums that we will want to search.
    // It is important to note that this step isn't actually about searching, it is
    // about determining which forums we can search by testing accessibility.
    $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);

    // Will be used to build the where conditions for the search
    $forumsearchwhere = array();
    // Will be used to store the where condition params for the search
    $forumsearchparams = array();
    // Will record forums where the user can freely access everything
    $forumsearchfullaccess = array();
    // DB caching friendly
    $now = round(time(), -2);
    // For each course to search we want to find the forums the user has posted in
    // and providing the current user can access the forum create a search condition
    // for the forum to get the requested users posts.
    foreach ($return->courses as $course) {
        // Now we need to get the forums
        $modinfo = get_fast_modinfo($course);
        if (empty($modinfo->instances['forum'])) {
            // hmmm, no forums? well at least its easy... skip!
            continue;
        }
        // Iterate
        foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
            if (!$cm->uservisible or !isset($forums[$forumid])) {
                continue;
            }
            // Get the forum in question
            $forum = $forums[$forumid];
            // This is needed for functionality later on in the forum code....
            $forum->cm = $cm;

            // Check that either the current user can view the forum, or that the
            // current user has capabilities over the requested user and the requested
            // user can view the discussion
            if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
                continue;
            }

            // This will contain forum specific where clauses
            $forumsearchselect = array();
            if (!$iscurrentuser && !$hascapsonuser) {
                // Make sure we check group access
                if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
                    $groups = $modinfo->get_groups($cm->groupingid);
                    $groups[] = -1;
                    list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
                    $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
                    $forumsearchselect[] = "d.groupid $groupid_sql";
                }

                // hidden timed discussions
                if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
                    $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
                    $forumsearchparams['userid'.$forumid] = $user->id;
                    $forumsearchparams['timestart'.$forumid] = $now;
                    $forumsearchparams['timeend'.$forumid] = $now;
                }

                // qanda access
                if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
                    // We need to check whether the user has posted in the qanda forum.
                    $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
                    if (!empty($discussionspostedin)) {
                        $forumonlydiscussions = array();  // Holds discussion ids for the discussions the user is allowed to see in this forum.
                        foreach ($discussionspostedin as $d) {
                            $forumonlydiscussions[] = $d->id;
                        }
                        list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
                        $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
                        $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
                    } else {
                        $forumsearchselect[] = "p.parent = 0";
                    }

                }

                if (count($forumsearchselect) > 0) {
                    $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
                    $forumsearchparams['forum'.$forumid] = $forumid;
                } else {
                    $forumsearchfullaccess[] = $forumid;
                }
            } else {
                // The current user/parent can see all of their own posts
                $forumsearchfullaccess[] = $forumid;
            }
        }
    }

    // If we dont have any search conditions, and we don't have any forums where
    // the user has full access then we just return the default.
    if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
        return $return;
    }

    // Prepare a where condition for the full access forums.
    if (count($forumsearchfullaccess) > 0) {
        list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
        $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
        $forumsearchwhere[] = "(d.forum $fullidsql)";
    }

    // Prepare SQL to both count and search.
    // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
    // oracle and mssql.
    $userfields = user_picture::fields('u', null, 'useridx');
    $countsql = 'SELECT COUNT(*) ';
    $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
    $wheresql = implode(" OR ", $forumsearchwhere);

    if ($discussionsonly) {
        if ($wheresql == '') {
            $wheresql = 'p.parent = 0';
        } else {
            $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
        }
    }

    $sql = "FROM {forum_posts} p
            JOIN {forum_discussions} d ON d.id = p.discussion
            JOIN {user} u ON u.id = p.userid
           WHERE ($wheresql)
             AND p.userid = :userid ";
    $orderby = "ORDER BY p.modified DESC";
    $forumsearchparams['userid'] = $user->id;

    // Set the total number posts made by the requested user that the current user can see
    $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
    // Set the collection of posts that has been requested
    $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);

    // We need to build an array of forums for which posts will be displayed.
    // We do this here to save the caller needing to retrieve them themselves before
    // printing these forums posts. Given we have the forums already there is
    // practically no overhead here.
    foreach ($return->posts as $post) {
        if (!array_key_exists($post->forum, $return->forums)) {
            $return->forums[$post->forum] = $forums[$post->forum];
        }
    }

    return $return;
}
Exemplo n.º 28
0
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = context_course::instance($course->id);
     // Course context
     $systemcontext = context_system::instance();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = context_user::instance($user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = context_user::instance($user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
             if (!$canviewusercourse && !$canviewuser || !$userisenrolled) {
                 return false;
             }
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
                 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
                 if ($courseid == $this->page->course->id) {
                     $mygroups = get_fast_modinfo($this->page->course)->groups;
                 } else {
                     $mygroups = groups_get_user_groups($courseid);
                 }
                 $usergroups = groups_get_user_groups($courseid, $userid);
                 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
                     return false;
                 }
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     $prefurl = new moodle_url('/user/preferences.php');
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
         $prefurl->param('userid', $userid);
     }
     // Add a user setting branch.
     if ($gstitle == 'usercurrentsettings') {
         $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
         // This should be set to false as we don't want to show this to the user. It's only for generating the correct
         // breadcrumb.
         $dashboard->display = false;
         if (get_home_page() == HOMEPAGE_MY) {
             $dashboard->mainnavonly = true;
         }
         $iscurrentuser = $user->id == $USER->id;
         $baseargs = array('id' => $user->id);
         if ($course->id != $SITE->id && !$iscurrentuser) {
             $baseargs['course'] = $course->id;
             $issitecourse = false;
         } else {
             // Load all categories and get the context for the system.
             $issitecourse = true;
         }
         // Add the user profile to the dashboard.
         $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php', array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
         if (!empty($CFG->navadduserpostslinks)) {
             // Add nodes for forum posts and discussions if the user can view either or both
             // There are no capability checks here as the content of the page is based
             // purely on the forums the current user has access too.
             $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
             $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
             $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
         }
         // Add blog nodes.
         if (!empty($CFG->enableblogs)) {
             if (!$this->cache->cached('userblogoptions' . $user->id)) {
                 require_once $CFG->dirroot . '/blog/lib.php';
                 // Get all options for the user.
                 $options = blog_get_options_for_user($user);
                 $this->cache->set('userblogoptions' . $user->id, $options);
             } else {
                 $options = $this->cache->{'userblogoptions' . $user->id};
             }
             if (count($options) > 0) {
                 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
                 foreach ($options as $type => $option) {
                     if ($type == "rss") {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
                     } else {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
                     }
                 }
             }
         }
         // Add the messages link.
         // It is context based so can appear in the user's profile and in course participants information.
         if (!empty($CFG->messaging)) {
             $messageargs = array('user1' => $USER->id);
             if ($USER->id != $user->id) {
                 $messageargs['user2'] = $user->id;
             }
             if ($course->id != $SITE->id) {
                 $messageargs['viewing'] = MESSAGE_VIEW_COURSE . $course->id;
             }
             $url = new moodle_url('/message/index.php', $messageargs);
             $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
         }
         // Add the "My private files" link.
         // This link doesn't have a unique display for course context so only display it under the user's profile.
         if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
             $url = new moodle_url('/user/files.php');
             $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
         }
         // Add a node to view the users notes if permitted.
         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
             $url = new moodle_url('/notes/index.php', array('user' => $user->id));
             if ($coursecontext->instanceid != SITEID) {
                 $url->param('course', $coursecontext->instanceid);
             }
             $profilenode->add(get_string('notes', 'notes'), $url);
         }
         // Show the grades node.
         if ($issitecourse && $iscurrentuser || has_capability('moodle/user:viewdetails', $usercontext)) {
             require_once $CFG->dirroot . '/user/lib.php';
             // Set the grades node to link to the "Grades" page.
             if ($course->id == SITEID) {
                 $url = user_mygrades_url($user->id, $course->id);
             } else {
                 // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
                 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
             }
             $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
         }
         // Let plugins hook into user navigation.
         $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
         foreach ($pluginsfunction as $plugintype => $plugins) {
             if ($plugintype != 'report') {
                 foreach ($plugins as $pluginfunction) {
                     $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
                 }
             }
         }
         $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $dashboard->add_node($usersetting);
     } else {
         $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $usersetting->display = false;
     }
     $usersetting->id = 'usersettings';
     // Check if the user has been deleted.
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message.
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile.
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
     // Add the profile edit link.
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link.
     if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
     }
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
         }
     }
     $pluginmanager = core_plugin_manager::instance();
     $enabled = $pluginmanager->get_enabled_plugins('mod');
     if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
         }
     }
     $editors = editors_get_enabled();
     if (count($editors) > 1) {
         if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
             if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
                 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
                 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
             }
         }
     }
     // Add "Course preferences" link.
     if (isloggedin() && !isguestuser($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
         }
     }
     // View the roles settings.
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Repositories.
     if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) {
         require_once $CFG->dirroot . '/repository/lib.php';
         $editabletypes = repository::get_editable_types($usercontext);
         $haseditabletypes = !empty($editabletypes);
         unset($editabletypes);
         $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes);
     } else {
         $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id};
     }
     if ($haseditabletypes) {
         $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
         $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
     }
     // Portfolio.
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_has_visible_instances()) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', context_system::instance())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys.
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Messaging.
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $useraccount->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs.
     if ($currentuser && !empty($CFG->enableblogs)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         if (has_capability('moodle/blog:view', $systemcontext)) {
             $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         }
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', $systemcontext)) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
         // Remove the blog node if empty.
         $blog->trim_if_empty();
     }
     // Badges.
     if ($currentuser && !empty($CFG->enablebadges)) {
         $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
         if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
             $url = new moodle_url('/badges/mybadges.php');
             $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
         }
         $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->badges_allowexternalbackpack)) {
             $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Let plugins hook into user settings navigation.
     $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
     foreach ($pluginsfunction as $plugintype => $plugins) {
         foreach ($plugins as $pluginfunction) {
             $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
         }
     }
     return $usersetting;
 }
Exemplo n.º 29
0
/**
 * Returns true if the user is able to access the course.
 *
 * This function is in no way, shape, or form a substitute for require_login.
 * It should only be used in circumstances where it is not possible to call require_login
 * such as the navigation.
 *
 * This function checks many of the methods of access to a course such as the view
 * capability, enrollments, and guest access. It also makes use of the cache
 * generated by require_login for guest access.
 *
 * The flags within the $USER object that are used here should NEVER be used outside
 * of this function can_access_course and require_login. Doing so WILL break future
 * versions.
 *
 * @param stdClass $course record
 * @param stdClass|int|null $user user record or id, current user if null
 * @param string $withcapability Check for this capability as well.
 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
 * @return boolean Returns true if the user is able to access the course
 */
function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false)
{
    global $DB, $USER;
    // this function originally accepted $coursecontext parameter
    if ($course instanceof context) {
        if ($course instanceof context_course) {
            debugging('deprecated context parameter, please use $course record');
            $coursecontext = $course;
            $course = $DB->get_record('course', array('id' => $coursecontext->instanceid));
        } else {
            debugging('Invalid context parameter, please use $course record');
            return false;
        }
    } else {
        $coursecontext = context_course::instance($course->id);
    }
    if (!isset($USER->id)) {
        // should never happen
        $USER->id = 0;
    }
    // make sure there is a user specified
    if ($user === null) {
        $userid = $USER->id;
    } else {
        $userid = is_object($user) ? $user->id : $user;
    }
    unset($user);
    if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
        return false;
    }
    if ($userid == $USER->id) {
        if (!empty($USER->access['rsw'][$coursecontext->path])) {
            // the fact that somebody switched role means they can access the course no matter to what role they switched
            return true;
        }
    }
    if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
        return false;
    }
    if (is_viewing($coursecontext, $userid)) {
        return true;
    }
    if ($userid != $USER->id) {
        // for performance reasons we do not verify temporary guest access for other users, sorry...
        return is_enrolled($coursecontext, $userid, '', $onlyactive);
    }
    // === from here we deal only with $USER ===
    $coursecontext->reload_if_dirty();
    if (isset($USER->enrol['enrolled'][$course->id])) {
        if ($USER->enrol['enrolled'][$course->id] > time()) {
            return true;
        }
    }
    if (isset($USER->enrol['tempguest'][$course->id])) {
        if ($USER->enrol['tempguest'][$course->id] > time()) {
            return true;
        }
    }
    if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
        return true;
    }
    // if not enrolled try to gain temporary guest access
    $instances = $DB->get_records('enrol', array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
    $enrols = enrol_get_plugins(true);
    foreach ($instances as $instance) {
        if (!isset($enrols[$instance->enrol])) {
            continue;
        }
        // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
        $until = $enrols[$instance->enrol]->try_guestaccess($instance);
        if ($until !== false and $until > time()) {
            $USER->enrol['tempguest'][$course->id] = $until;
            return true;
        }
    }
    if (isset($USER->enrol['tempguest'][$course->id])) {
        unset($USER->enrol['tempguest'][$course->id]);
        remove_temp_course_roles($coursecontext);
    }
    return false;
}
Exemplo n.º 30
0
// Graph Type.
$user = required_param('user', PARAM_INT);
// Student ID.
$date = optional_param('date', 0, PARAM_INT);
// A time of a day (in GMT).
$logreader = optional_param('logreader', '', PARAM_COMPONENT);
$url = new moodle_url('/report/log/graph.php', array('id' => $id, 'type' => $type, 'user' => $user, 'date' => $date, 'logreader' => $logreader));
$PAGE->set_url($url);
if ($type !== "usercourse.png" and $type !== "userday.png") {
    $type = 'userday.png';
}
$course = $DB->get_record("course", array("id" => $id), '*', MUST_EXIST);
$user = $DB->get_record("user", array("id" => $user, 'deleted' => 0), '*', MUST_EXIST);
$coursecontext = context_course::instance($course->id);
$personalcontext = context_user::instance($user->id);
if ($USER->id != $user->id and has_capability('moodle/user:viewuseractivitiesreport', $personalcontext) and !is_enrolled($coursecontext, $USER) and is_enrolled($coursecontext, $user)) {
    //TODO: do not require parents to be enrolled in courses - this is a hack!
    require_login();
    $PAGE->set_course($course);
} else {
    require_login($course);
}
list($all, $today) = report_log_can_access_user_report($user, $course);
if ($type === "userday.png") {
    if (!$today) {
        require_capability('report/log:viewtoday', $coursecontext);
    }
} else {
    if (!$all) {
        require_capability('report/log:view', $coursecontext);
    }