Example #1
0
 /**
  * Renders course info box.
  *
  * @param stdClass $course
  * @return string
  */
 public function course_info_box(stdClass $course)
 {
     global $CFG;
     $context = context_course::instance($course->id);
     $content = '';
     $content .= $this->output->box_start('generalbox info');
     $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
     $content .= format_text($summary, $course->summaryformat, array('overflowdiv' => true), $course->id);
     if (!empty($CFG->coursecontact)) {
         $coursecontactroles = explode(',', $CFG->coursecontact);
         foreach ($coursecontactroles as $roleid) {
             if ($users = get_role_users($roleid, $context, true)) {
                 foreach ($users as $teacher) {
                     $role = new stdClass();
                     $role->id = $teacher->roleid;
                     $role->name = $teacher->rolename;
                     $role->shortname = $teacher->roleshortname;
                     $role->coursealias = $teacher->rolecoursealias;
                     $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
                     $namesarray[] = role_get_name($role, $context) . ': <a href="' . $CFG->wwwroot . '/user/view.php?id=' . $teacher->id . '&amp;course=' . SITEID . '">' . $fullname . '</a>';
                 }
             }
         }
         if (!empty($namesarray)) {
             $content .= "<ul class=\"teachers\">\n<li>";
             $content .= implode('</li><li>', $namesarray);
             $content .= "</li></ul>";
         }
     }
     $content .= $this->output->box_end();
     return $content;
 }
 function definition()
 {
     global $CFG, $DB;
     $mform = $this->_form;
     list($instance, $plugin, $course) = $this->_customdata;
     $coursecontext = context_course::instance($course->id);
     $enrol = enrol_get_plugin('cohort');
     $groups = array(0 => get_string('none'));
     foreach (groups_get_all_groups($course->id) as $group) {
         $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
     }
     $mform->addElement('header', 'general', get_string('pluginname', 'enrol_cohort'));
     $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
     $mform->setType('name', PARAM_TEXT);
     $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'), ENROL_INSTANCE_DISABLED => get_string('no'));
     $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
     if ($instance->id) {
         if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
             $cohorts = array($instance->customint1 => format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid))));
         } else {
             $cohorts = array($instance->customint1 => get_string('error'));
         }
         $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts);
         $mform->setConstant('customint1', $instance->customint1);
         $mform->hardFreeze('customint1', $instance->customint1);
     } else {
         $cohorts = array('' => get_string('choosedots'));
         $allcohorts = cohort_get_available_cohorts($coursecontext, 0, 0, 0);
         foreach ($allcohorts as $c) {
             $cohorts[$c->id] = format_string($c->name);
         }
         $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $cohorts);
         $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
     }
     $roles = get_assignable_roles($coursecontext);
     $roles[0] = get_string('none');
     $roles = array_reverse($roles, true);
     // Descending default sortorder.
     $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
     $mform->setDefault('roleid', $enrol->get_config('roleid'));
     if ($instance->id and !isset($roles[$instance->roleid])) {
         if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
             $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true);
             $roles[$instance->roleid] = role_get_name($role, $coursecontext);
         } else {
             $roles[$instance->roleid] = get_string('error');
         }
     }
     $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
     $mform->addElement('hidden', 'courseid', null);
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'id', null);
     $mform->setType('id', PARAM_INT);
     if ($instance->id) {
         $this->add_action_buttons(true);
     } else {
         $this->add_action_buttons(true, get_string('addinstance', 'enrol'));
     }
     $this->set_data($instance);
 }
Example #3
0
 /**
  * Returns localised name of enrol instance
  *
  * @param object|null $instance enrol_mnet instance
  * @return string
  */
 public function get_instance_name($instance)
 {
     global $DB;
     if (empty($instance)) {
         $enrol = $this->get_name();
         return get_string('pluginname', 'enrol_' . $enrol);
     } else {
         if (empty($instance->name)) {
             $enrol = $this->get_name();
             if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
                 $role = role_get_name($role, get_context_instance(CONTEXT_COURSE, $instance->courseid));
             } else {
                 $role = get_string('error');
             }
             if (empty($instance->customint1)) {
                 $host = get_string('remotesubscribersall', 'enrol_mnet');
             } else {
                 $host = $DB->get_field('mnet_host', 'name', array('id' => $instance->customint1));
             }
             return get_string('pluginname', 'enrol_' . $enrol) . ' (' . format_string($host) . ' - ' . $role . ')';
         } else {
             return format_string($instance->name);
         }
     }
 }
Example #4
0
 /**
  * Returns localised name of enrol instance.
  *
  * @param stdClass $instance (null is accepted too)
  * @return string
  */
 public function get_instance_name($instance)
 {
     global $DB;
     if (empty($instance)) {
         $enrol = $this->get_name();
         return get_string('pluginname', 'enrol_' . $enrol);
     } else {
         if (empty($instance->name)) {
             $enrol = $this->get_name();
             $cohort = $DB->get_record('cohort', array('id' => $instance->customint1));
             if (!$cohort) {
                 return get_string('pluginname', 'enrol_' . $enrol);
             }
             $cohortname = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
             if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
                 $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING));
                 return get_string('pluginname', 'enrol_' . $enrol) . ' (' . $cohortname . ' - ' . $role . ')';
             } else {
                 return get_string('pluginname', 'enrol_' . $enrol) . ' (' . $cohortname . ')';
             }
         } else {
             return format_string($instance->name, true, array('context' => context_course::instance($instance->courseid)));
         }
     }
 }
Example #5
0
 /**
  * Returns a human friendly description of the filter used as label.
  * @param array $data filter settings
  * @return string active filter label
  */
 function get_label($data)
 {
     global $DB;
     $role = $DB->get_record('role', array('id' => $data['value']));
     $a = new stdClass();
     $a->label = $this->_label;
     $a->value = '"' . role_get_name($role) . '"';
     return get_string('globalrolelabel', 'filters', $a);
 }
 /**
  * Gets role name.
  * If no such role exists this function returns null.
  *
  * @return string|null
  */
 private function get_role_name($rid)
 {
     global $DB, $PAGE;
     $rec = $DB->get_record('role', array('id' => $rid));
     if ($rec) {
         return role_get_name($rec, $PAGE->context, ROLENAME_ALIAS);
     } else {
         return null;
     }
 }
 /**
  * Gets a list of roles that this user can assign for the course as the default for auto-enrolment.
  *
  * @param context $context the context.
  * @param integer $defaultrole the id of the role that is set as the default for auto-enrolment
  * @return array index is the role id, value is the role name
  */
 function extend_assignable_roles($context, $defaultrole)
 {
     global $DB;
     $roles = get_assignable_roles($context, ROLENAME_BOTH);
     if (!isset($roles[$defaultrole])) {
         if ($role = $DB->get_record('role', array('id' => $defaultrole))) {
             $roles[$defaultrole] = role_get_name($role, $context, ROLENAME_BOTH);
         }
     }
     return $roles;
 }
 protected function get_course_roles($context)
 {
     global $DB;
     $roleswithnames = array();
     $contextroleids = get_roles_for_contextlevels(CONTEXT_COURSE);
     $contextroles = $DB->get_records_list('role', 'id', $contextroleids);
     foreach ($contextroles as $id => $role) {
         $roleswithnames[$id] = role_get_name($role, $context);
     }
     return $roleswithnames;
 }
Example #9
0
 /**
  * Creating an instance of the plugin
  */
 public function get_instance_name($instance)
 {
     if (empty($instance->name)) {
         if (!empty($instance->roleid)) {
             $role = ' (' . role_get_name($role, context_course::instance($instance->courseid)) . ')';
         } else {
             $role = '';
         }
         $enrol = $this->get_name();
         return get_string('pluginname', 'enrol_' . $enrol) . $role;
     } else {
         return format_string($instance->name);
     }
 }
Example #10
0
File: lib.php Project: ruddj/moodle
 /**
  * Returns localised name of enrol instance
  *
  * @param stdClass $instance (null is accepted too)
  * @return string
  */
 public function get_instance_name($instance)
 {
     global $DB;
     if (empty($instance->name)) {
         if (!empty($instance->roleid) and $role = $DB->get_record('role', array('id' => $instance->roleid))) {
             $role = ' (' . role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)) . ')';
         } else {
             $role = '';
         }
         $enrol = $this->get_name();
         return get_string('pluginname', 'enrol_' . $enrol) . $role;
     } else {
         return format_string($instance->name);
     }
 }
Example #11
0
 /**
  * Returns localised name of enrol instance
  *
  * @param object $instance (null is accepted too)
  * @return string
  */
 public function get_instance_name($instance)
 {
     global $DB;
     if (empty($instance)) {
         $enrol = $this->get_name();
         return get_string('pluginname', 'enrol_' . $enrol);
     } else {
         if (empty($instance->name)) {
             $enrol = $this->get_name();
             if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
                 $role = role_get_name($role, get_context_instance(CONTEXT_COURSE, $instance->courseid));
                 return get_string('pluginname', 'enrol_' . $enrol) . ' (' . format_string($DB->get_field('cohort', 'name', array('id' => $instance->customint1))) . ' - ' . $role . ')';
             } else {
                 return get_string('pluginname', 'enrol_' . $enrol) . ' (' . format_string($DB->get_field('cohort', 'name', array('id' => $instance->customint1))) . ')';
             }
         } else {
             return format_string($instance->name);
         }
     }
 }
Example #12
0
/**
 * @param stdClass $capability the information about a capability.
 * @return array role shortname => object with fields (role) shortname, (role) name,
 *      (role) description and permission (for this capability for that role).
 */
function tool_editrolesbycap_load_role_definitions($capability)
{
    global $DB;
    $data = $DB->get_records_sql('
                SELECT r.id AS roleid,
                       r.shortname,
                       r.name,
                       r.description,
                       r.archetype,
                       rc.permission
                  FROM {role} r
             LEFT JOIN {role_capabilities} rc ON rc.roleid = r.id
                                             AND rc.capability = :capability
                                             AND rc.contextid = :syscontextid
              ORDER BY r.sortorder, r.name', array('capability' => $capability->name, 'syscontextid' => context_system::instance()->id));
    foreach ($data as $role) {
        $role->name = role_get_name($role);
        $role->description = role_get_description($role);
        $role->defaultpermission = tool_editrolesbycap_get_default_permission($role, $capability);
    }
    return $data;
}
 protected function get_name_field($id)
 {
     return role_get_name($this->role);
 }
 /**
  * Returns list of course contacts (usually teachers) to display in course link
  *
  * Roles to display are set up in $CFG->coursecontact
  *
  * The result is the list of users where user id is the key and the value
  * is an array with elements:
  *  - 'user' - object containing basic user information
  *  - 'role' - object containing basic role information (id, name, shortname, coursealias)
  *  - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
  *  - 'username' => fullname($user, $canviewfullnames)
  *
  * @return array
  */
 public function get_course_contacts()
 {
     global $CFG;
     if (empty($CFG->coursecontact)) {
         // No roles are configured to be displayed as course contacts.
         return array();
     }
     if ($this->coursecontacts === null) {
         $this->coursecontacts = array();
         $context = context_course::instance($this->id);
         if (!isset($this->record->managers)) {
             // Preload course contacts from DB.
             $courses = array($this->id => &$this->record);
             coursecat::preload_course_contacts($courses);
         }
         // Build return array with full roles names (for this course context) and users names.
         $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
         foreach ($this->record->managers as $ruser) {
             if (isset($this->coursecontacts[$ruser->id])) {
                 // Only display a user once with the highest sortorder role.
                 continue;
             }
             $user = new stdClass();
             $user = username_load_fields_from_object($user, $ruser, null, array('id', 'username'));
             $role = new stdClass();
             $role->id = $ruser->roleid;
             $role->name = $ruser->rolename;
             $role->shortname = $ruser->roleshortname;
             $role->coursealias = $ruser->rolecoursealias;
             $this->coursecontacts[$user->id] = array('user' => $user, 'role' => $role, 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS), 'username' => fullname($user, $canviewfullnames));
         }
     }
     return $this->coursecontacts;
 }
Example #15
0
    /**
     * Return the standard string that says whether you are logged in (and switched
     * roles/logged in as another user).
     * @param bool $withlinks if false, then don't include any links in the HTML produced.
     * If not set, the default is the nologinlinks option from the theme config.php file,
     * and if that is not set, then links are included.
     * @return string HTML fragment.
     */
    public function login_info($withlinks = null) {
        global $USER, $CFG, $DB, $SESSION;

        if (during_initial_install()) {
            return '';
        }

        if (is_null($withlinks)) {
            $withlinks = empty($this->page->layout_options['nologinlinks']);
        }

        $course = $this->page->course;
        if (\core\session\manager::is_loggedinas()) {
            $realuser = \core\session\manager::get_realuser();
            $fullname = fullname($realuser, true);
            if ($withlinks) {
                $loginastitle = get_string('loginas');
                $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
                $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
            } else {
                $realuserinfo = " [$fullname] ";
            }
        } else {
            $realuserinfo = '';
        }

        $loginpage = $this->is_login_page();
        $loginurl = get_login_url();

        if (empty($course->id)) {
            // $course->id is not defined during installation
            return '';
        } else if (isloggedin()) {
            $context = context_course::instance($course->id);

            $fullname = fullname($USER, true);
            // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
            if ($withlinks) {
                $linktitle = get_string('viewprofile');
                $username = "******"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
            } else {
                $username = $fullname;
            }
            if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
                if ($withlinks) {
                    $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
                } else {
                    $username .= " from {$idprovider->name}";
                }
            }
            if (isguestuser()) {
                $loggedinas = $realuserinfo.get_string('loggedinasguest');
                if (!$loginpage && $withlinks) {
                    $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
                }
            } else if (is_role_switched($course->id)) { // Has switched roles
                $rolename = '';
                if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
                    $rolename = ': '.role_get_name($role, $context);
                }
                $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
                if ($withlinks) {
                    $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
                    $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
                }
            } else {
                $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
                if ($withlinks) {
                    $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
                }
            }
        } else {
            $loggedinas = get_string('loggedinnot', 'moodle');
            if (!$loginpage && $withlinks) {
                $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
            }
        }

        $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';

        if (isset($SESSION->justloggedin)) {
            unset($SESSION->justloggedin);
            if (!empty($CFG->displayloginfailures)) {
                if (!isguestuser()) {
                    // Include this file only when required.
                    require_once($CFG->dirroot . '/user/lib.php');
                    if ($count = user_count_login_failures($USER)) {
                        $loggedinas .= '<div class="loginfailures">';
                        $a = new stdClass();
                        $a->attempts = $count;
                        $loggedinas .= get_string('failedloginattempts', '', $a);
                        if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
                            $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
                                    'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
                        }
                        $loggedinas .= '</div>';
                    }
                }
            }
        }

        return $loggedinas;
    }
 /**
  * Return criteria title for display in reports
  *
  * @return string
  */
 public function get_title()
 {
     global $DB;
     $role = $DB->get_record('role', array('id' => $this->role));
     if (!$role) {
         return '[' . get_string('roleidnotfound', 'completion', $this->role) . ']';
     }
     return role_get_name($role, context_course::instance($this->course));
 }
Example #17
0
/**
 * Lists all roles that have the ability to backup user data, as well as users
 * @param bool $detailed
 * @return object result
 */
function report_security_check_riskbackup($detailed = false)
{
    global $CFG;
    $result = new object();
    $result->issue = 'report_security_check_riskbackup';
    $result->name = get_string('check_riskbackup_name', 'report_security');
    $result->info = null;
    $result->details = null;
    $result->status = null;
    $result->link = null;
    $syscontext = get_context_instance(CONTEXT_SYSTEM);
    $systemroles = get_records_sql("SELECT DISTINCT r.*\n           FROM {$CFG->prefix}role r\n           JOIN {$CFG->prefix}role_capabilities rc ON rc.roleid = r.id\n          WHERE rc.capability = 'moodle/backup:userinfo' AND rc.contextid = {$syscontext->id} AND rc.permission = " . CAP_ALLOW . "");
    $overriddenroles = get_records_sql("SELECT DISTINCT r.*, rc.contextid\n           FROM {$CFG->prefix}role r\n           JOIN {$CFG->prefix}role_capabilities rc ON rc.roleid = r.id\n          WHERE rc.capability = 'moodle/backup:userinfo' AND rc.contextid <> {$syscontext->id} AND rc.permission = " . CAP_ALLOW . "");
    // list of users that are able to backup personal info
    // note: "sc" is context where is role assigned,
    //       "c" is context where is role overriden or system context if in role definition
    $sqluserinfo = "\n        FROM (SELECT rcx.*\n                FROM {$CFG->prefix}role_capabilities rcx\n               WHERE rcx.permission = " . CAP_ALLOW . " AND rcx.capability = 'moodle/backup:userinfo') rc,\n             {$CFG->prefix}context c,\n             {$CFG->prefix}context sc,\n             {$CFG->prefix}role_assignments ra,\n             {$CFG->prefix}user u\n       WHERE c.id = rc.contextid\n             AND (sc.path = c.path OR sc.path LIKE " . sql_concat('c.path', "'/%'") . " OR c.path LIKE " . sql_concat('sc.path', "'/%'") . ")\n             AND u.id = ra.userid AND u.deleted = 0\n             AND ra.contextid = sc.id AND ra.roleid = rc.roleid\n             AND sc.contextlevel <= " . CONTEXT_COURSE . " AND c.contextlevel <= " . CONTEXT_COURSE . "";
    $usercount = count_records_sql("SELECT COUNT('x') FROM (SELECT DISTINCT u.id {$sqluserinfo}) userinfo");
    $systemrolecount = empty($systemroles) ? 0 : count($systemroles);
    $overriddenrolecount = empty($overriddenroles) ? 0 : count($overriddenroles);
    $result->status = REPORT_SECURITY_WARNING;
    // there is always at least one admin
    $a = (object) array('rolecount' => $systemrolecount, 'overridecount' => $overriddenrolecount, 'usercount' => $usercount);
    $result->info = get_string('check_riskbackup_warning', 'report_security', $a);
    if ($detailed) {
        $result->details = '';
        // Will be added to later
        // Make a list of roles
        if ($systemroles) {
            $links = array();
            foreach ($systemroles as $role) {
                $role->url = "{$CFG->wwwroot}/{$CFG->admin}/roles/manage.php?action=edit&amp;roleid={$role->id}";
                $links[] = '<li>' . get_string('check_riskbackup_editrole', 'report_security', $role) . '</li>';
            }
            $links = '<ul>' . implode($links) . '</ul>';
            $result->details .= get_string('check_riskbackup_details_systemroles', 'report_security', $links);
        }
        // Make a list of overrides to roles
        $rolelinks2 = array();
        if ($overriddenroles) {
            $links = array();
            foreach ($overriddenroles as $role) {
                $context = get_context_instance_by_id($role->contextid);
                if ($context->contextlevel == CONTEXT_COURSE) {
                    $role->name = role_get_name($role, $context);
                }
                $role->contextname = print_context_name($context);
                $role->url = "{$CFG->wwwroot}/{$CFG->admin}/roles/override.php?contextid={$role->contextid}&amp;roleid={$role->id}";
                $links[] = '<li>' . get_string('check_riskbackup_editoverride', 'report_security', $role) . '</li>';
            }
            $links = '<ul>' . implode($links) . '</ul>';
            $result->details .= get_string('check_riskbackup_details_overriddenroles', 'report_security', $links);
        }
        // Get a list of affected users as well
        $rs = get_recordset_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, ra.contextid, ra.roleid\n            {$sqluserinfo} ORDER BY u.lastname, u.firstname");
        $users = array();
        while ($user = rs_fetch_next_record($rs)) {
            $context = get_context_instance_by_id($user->contextid);
            $url = "{$CFG->wwwroot}/{$CFG->admin}/roles/assign.php?contextid={$user->contextid}&amp;roleid={$user->roleid}";
            $a = (object) array('fullname' => fullname($user), 'url' => $url, 'email' => $user->email, 'contextname' => print_context_name($context));
            $users[] = '<li>' . get_string('check_riskbackup_unassign', 'report_security', $a) . '</li>';
        }
        rs_close($rs);
        if (!empty($users)) {
            $users = '<ul>' . implode($users) . '</ul>';
            $result->details .= get_string('check_riskbackup_details_users', 'report_security', $users);
        }
    }
    return $result;
}
Example #18
0
/**
 * Performs the report function.
 *
 * @param array $formdata the form data
 * @param int $type the report type
 * @param string $saveto File to save the pdf report to.
 * @return bool False on failure
 * @uses $CFG, $DB
 */
function report_ncccscensus_generate_report($formdata, $type = REPORT_NCCCSCENSUS_ACTION_VIEW, $saveto = false)
{
    global $CFG, $DB;
    require_once $CFG->libdir . '/moodlelib.php';
    $reportname = 'report_ncccscensus';
    $cid = $formdata->id;
    // In case the form is hacked, set a default startdate to today at midnight.
    if (empty($formdata->startdate)) {
        $formdata->startdate = usergetmidnight(time(), get_user_timezone());
    }
    // In case the form is hacked, set a default enddate to today at midnight.
    if (empty($formdata->enddate)) {
        $formdata->enddate = $formdata->startdate;
    }
    // Advance enddate to tomorrow's midnight.
    $formdata->enddate += DAYSECS - 1;
    // This flag determines if we should display grouped users or not.
    $nogroups = isset($formdata->disablegroups) ? true : false;
    if ($nogroups) {
        $group = false;
    } else {
        // If group specified, do some validation.
        $group = isset($formdata->group) ? $formdata->group : false;
        // In case the form is hacked, the group could be invalid.
        if ($group === false || $group < 0) {
            throw new report_ncccscensus_exception('cannotfindgroup');
        }
        if ($group > 0) {
            // Validate the group ID.
            if (!groups_group_exists($group)) {
                throw new report_ncccscensus_exception('cannotfindgroup');
            }
            // Validate the group ID with respect to the course ID.
            $groupdata = groups_get_course_data($cid);
            $groupfound = false;
            foreach ($groupdata->groups as $groupobject) {
                if ($groupobject->id == $group) {
                    $groupfound = true;
                    break;
                }
            }
            if (!$groupfound) {
                throw new report_ncccscensus_exception('invalidgroupid');
            }
            // User could still hack form to view a group that they don't have the capability to see.
            $context = context_course::instance($cid);
            if (has_capability('moodle/site:accessallgroups', $context)) {
                $userid = 0;
            } else {
                if (has_capability('moodle/course:managegroups', $context)) {
                    $userid = $USER->id;
                } else {
                    $userid = false;
                }
            }
            if ($userid === false) {
                throw new report_ncccscensus_exception('invalidgroupid');
            }
            if ($userid != 0) {
                $grouprecs = groups_get_all_groups($course->id, $userid, 0, 'g.id, g.name');
                $groupnotfound = true;
                foreach ($grouprecs as $grouprec) {
                    if ($grouprec->id == $group) {
                        $groupnotfound = false;
                        break;
                    }
                }
                if ($groupnotfound) {
                    throw new report_ncccscensus_exception('invalidgroupid');
                }
            }
        }
    }
    $users = array();
    if ($nogroups) {
        $users = report_ncccscensus_get_users($cid, REPORT_NCCCSCENSUS_EXCLUDE_GROUP_MEMBERS);
    } else {
        if ($group > 0) {
            $users = report_ncccscensus_get_users($cid, $group);
        } else {
            $users = report_ncccscensus_get_users($cid);
        }
    }
    $results = report_ncccscensus_build_grades_array($cid, $users, $formdata->startdate, $formdata->enddate);
    if (empty($results)) {
        return false;
    }
    if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) {
        $headers = array('student' => get_string('studentfullnamehtml', $reportname));
        $showstudentid = report_ncccscensus_check_field_status('showstudentid', 'html');
    } else {
        if ($type == REPORT_NCCCSCENSUS_ACTION_CSV) {
            $headers = array('student' => get_string('studentfullnamecsv', $reportname));
            $showstudentid = report_ncccscensus_check_field_status('showstudentid', 'csv');
        } else {
            $headers = array('student' => get_string('studentfullnamepdf', $reportname));
            $showstudentid = report_ncccscensus_check_field_status('showstudentid', 'pdf');
        }
    }
    if ($showstudentid) {
        $headers['studentid'] = get_string('studentid', $reportname);
    }
    $headers['activity'] = get_string('activityname', $reportname);
    $headers['module'] = get_string('activitymodule', $reportname);
    $headers['status'] = get_string('submissionstatus', $reportname);
    $headers['datesubmitted'] = get_string('submissiondate', $reportname);
    $headers['grade'] = get_string('grade', $reportname);
    $headers['gradedate'] = get_string('gradedate', $reportname);
    $context = context_course::instance($cid);
    $namesarrayview = array();
    $namesarraypdf = array();
    $instructors = ' - ';
    $viewlink = ': <a href="' . $CFG->wwwroot . '/user/view.php?id=';
    if (!empty($CFG->coursecontact)) {
        $coursecontactroles = explode(',', $CFG->coursecontact);
        sort($coursecontactroles);
        // If a user has multiple roles, we do not want to show user multiple times as a contact.
        $teachers = array();
        foreach ($coursecontactroles as $roleid) {
            $roleid = (int) $roleid;
            if ($users = get_role_users($roleid, $context, true)) {
                $role = $DB->get_record('role', array('id' => $roleid));
                $rolename = format_string(role_get_name($role, $context));
                foreach ($users as $teacher) {
                    // The $teachers array tracks whether a user is already a course contact.
                    if (!isset($teachers[$teacher->id])) {
                        $teachers[$teacher->id] = true;
                        $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
                        $namesarrayview[] = $rolename . $viewlink . $teacher->id . '&amp;course=' . SITEID . '">' . $fullname . '</a>';
                        $namesarraycsv[] = $rolename . ': ' . $fullname;
                        $namesarraypdf[] = $rolename . ': ' . $fullname;
                    }
                }
            }
        }
    }
    if ($type != REPORT_NCCCSCENSUS_ACTION_PDF) {
        if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) {
            // Create legend for HTML view.
            $legend = new html_table();
            $legend->head = array(get_string('legend', $reportname));
            $legend->headspan = array(2);
            $legendrow1colour = new html_table_cell();
            $legendrow1colour->style = 'width: 50px; background-color: ' . get_config('report_ncccscensus', 'gradeoverridecolour');
            $legendrow1[] = $legendrow1colour;
            $legendrow1[] = get_string('legendgradeoverride', $reportname);
            $legendrow2colour = new html_table_cell();
            $legendrow2colour->style = 'width: 50px; background-color: ' . get_config('report_ncccscensus', 'gradenogradecolour');
            $legendrow2[] = $legendrow2colour;
            $legendrow2[] = get_string('legendnograde', $reportname);
            $legend->data = array($legendrow1, $legendrow2);
            $legendalign = array('center', 'left');
            $legend->align = $legendalign;
        }
        $table = new html_table();
        $table->head = $headers;
        $align = array('left');
        $numheaders = count($headers);
        for ($i = 1; $i < $numheaders; $i++) {
            $align[] = 'center';
        }
        $table->align = $align;
        $table->data = array();
        foreach ($results as $result) {
            $datum = array();
            $datum[] = $result->student;
            if ($showstudentid) {
                $datum[] = $result->studentid;
            }
            $datum[] = $result->activity;
            $datum[] = $result->module;
            $status = $result->status;
            $grade = $result->grade;
            if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $grade == get_string('nograde', $reportname)) {
                $specialstatus = new html_table_cell($status);
                $specialstatus->style = 'background-color: ' . get_config('report_ncccscensus', 'gradenogradecolour');
                $status = $specialstatus;
            } else {
                if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $result->overridden) {
                    $specialstatus = new html_table_cell($status);
                    $specialstatus->style = 'background-color: ' . get_config('report_ncccscensus', 'gradeoverridecolour');
                    $status = $specialstatus;
                }
            }
            $datum[] = $status;
            $datum[] = $result->submitdate;
            if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $grade == get_string('nograde', $reportname)) {
                $nograde = new html_table_cell($grade);
                $nograde->style = 'background-color: ' . get_config('report_ncccscensus', 'gradenogradecolour');
                $grade = $nograde;
            } else {
                if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW && $result->overridden) {
                    $overriddengrade = new html_table_cell($grade);
                    $overriddengrade->style = 'background-color: ' . get_config('report_ncccscensus', 'gradeoverridecolour');
                    $grade = $overriddengrade;
                }
            }
            $datum[] = $grade;
            $datum[] = $result->date;
            $table->data[] = $datum;
        }
    }
    $course = $DB->get_record('course', array('id' => $cid));
    if ($group > 0) {
        $groupname = groups_get_group_name($group);
    }
    $datestring = 'n/j/y';
    $reportrange = date($datestring, $formdata->startdate) . ' - ' . date($datestring, $formdata->enddate);
    if ($type != REPORT_NCCCSCENSUS_ACTION_VIEW) {
        $date = usergetdate(time(), get_user_timezone());
        $filename = 'CensusRpt2_';
        $filename .= date('MdY_Hi', mktime($date['hours'], $date['minutes'], 0, $date['mon'], $date['mday'], $date['year']));
    }
    if ($type == REPORT_NCCCSCENSUS_ACTION_VIEW) {
        if (report_ncccscensus_check_field_status('showcoursename', 'html')) {
            echo '<b>' . get_string('coursetitle', $reportname) . ':</b> ' . $course->fullname . '<br>';
        }
        if (report_ncccscensus_check_field_status('showcoursecode', 'html')) {
            echo '<b>' . get_string('coursecode', $reportname) . ':</b> ' . $course->shortname . '<br>';
        }
        // Only show course ID if present.
        if (report_ncccscensus_check_field_status('showcourseid', 'html') && $course->idnumber !== '') {
            echo '<b>' . get_string('courseid', $reportname) . ':</b> ' . $course->idnumber . '<br>';
        }
        if (report_ncccscensus_check_field_status('showteachername', 'html')) {
            if (!empty($namesarrayview)) {
                $instructors = implode(', ', $namesarrayview);
                echo '<b>' . get_string('instructor', $reportname) . ':</b> ' . $instructors . '<br>';
            }
        }
        echo '<b>' . get_string('reportrange', $reportname) . ':</b> ' . $reportrange . '<br>';
        if (isset($groupname)) {
            echo '<b>' . get_string('section', $reportname) . ':</b> ' . $groupname . '<br>';
        } else {
            echo '<b>' . get_string('section', $reportname) . ':</b> ' . get_string('allgroupspdf', $reportname) . '<br>';
        }
        echo '<br>';
        echo html_writer::table($table);
        echo '<div id="studentfootnote" style="font-size:10px;">' . get_string('studentfootnote', $reportname) . '</div>';
        echo '<br>';
        echo html_writer::table($legend);
        echo '<br><div align="center"><a href="' . $CFG->wwwroot . '/report/ncccscensus/index.php?id=' . $formdata->id . '">';
        echo get_string('backtoreport', 'report_ncccscensus') . '</a></div>';
    } else {
        if ($type == REPORT_NCCCSCENSUS_ACTION_PDF) {
            $topheaders = array();
            $topheaders['student'] = get_string('student', $reportname);
            $topheaders['activity'] = get_string('activity', $reportname);
            $topheaders['submission'] = get_string('submission', $reportname);
            $topheaders['grade'] = get_string('grade', $reportname);
            $bottomheaders = array();
            $bottomheaders['student'] = array('fullname' => get_string('studentfullnamepdf', $reportname));
            $showstudentid = report_ncccscensus_check_field_status('showstudentid', 'pdf');
            if ($showstudentid) {
                $bottomheaders['student']['id'] = get_string('studentidpdf', $reportname);
            }
            $bottomheaders['activity'] = array('name' => get_string('activityname', $reportname), 'module' => get_string('activitymodule', $reportname));
            $bottomheaders['submission'] = array('status' => get_string('submissionstatus', $reportname), 'date' => get_string('submissiondate', $reportname));
            $bottomheaders['grade'] = array('grade' => get_string('grade', $reportname), 'date' => get_string('gradedatepdf', $reportname));
            require_once 'report.class.php';
            $censusreport = new report();
            $censusreport->topheaders = $topheaders;
            $censusreport->bottomheaders = $bottomheaders;
            $censusreport->data = array();
            foreach ($results as $result) {
                $fieldarray = array();
                $fieldarray['studentfullname'] = $result->student;
                if ($showstudentid) {
                    $fieldarray['studentid'] = $result->studentid;
                }
                $fieldarray['activityname'] = $result->activity;
                $fieldarray['activitymodule'] = $result->module;
                $fieldarray['submissionstatus'] = $result->status;
                $fieldarray['submissiondate'] = $result->submitdate;
                $fieldarray['gradegrade'] = $result->grade;
                $fieldarray['gradedate'] = $result->date;
                $censusreport->data[] = array('data' => $fieldarray, 'override' => $result->overridden != 0 ? true : false, 'nograde' => $result->grade == get_string('nograde', $reportname) ? true : false);
            }
            $censusreport->filename = $filename . '.pdf';
            if (report_ncccscensus_check_field_status('showcoursename', 'pdf')) {
                $censusreport->top[] = array(get_string('coursetitlepdf', $reportname) . ':', $course->fullname);
            }
            if (report_ncccscensus_check_field_status('showcoursecode', 'pdf')) {
                $censusreport->top[] = array(get_string('coursecodepdf', $reportname) . ':', $course->shortname);
            }
            if (report_ncccscensus_check_field_status('showcourseid', 'pdf') && $course->idnumber !== '') {
                $censusreport->top[] = array(get_string('courseid', $reportname) . ':', $course->idnumber);
            }
            if (report_ncccscensus_check_field_status('showteachername', 'pdf')) {
                if (!empty($namesarrayview)) {
                    $instructors = implode(', ', $namesarrayview);
                }
                $censusreport->top[] = array(get_string('instructor', $reportname) . ':', strip_tags($instructors));
            }
            $censusreport->top[] = array(get_string('reportrangepdf', $reportname) . ':', $reportrange);
            if (isset($groupname)) {
                $censusreport->top[] = array(get_string('group', $reportname) . ':', $groupname);
            } else {
                if ($group !== false) {
                    $censusreport->top[] = array(get_string('group', $reportname) . ':', get_string('allgroupspdf', $reportname));
                }
            }
            if (report_ncccscensus_check_field_status('showsignatureline', 'pdf')) {
                $censusreport->signatureline = true;
            }
            if (report_ncccscensus_check_field_status('showdateline', 'pdf')) {
                $censusreport->dateline = true;
            }
            if ($footermessage = get_config('report_ncccscensus', 'footermessage')) {
                $censusreport->bottom .= $footermessage;
            }
            $censusreport->download($saveto);
            return true;
        } else {
            if ($type == REPORT_NCCCSCENSUS_ACTION_CSV) {
                if (!empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) {
                    header('Expires: 0');
                    header('Cache-Control: private, pre-check=0, post-check=0, max-age=0, must-revalidate');
                    header('Connection: Keep-Alive');
                    header('Content-Language: ' . current_language());
                    header('Keep-Alive: timeout=5, max=100');
                    header('Pragma: no-cache');
                    header('Pragma: expires');
                    header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
                    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                }
                header('Content-Transfer-Encoding: ascii');
                header('Content-Disposition: attachment; filename=' . $filename . '.csv');
                header('Content-Type: text/comma-separated-values');
                $output = fopen('php://output', 'w');
                fputcsv($output, array(get_string('ncccscensusreport_title', 'report_ncccscensus')));
                fputcsv($output, array());
                if (report_ncccscensus_check_field_status('showcoursename', 'csv')) {
                    fputcsv($output, array(get_string('coursetitle', $reportname), $course->fullname));
                }
                if (report_ncccscensus_check_field_status('showcoursecode', 'csv')) {
                    fputcsv($output, array(get_string('coursecode', $reportname), $course->shortname));
                }
                if (report_ncccscensus_check_field_status('showcourseid', 'csv') && $course->idnumber !== '') {
                    fputcsv($output, array(get_string('courseid', $reportname), $course->idnumber));
                }
                if (!empty($namesarrayview) && report_ncccscensus_check_field_status('showteachername', 'csv')) {
                    fputcsv($output, array_merge(array(get_string('instructor', $reportname)), $namesarraycsv));
                }
                fputcsv($output, array(get_string('reportrange', $reportname), $reportrange));
                if (isset($groupname)) {
                    fputcsv($output, array(get_string('section', $reportname), $groupname));
                } else {
                    fputcsv($output, array(get_string('section', $reportname), get_string('allgroups', $reportname)));
                }
                fputcsv($output, array());
                fputcsv($output, $table->head);
                foreach ($table->data as $row) {
                    fputcsv($output, $row);
                }
                $showsignatureline = report_ncccscensus_check_field_status('showsignatureline', 'csv');
                $showdateline = report_ncccscensus_check_field_status('showdateline', 'csv');
                if ($showsignatureline || $showdateline) {
                    fputcsv($output, array());
                    if ($showsignatureline) {
                        fputcsv($output, array(get_string('certified', $reportname)));
                        fputcsv($output, array(get_string('signature', $reportname) . get_string('underscores', $reportname)));
                    }
                    if ($showdateline) {
                        fputcsv($output, array(get_string('date') . get_string('underscores', 'report_ncccscensus')));
                    }
                }
                fclose($output);
            }
        }
    }
}
Example #19
0
// but this is much cheaper. And in any case, it is only doable with limited numbers
// of rows anyway. On a large course it will explode badly...
//
if ($mode === MODE_ENROLDETAILS) {
    if ($context->id != $frontpagectx->id) {
        $userids = $DB->get_fieldset_sql("SELECT DISTINCT u.id {$from} {$where} {$wheresearch}", $params, $table->get_page_start(), $table->get_page_size());
    } else {
        $userids = $DB->get_fieldset_sql("SELECT u.id {$from} {$where} {$wheresearch}", $params, $table->get_page_start(), $table->get_page_size());
    }
    $userlist_extra = get_participants_extra($userids, $avoidroles, $course, $context);
}
if ($context->id == $frontpagectx->id) {
    $strallsiteusers = get_string('allsiteusers', 'role');
    if ($CFG->defaultfrontpageroleid) {
        if ($fprole = $DB->get_record('role', array('id' => $CFG->defaultfrontpageroleid))) {
            $fprole = role_get_name($fprole, $frontpagectx);
            $strallsiteusers = "{$strallsiteusers} ({$fprole})";
        }
    }
    $rolenames = array(-1 => $strallsiteusers) + $rolenames;
}
/// If there are multiple Roles in the course, then show a drop down menu for switching
if (count($rolenames) > 1) {
    echo '<div class="rolesform">';
    echo '<label for="rolesform_jump">' . get_string('currentrole', 'role') . '&nbsp;</label>';
    if ($context->id != $frontpagectx->id) {
        $rolenames = array(0 => get_string('all')) + $rolenames;
    } else {
        if (!$CFG->defaultfrontpageroleid) {
            // we do not want "All users with role" - we already have all users in defualt frontpage role option
            $rolenames = array(0 => get_string('userswithrole', 'role')) + $rolenames;
$error = '';
/// Get applicable roles
$rolenames = array();
if ($roles = get_roles_used_in_context($context, true)) {
    $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context);
    $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext);
    foreach ($roles as $role) {
        if (!isset($canviewroles[$role->id])) {
            // Avoid this role (eg course creator)
            continue;
        }
        if (isset($doanythingroles[$role->id])) {
            // Avoid this role (ie admin)
            continue;
        }
        $rolenames[$role->id] = strip_tags(role_get_name($role, $context));
        // Used in menus etc later on
    }
}
/// Create the form
$editform = new autogroup_form(null, array('roles' => $rolenames));
$editform->set_data(array('courseid' => $courseid, 'seed' => time()));
/// Handle form submission
if ($editform->is_cancelled()) {
    redirect($returnurl);
} elseif ($data = $editform->get_data(false)) {
    /// Allocate members from the selected role to groups
    switch ($data->allocateby) {
        case 'no':
        case 'random':
        case 'lastname':
Example #21
0
/**
 * Prepare list of roles for display, apply aliases and localise default role names.
 *
 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
 * @param context $context the context, null means system context
 * @param int $rolenamedisplay
 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
 * @return array Array of context-specific role names, or role objects with a ->localname field added.
 */
function role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
    global $DB;

    if (empty($roleoptions)) {
        return array();
    }

    if (!$context or !$coursecontext = $context->get_course_context(false)) {
        $coursecontext = null;
    }

    // We usually need all role columns...
    $first = reset($roleoptions);
    if ($returnmenu === null) {
        $returnmenu = !is_object($first);
    }

    if (!is_object($first) or !property_exists($first, 'shortname')) {
        $allroles = get_all_roles($context);
        foreach ($roleoptions as $rid => $unused) {
            $roleoptions[$rid] = $allroles[$rid];
        }
    }

    // Inject coursealias if necessary.
    if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
        $first = reset($roleoptions);
        if (!property_exists($first, 'coursealias')) {
            $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
            foreach ($aliasnames as $alias) {
                if (isset($roleoptions[$alias->roleid])) {
                    $roleoptions[$alias->roleid]->coursealias = $alias->name;
                }
            }
        }
    }

    // Add localname property.
    foreach ($roleoptions as $rid => $role) {
        $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
    }

    if (!$returnmenu) {
        return $roleoptions;
    }

    $menu = array();
    foreach ($roleoptions as $rid => $role) {
        $menu[$rid] = $role->localname;
    }

    return $menu;
}
 /**
  * Test roles used in course.
  */
 public function test_get_user_roles_in_course()
 {
     global $DB, $CFG;
     $this->resetAfterTest();
     $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'), '*', MUST_EXIST);
     $studentrole = $DB->get_record('role', array('shortname' => 'student'), '*', MUST_EXIST);
     $course = $this->getDataGenerator()->create_course();
     $coursecontext = context_course::instance($course->id);
     $teacherrename = (object) array('roleid' => $teacherrole->id, 'name' => 'Učitel', 'contextid' => $coursecontext->id);
     $DB->insert_record('role_names', $teacherrename);
     $roleids = explode(',', $CFG->profileroles);
     // Should include teacher and student in new installs.
     $this->assertTrue(in_array($teacherrole->id, $roleids));
     $this->assertTrue(in_array($studentrole->id, $roleids));
     $user1 = $this->getDataGenerator()->create_user();
     role_assign($teacherrole->id, $user1->id, $coursecontext->id);
     role_assign($studentrole->id, $user1->id, $coursecontext->id);
     $user2 = $this->getDataGenerator()->create_user();
     role_assign($studentrole->id, $user2->id, $coursecontext->id);
     $user3 = $this->getDataGenerator()->create_user();
     $roles = get_user_roles_in_course($user1->id, $course->id);
     $this->assertEquals(1, preg_match_all('/,/', $roles, $matches));
     $this->assertTrue(strpos($roles, role_get_name($teacherrole, $coursecontext)) !== false);
     $roles = get_user_roles_in_course($user2->id, $course->id);
     $this->assertEquals(0, preg_match_all('/,/', $roles, $matches));
     $this->assertTrue(strpos($roles, role_get_name($studentrole, $coursecontext)) !== false);
     $roles = get_user_roles_in_course($user3->id, $course->id);
     $this->assertSame('', $roles);
 }
Example #23
0
        require_capability('moodle/course:viewparticipants', $context);
    }

    $rolenamesurl = new moodle_url("$CFG->wwwroot/user/index.php?contextid=$context->id&sifirst=&silast=");

    $allroles = get_all_roles();
    $roles = get_profile_roles($context);
    $allrolenames = array();
    if ($isfrontpage) {
        $rolenames = array(0=>get_string('allsiteusers', 'role'));
    } else {
        $rolenames = array(0=>get_string('allparticipants'));
    }

    foreach ($allroles as $role) {
        $allrolenames[$role->id] = strip_tags(role_get_name($role, $context));   // Used in menus etc later on
        if (isset($roles[$role->id])) {
            $rolenames[$role->id] = $allrolenames[$role->id];
        }
    }

    // make sure other roles may not be selected by any means
    if (empty($rolenames[$roleid])) {
        print_error('noparticipants');
    }

    // no roles to display yet?
    // frontpage course is an exception, on the front page course we should display all users
    if (empty($rolenames) && !$isfrontpage) {
        if (has_capability('moodle/role:assign', $context)) {
            redirect($CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id);
Example #24
0
// print enrol info
if ($texts = enrol_get_course_description_texts($course)) {
    echo $OUTPUT->box_start('generalbox icons');
    echo implode($texts);
    echo $OUTPUT->box_end();
}
echo $OUTPUT->box_start('generalbox info');
$course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
echo format_text($course->summary, $course->summaryformat, array('overflowdiv' => true), $course->id);
if (!empty($CFG->coursecontact)) {
    $coursecontactroles = explode(',', $CFG->coursecontact);
    foreach ($coursecontactroles as $roleid) {
        $role = $DB->get_record('role', array('id' => $roleid));
        $roleid = (int) $roleid;
        if ($users = get_role_users($roleid, $context, true)) {
            foreach ($users as $teacher) {
                $fullname = fullname($teacher, has_capability('moodle/site:viewfullnames', $context));
                $namesarray[] = format_string(role_get_name($role, $context)) . ': <a href="' . $CFG->wwwroot . '/user/view.php?id=' . $teacher->id . '&amp;course=' . SITEID . '">' . $fullname . '</a>';
            }
        }
    }
    if (!empty($namesarray)) {
        echo "<ul class=\"teachers\">\n<li>";
        echo implode('</li><li>', $namesarray);
        echo "</li></ul>";
    }
}
// TODO: print some enrol icons
echo $OUTPUT->box_end();
echo "<br />";
echo $OUTPUT->footer();
Example #25
0
/**
 * Get a list of essential user navigation items.
 *
 * @param stdclass $user user object.
 * @param moodle_page $page page object.
 * @return stdClass $returnobj navigation information object, where:
 *
 *      $returnobj->navitems    array    array of links where each link is a
 *                                       stdClass with fields url, title, and
 *                                       pix
 *      $returnobj->metadata    array    array of useful user metadata to be
 *                                       used when constructing navigation;
 *                                       fields include:
 *
 *          ROLE FIELDS
 *          asotherrole    bool    whether viewing as another role
 *          rolename       string  name of the role
 *
 *          USER FIELDS
 *          These fields are for the currently-logged in user, or for
 *          the user that the real user is currently logged in as.
 *
 *          userid         int        the id of the user in question
 *          userfullname   string     the user's full name
 *          userprofileurl moodle_url the url of the user's profile
 *          useravatar     string     a HTML fragment - the rendered
 *                                    user_picture for this user
 *          userloginfail  string     an error string denoting the number
 *                                    of login failures since last login
 *
 *          "REAL USER" FIELDS
 *          These fields are for when asotheruser is true, and
 *          correspond to the underlying "real user".
 *
 *          asotheruser        bool    whether viewing as another user
 *          realuserid         int        the id of the user in question
 *          realuserfullname   string     the user's full name
 *          realuserprofileurl moodle_url the url of the user's profile
 *          realuseravatar     string     a HTML fragment - the rendered
 *                                        user_picture for this user
 *
 *          MNET PROVIDER FIELDS
 *          asmnetuser            bool   whether viewing as a user from an
 *                                       MNet provider
 *          mnetidprovidername    string name of the MNet provider
 *          mnetidproviderwwwroot string URL of the MNet provider
 */
function user_get_user_navigation_info($user, $page)
{
    global $OUTPUT, $DB, $SESSION, $CFG;
    $returnobject = new stdClass();
    $returnobject->navitems = array();
    $returnobject->metadata = array();
    $course = $page->course;
    // Query the environment.
    $context = context_course::instance($course->id);
    // Get basic user metadata.
    $returnobject->metadata['userid'] = $user->id;
    $returnobject->metadata['userfullname'] = fullname($user, true);
    $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array('id' => $user->id));
    $returnobject->metadata['useravatar'] = $OUTPUT->user_picture($user, array('link' => false, 'visibletoscreenreaders' => false));
    // Build a list of items for a regular user.
    // Query MNet status.
    if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
        $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
        $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
        $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
    }
    // Did the user just log in?
    if (isset($SESSION->justloggedin)) {
        // Don't unset this flag as login_info still needs it.
        if (!empty($CFG->displayloginfailures)) {
            // We're already in /user/lib.php, so we don't need to include.
            if ($count = user_count_login_failures($user)) {
                // Get login failures string.
                $a = new stdClass();
                $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
                $returnobject->metadata['userloginfail'] = get_string('failedloginattempts', '', $a);
            }
        }
    }
    // Links: Dashboard.
    $myhome = new stdClass();
    $myhome->itemtype = 'link';
    $myhome->url = new moodle_url('/my/');
    $myhome->title = get_string('mymoodle', 'admin');
    $myhome->pix = "i/course";
    $returnobject->navitems[] = $myhome;
    // Links: My Profile.
    $myprofile = new stdClass();
    $myprofile->itemtype = 'link';
    $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
    $myprofile->title = get_string('profile');
    $myprofile->pix = "i/user";
    $returnobject->navitems[] = $myprofile;
    // Links: Role-return or logout link.
    $lastobj = null;
    $buildlogout = true;
    $returnobject->metadata['asotherrole'] = false;
    if (is_role_switched($course->id)) {
        if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
            // Build role-return link instead of logout link.
            $rolereturn = new stdClass();
            $rolereturn->itemtype = 'link';
            $rolereturn->url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $page->url->out_as_local_url(false)));
            $rolereturn->pix = "a/logout";
            $rolereturn->title = get_string('switchrolereturn');
            $lastobj = $rolereturn;
            $returnobject->metadata['asotherrole'] = true;
            $returnobject->metadata['rolename'] = role_get_name($role, $context);
            $buildlogout = false;
        }
    }
    if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
        $realuser = \core\session\manager::get_realuser();
        // Save values for the real user, as $user will be full of data for the
        // user the user is disguised as.
        $returnobject->metadata['realuserid'] = $realuser->id;
        $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
        $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array('id' => $realuser->id));
        $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, array('link' => false, 'visibletoscreenreaders' => false));
        // Build a user-revert link.
        $userrevert = new stdClass();
        $userrevert->itemtype = 'link';
        $userrevert->url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'sesskey' => sesskey()));
        $userrevert->pix = "a/logout";
        $userrevert->title = get_string('logout');
        $lastobj = $userrevert;
        $buildlogout = false;
    }
    if ($buildlogout) {
        // Build a logout link.
        $logout = new stdClass();
        $logout->itemtype = 'link';
        $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
        $logout->pix = "a/logout";
        $logout->title = get_string('logout');
        $lastobj = $logout;
    }
    // Before we add the last item (usually a logout link), add any
    // custom-defined items.
    $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
    foreach ($customitems as $item) {
        $returnobject->navitems[] = $item;
    }
    // Add the last item to the list.
    if (!is_null($lastobj)) {
        $returnobject->navitems[] = $lastobj;
    }
    return $returnobject;
}
/**
 * Lists all roles that have the ability to backup user data, as well as users
 * @param bool $detailed
 * @return object result
 */
function report_security_check_riskbackup($detailed = false)
{
    global $CFG, $DB;
    $result = new stdClass();
    $result->issue = 'report_security_check_riskbackup';
    $result->name = get_string('check_riskbackup_name', 'report_security');
    $result->info = null;
    $result->details = null;
    $result->status = null;
    $result->link = null;
    $syscontext = context_system::instance();
    $params = array('capability' => 'moodle/backup:userinfo', 'permission' => CAP_ALLOW, 'contextid' => $syscontext->id);
    $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, r.archetype\n              FROM {role} r\n              JOIN {role_capabilities} rc ON rc.roleid = r.id\n             WHERE rc.capability = :capability\n               AND rc.contextid  = :contextid\n               AND rc.permission = :permission";
    $systemroles = $DB->get_records_sql($sql, $params);
    $params = array('capability' => 'moodle/backup:userinfo', 'permission' => CAP_ALLOW, 'contextid' => $syscontext->id);
    $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, r.archetype, rc.contextid\n              FROM {role} r\n              JOIN {role_capabilities} rc ON rc.roleid = r.id\n             WHERE rc.capability = :capability\n               AND rc.contextid <> :contextid\n               AND rc.permission = :permission";
    $overriddenroles = $DB->get_records_sql($sql, $params);
    // list of users that are able to backup personal info
    // note: "sc" is context where is role assigned,
    //       "c" is context where is role overridden or system context if in role definition
    $params = array('capability' => 'moodle/backup:userinfo', 'permission' => CAP_ALLOW, 'context1' => CONTEXT_COURSE, 'context2' => CONTEXT_COURSE);
    $sqluserinfo = "\n        FROM (SELECT rcx.*\n                FROM {role_capabilities} rcx\n               WHERE rcx.permission = :permission AND rcx.capability = :capability) rc,\n             {context} c,\n             {context} sc,\n             {role_assignments} ra,\n             {user} u\n       WHERE c.id = rc.contextid\n             AND (sc.path = c.path OR sc.path LIKE " . $DB->sql_concat('c.path', "'/%'") . " OR c.path LIKE " . $DB->sql_concat('sc.path', "'/%'") . ")\n             AND u.id = ra.userid AND u.deleted = 0\n             AND ra.contextid = sc.id AND ra.roleid = rc.roleid\n             AND sc.contextlevel <= :context1 AND c.contextlevel <= :context2";
    $usercount = $DB->count_records_sql("SELECT COUNT('x') FROM (SELECT DISTINCT u.id {$sqluserinfo}) userinfo", $params);
    $systemrolecount = empty($systemroles) ? 0 : count($systemroles);
    $overriddenrolecount = empty($overriddenroles) ? 0 : count($overriddenroles);
    $result->status = REPORT_SECURITY_WARNING;
    // there is always at least one admin
    $a = (object) array('rolecount' => $systemrolecount, 'overridecount' => $overriddenrolecount, 'usercount' => $usercount);
    $result->info = get_string('check_riskbackup_warning', 'report_security', $a);
    if ($detailed) {
        $result->details = '';
        // Will be added to later
        // Make a list of roles
        if ($systemroles) {
            $links = array();
            foreach ($systemroles as $role) {
                $role->name = role_get_name($role);
                $role->url = "{$CFG->wwwroot}/{$CFG->admin}/roles/manage.php?action=edit&amp;roleid={$role->id}";
                $links[] = '<li>' . get_string('check_riskbackup_editrole', 'report_security', $role) . '</li>';
            }
            $links = '<ul>' . implode($links) . '</ul>';
            $result->details .= get_string('check_riskbackup_details_systemroles', 'report_security', $links);
        }
        // Make a list of overrides to roles
        $rolelinks2 = array();
        if ($overriddenroles) {
            $links = array();
            foreach ($overriddenroles as $role) {
                $role->name = $role->localname;
                $context = context::instance_by_id($role->contextid);
                $role->name = role_get_name($role, $context, ROLENAME_BOTH);
                $role->contextname = $context->get_context_name();
                $role->url = "{$CFG->wwwroot}/{$CFG->admin}/roles/override.php?contextid={$role->contextid}&amp;roleid={$role->id}";
                $links[] = '<li>' . get_string('check_riskbackup_editoverride', 'report_security', $role) . '</li>';
            }
            $links = '<ul>' . implode('', $links) . '</ul>';
            $result->details .= get_string('check_riskbackup_details_overriddenroles', 'report_security', $links);
        }
        // Get a list of affected users as well
        $users = array();
        list($sort, $sortparams) = users_order_by_sql('u');
        $rs = $DB->get_recordset_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, u.imagealt, u.email, ra.contextid, ra.roleid\n            {$sqluserinfo} ORDER BY {$sort}", array_merge($params, $sortparams));
        foreach ($rs as $user) {
            $context = context::instance_by_id($user->contextid);
            $url = "{$CFG->wwwroot}/{$CFG->admin}/roles/assign.php?contextid={$user->contextid}&amp;roleid={$user->roleid}";
            $a = (object) array('fullname' => fullname($user), 'url' => $url, 'email' => $user->email, 'contextname' => $context->get_context_name());
            $users[] = '<li>' . get_string('check_riskbackup_unassign', 'report_security', $a) . '</li>';
        }
        if (!empty($users)) {
            $users = '<ul>' . implode('', $users) . '</ul>';
            $result->details .= get_string('check_riskbackup_details_users', 'report_security', $users);
        }
    }
    return $result;
}
Example #27
0
if (count($acceptedroles) > 1) {
    // If there is more than one role that can award a badge, prompt user to make a selection.
    // If it is an admin, include all accepted roles, otherwise only the ones that current user has in this context.
    if ($isadmin) {
        $selection = $acceptedroles;
    } else {
        // Get all the roles that user has and use the ones required by this badge.
        $roles = get_user_roles($context, $USER->id);
        $roleids = array_map(create_function('$o', 'return $o->roleid;'), $roles);
        $selection = array_intersect($acceptedroles, $roleids);
    }
    if (!empty($selection)) {
        list($usertest, $userparams) = $DB->get_in_or_equal($selection, SQL_PARAMS_NAMED, 'existing', true);
        $options = $DB->get_records_sql('SELECT * FROM {role} WHERE id ' . $usertest, $userparams);
        foreach ($options as $p) {
            $select[$p->id] = role_get_name($p);
        }
        if (!$role) {
            $pageurl = new moodle_url('/badges/award.php', array('id' => $badgeid));
            echo $OUTPUT->header();
            echo $OUTPUT->box(get_string('selectaward', 'badges') . $OUTPUT->single_select(new moodle_url($pageurl), 'role', $select));
            echo $OUTPUT->footer();
            die;
        } else {
            $pageurl = new moodle_url('/badges/award.php', array('id' => $badgeid));
            $issuerrole = new stdClass();
            $issuerrole->roleid = $role;
            $roleselect = get_string('selectaward', 'badges') . $OUTPUT->single_select(new moodle_url($pageurl), 'role', $select, $role, null);
        }
    } else {
        echo $OUTPUT->header();
function backup_general_info($bf, $preferences)
{
    global $CFG;
    fwrite($bf, start_tag("INFO", 1, true));
    //The name of the backup
    fwrite($bf, full_tag("NAME", 2, false, $preferences->backup_name));
    //The moodle_version
    fwrite($bf, full_tag("MOODLE_VERSION", 2, false, $preferences->moodle_version));
    fwrite($bf, full_tag("MOODLE_RELEASE", 2, false, $preferences->moodle_release));
    //The backup_version
    fwrite($bf, full_tag("BACKUP_VERSION", 2, false, $preferences->backup_version));
    fwrite($bf, full_tag("BACKUP_RELEASE", 2, false, $preferences->backup_release));
    //The date
    fwrite($bf, full_tag("DATE", 2, false, $preferences->backup_unique_code));
    //The original site wwwroot
    fwrite($bf, full_tag("ORIGINAL_WWWROOT", 2, false, $CFG->wwwroot));
    //The original site identifier. MD5 hashed for security.
    fwrite($bf, full_tag("ORIGINAL_SITE_IDENTIFIER_HASH", 2, false, md5(get_site_identifier())));
    //The zip method used
    if (!empty($CFG->zip)) {
        $zipmethod = 'external';
    } else {
        $zipmethod = 'internal';
    }
    //Indicate if it includes external MNET users
    $sql = "SELECT b.old_id\n                   FROM   {$CFG->prefix}backup_ids b\n                     JOIN {$CFG->prefix}user       u ON b.old_id=u.id\n                   WHERE b.backup_code = '{$preferences->backup_unique_code}'\n                         AND b.table_name = 'user' AND u.mnethostid != '{$CFG->mnet_localhost_id}'";
    if (record_exists_sql($sql)) {
        fwrite($bf, full_tag("MNET_REMOTEUSERS", 2, false, 'true'));
    }
    fwrite($bf, full_tag("ZIP_METHOD", 2, false, $zipmethod));
    //Te includes tag
    fwrite($bf, start_tag("DETAILS", 2, true));
    //Now, go to mod element of preferences to print its status
    foreach ($preferences->mods as $element) {
        //Calculate info
        $included = "false";
        $userinfo = "false";
        if ($element->backup) {
            $included = "true";
            if ($element->userinfo) {
                $userinfo = "true";
            }
        }
        //Prints the mod start
        fwrite($bf, start_tag("MOD", 3, true));
        fwrite($bf, full_tag("NAME", 4, false, $element->name));
        fwrite($bf, full_tag("INCLUDED", 4, false, $included));
        fwrite($bf, full_tag("USERINFO", 4, false, $userinfo));
        if (isset($preferences->mods[$element->name]->instances) && is_array($preferences->mods[$element->name]->instances) && count($preferences->mods[$element->name]->instances)) {
            fwrite($bf, start_tag("INSTANCES", 4, true));
            foreach ($preferences->mods[$element->name]->instances as $id => $object) {
                if (!empty($object->backup)) {
                    //Calculate info
                    $included = "false";
                    $userinfo = "false";
                    if ($object->backup) {
                        $included = "true";
                        if ($object->userinfo) {
                            $userinfo = "true";
                        }
                    }
                    fwrite($bf, start_tag("INSTANCE", 5, true));
                    fwrite($bf, full_tag("ID", 5, false, $id));
                    fwrite($bf, full_tag("NAME", 5, false, $object->name));
                    fwrite($bf, full_tag("INCLUDED", 5, false, $included));
                    fwrite($bf, full_tag("USERINFO", 5, false, $userinfo));
                    fwrite($bf, end_tag("INSTANCE", 5, true));
                }
            }
            fwrite($bf, end_tag("INSTANCES", 4, true));
        }
        //Print the end
        fwrite($bf, end_tag("MOD", 3, true));
    }
    //The metacourse in backup
    if ($preferences->backup_metacourse == 1) {
        fwrite($bf, full_tag("METACOURSE", 3, false, "true"));
    } else {
        fwrite($bf, full_tag("METACOURSE", 3, false, "false"));
    }
    //The user in backup
    if ($preferences->backup_users == 1) {
        fwrite($bf, full_tag("USERS", 3, false, "course"));
    } else {
        if ($preferences->backup_users == 0) {
            fwrite($bf, full_tag("USERS", 3, false, "all"));
        } else {
            fwrite($bf, full_tag("USERS", 3, false, "none"));
        }
    }
    //The logs in backup
    if ($preferences->backup_logs == 1) {
        fwrite($bf, full_tag("LOGS", 3, false, "true"));
    } else {
        fwrite($bf, full_tag("LOGS", 3, false, "false"));
    }
    //The user files
    if ($preferences->backup_user_files == 1) {
        fwrite($bf, full_tag("USERFILES", 3, false, "true"));
    } else {
        fwrite($bf, full_tag("USERFILES", 3, false, "false"));
    }
    //The course files
    if ($preferences->backup_course_files == 1) {
        fwrite($bf, full_tag("COURSEFILES", 3, false, "true"));
    } else {
        fwrite($bf, full_tag("COURSEFILES", 3, false, "false"));
    }
    //The site files
    if ($preferences->backup_site_files == 1) {
        fwrite($bf, full_tag("SITEFILES", 3, false, "true"));
    } else {
        fwrite($bf, full_tag("SITEFILES", 3, false, "false"));
    }
    //The gradebook histories
    if (empty($CFG->disablegradehistory) && $preferences->backup_gradebook_history == 1) {
        fwrite($bf, full_tag("GRADEBOOKHISTORIES", 3, false, "true"));
    } else {
        fwrite($bf, full_tag("GRADEBOOKHISTORIES", 3, false, "false"));
    }
    //The messages in backup
    if ($preferences->backup_messages == 1 && $preferences->backup_course == SITEID) {
        fwrite($bf, full_tag("MESSAGES", 3, false, "true"));
    } else {
        fwrite($bf, full_tag("MESSAGES", 3, false, "false"));
    }
    //The blogs in backup
    if ($preferences->backup_blogs == 1 && $preferences->backup_course == SITEID) {
        fwrite($bf, full_tag("BLOGS", 3, false, "true"));
    } else {
        fwrite($bf, full_tag("BLOGS", 3, false, "false"));
    }
    //The mode of writing the block data
    fwrite($bf, full_tag('BLOCKFORMAT', 3, false, 'instances'));
    fwrite($bf, end_tag("DETAILS", 2, true));
    $status = fwrite($bf, end_tag("INFO", 1, true));
    ///Roles stuff goes in here
    fwrite($bf, start_tag('ROLES', 1, true));
    $roles = backup_fetch_roles($preferences);
    $sitecontext = get_context_instance(CONTEXT_SYSTEM);
    $coursecontext = get_context_instance(CONTEXT_COURSE, $preferences->backup_course);
    foreach ($roles as $role) {
        fwrite($bf, start_tag('ROLE', 2, true));
        fwrite($bf, full_tag('ID', 3, false, $role->id));
        fwrite($bf, full_tag('NAME', 3, false, $role->name));
        fwrite($bf, full_tag('SHORTNAME', 3, false, $role->shortname));
        /// Calculate $role name in course
        $nameincourse = role_get_name($role, $coursecontext);
        if ($nameincourse != $role->name) {
            fwrite($bf, full_tag('NAMEINCOURSE', 3, false, $nameincourse));
        }
        // find and write all default capabilities
        fwrite($bf, start_tag('CAPABILITIES', 3, true));
        // pull out all default (site context) capabilities
        if ($capabilities = role_context_capabilities($role->id, $sitecontext)) {
            foreach ($capabilities as $capability => $value) {
                fwrite($bf, start_tag('CAPABILITY', 4, true));
                fwrite($bf, full_tag('NAME', 5, false, $capability));
                fwrite($bf, full_tag('PERMISSION', 5, false, $value));
                // use this to pull out the other info (timemodified and modifierid)
                $cap = get_record_sql("SELECT *\n                                           FROM {$CFG->prefix}role_capabilities\n                                           WHERE capability = '{$capability}'\n                                                 AND contextid = {$sitecontext->id}\n                                                 AND roleid = {$role->id}");
                fwrite($bf, full_tag("TIMEMODIFIED", 5, false, $cap->timemodified));
                fwrite($bf, full_tag("MODIFIERID", 5, false, $cap->modifierid));
                fwrite($bf, end_tag('CAPABILITY', 4, true));
            }
        }
        fwrite($bf, end_tag('CAPABILITIES', 3, true));
        fwrite($bf, end_tag('ROLE', 2, true));
    }
    fwrite($bf, end_tag('ROLES', 1, true));
    return $status;
}
 /**
  * Return the standard string that says whether you are logged in (and switched
  * roles/logged in as another user).
  * @param bool $withlinks if false, then don't include any links in the HTML produced.
  * If not set, the default is the nologinlinks option from the theme config.php file,
  * and if that is not set, then links are included.
  * @return string HTML fragment.
  */
 public function login_info($withlinks = null)
 {
     global $USER, $CFG, $DB, $SESSION;
     if (during_initial_install()) {
         return '';
     }
     if (is_null($withlinks)) {
         $withlinks = empty($this->page->layout_options['nologinlinks']);
     }
     $loginpage = (string) $this->page->url === get_login_url();
     $course = $this->page->course;
     if (\core\session\manager::is_loggedinas()) {
         $realuser = \core\session\manager::get_realuser();
         $fullname = fullname($realuser, true);
         if ($withlinks) {
             $loginastitle = get_string('loginas');
             $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&amp;sesskey=" . sesskey() . "\"";
             $realuserinfo .= "title =\"" . $loginastitle . "\">{$fullname}</a>] ";
         } else {
             $realuserinfo = " [{$fullname}] ";
         }
     } else {
         $realuserinfo = '';
     }
     $loginurl = get_login_url();
     if (empty($course->id)) {
         // $course->id is not defined during installation
         return '';
     } else {
         if (isloggedin()) {
             $context = context_course::instance($course->id);
             $fullname = fullname($USER, true);
             // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
             if ($withlinks) {
                 $linktitle = get_string('viewprofile');
                 $username = "******"{$CFG->wwwroot}/user/profile.php?id={$USER->id}\" title=\"{$linktitle}\">{$fullname}</a>";
             } else {
                 $username = $fullname;
             }
             if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) {
                 if ($withlinks) {
                     $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
                 } else {
                     $username .= " from {$idprovider->name}";
                 }
             }
             if (isguestuser()) {
                 $loggedinas = $realuserinfo . get_string('loggedinasguest');
                 if (!$loginpage && $withlinks) {
                     $loggedinas .= " (<a href=\"{$loginurl}\">" . get_string('login') . '</a>)';
                 }
             } else {
                 if (is_role_switched($course->id)) {
                     // Has switched roles
                     $rolename = '';
                     if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) {
                         $rolename = ': ' . role_get_name($role, $context);
                     }
                     $loggedinas = get_string('loggedinas', 'moodle', $username) . $rolename;
                     if ($withlinks) {
                         $url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false)));
                         $loggedinas .= '(' . html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)) . ')';
                     }
                 } else {
                     $loggedinas = $realuserinfo . get_string('loggedinas', 'moodle', $username);
                     if ($withlinks) {
                         echo "<i class='fa fa-user hide979 mywhite'></i> ";
                         //****************$loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
                         $loggedinas .= " <span class=\"line-trans\">|</span><a class=\"logtop\" href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\"> " . get_string('logout') . '</a><span class="line-trans"> |</span>';
                     }
                 }
             }
         } else {
             $loggedinas = get_string('loggedinnot', 'moodle');
             if (!$loginpage && $withlinks) {
                 //****************$loggedinas $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
                 echo "<i class='fa fa-lock hide979 mywhite'></i> ";
                 $loggedinas .= " | <a href=\"{$loginurl}\">" . get_string('login') . '</a> |';
             }
         }
     }
     $loggedinas = '<div class="logininfo">' . $loggedinas . '</div>';
     if (isset($SESSION->justloggedin)) {
         unset($SESSION->justloggedin);
         if (!empty($CFG->displayloginfailures)) {
             if (!isguestuser()) {
                 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
                     $loggedinas .= '&nbsp;<div class="loginfailures">';
                     if (empty($count->accounts)) {
                         $loggedinas .= get_string('failedloginattempts', '', $count);
                     } else {
                         $loggedinas .= get_string('failedloginattemptsall', '', $count);
                     }
                     if (file_exists("{$CFG->dirroot}/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
                         $loggedinas .= ' (<a href="' . $CFG->wwwroot . '/report/log/index.php' . '?chooselog=1&amp;id=1&amp;modid=site_errors">' . get_string('logs') . '</a>)';
                     }
                     $loggedinas .= '</div>';
                 }
             }
         }
     }
     return $loggedinas;
 }
Example #30
0
 /**
  * Returns a human friendly description of the filter used as label.
  * @param array $data filter settings
  * @return string active filter label
  */
 function get_label($data)
 {
     global $DB;
     $value = $data['value'];
     $roleid = $data['roleid'];
     $categoryid = $data['categoryid'];
     $a = new stdClass();
     $a->label = $this->_label;
     if ($roleid) {
         $role = $DB->get_record('role', array('id' => $roleid));
         $a->rolename = '"' . role_get_name($role) . '"';
     } else {
         $a->rolename = get_string('anyrole', 'filters');
     }
     if ($categoryid) {
         $catname = $DB->get_field('course_categories', 'name', array('id' => $categoryid));
         $a->categoryname = '"' . format_string($catname) . '"';
     } else {
         $a->categoryname = get_string('anycategory', 'filters');
     }
     if ($value) {
         $a->coursename = '"' . s($value) . '"';
         if (!$DB->record_exists('course', array('shortname' => $value))) {
             return '<span class="notifyproblem">' . get_string('courserolelabelerror', 'filters', $a) . '</span>';
         }
     } else {
         $a->coursename = get_string('anycourse', 'filters');
     }
     return get_string('courserolelabel', 'filters', $a);
 }