Example #1
0
 public function navbar()
 {
     global $CFG;
     $items = $this->page->navbar->get_items();
     /* Added for subadmin */
     $context = get_context_instance(CONTEXT_SYSTEM);
     $roles = get_user_roles($context, $USER->id, false);
     $role = key($roles);
     $rolename = $roles[$role]->shortname;
     $htmlblocks = array();
     // Iterate the navarray and display each node
     $itemcount = count($items);
     $separator = get_separator();
     for ($i = 0; $i < $itemcount; $i++) {
         $item = $items[$i];
         $item->hideicon = true;
         if ($i === 0) {
             if ($rolename == 'subadmin') {
                 $item->action = new moodle_url($CFG->wwwroot . '/my/');
             }
             $content = html_writer::tag('li', $this->render($item));
         } else {
             $content = html_writer::tag('li', $separator . $this->render($item));
         }
         $htmlblocks[] = $content;
     }
     //accessibility: heading for navbar list  (MDL-20446)
     $navbarcontent = html_writer::tag('span', get_string('pagepath'), array('class' => 'accesshide'));
     $navbarcontent .= html_writer::tag('ul', join('', $htmlblocks), array('role' => 'navigation'));
     // XHTML
     return $navbarcontent;
 }
Example #2
0
/**
 * Obtiene el rol del usuario logeado.
 * @return string Rol {'Alumno', 'Profesor', 'Decano', 'Rector'}
 */
function get_rol()
{
    global $USER, $DB, $SESSION;
    if (isset($SESSION->rol)) {
        return $SESSION->rol;
        exit;
    }
    $context = context_system::instance();
    $rolesportada = get_user_roles($context, false);
    foreach ($rolesportada as $rol) {
        if ($rol->name == 'Rector') {
            $SESSION->rol = 'Rector';
            return 'Rector';
        }
    }
    $facultades = $DB->get_records_sql("SELECT DISTINCT {course}.category\n\t\t\t\t\t\t\t\t\t\tFROM {course} INNER JOIN {context} ON ({course}.category = {context}.instanceid)\n\t\t\t\t\t\t\t\t\t\tINNER JOIN {role_assignments} ON ({context}.id = {role_assignments}.contextid)\n\t\t\t\t\t\t\t\t\t\tINNER JOIN {role} ON ({role_assignments}.roleid = {role}.id)\n\t\t\t\t\t\t\t\t\t\tWHERE {role}.name = 'Decano' AND {role_assignments}.userid = " . $USER->id);
    if (!empty($facultades)) {
        $SESSION->rol = 'Decano';
        $SESSION->facultades = array_keys($facultades);
        return 'Decano';
    }
    $profesores = $DB->get_records_sql("SELECT DISTINCT id_profesor FROM {local_toolbox_score}");
    if (array_key_exists($USER->id, $profesores)) {
        $SESSION->rol = 'Profesor';
        return 'Profesor';
    }
    $SESSION->rol = 'Alumno';
    return 'Alumno';
}
Example #3
0
 function definition()
 {
     global $CFG, $DB;
     $mform = $this->_form;
     $user = $this->_customdata['user'];
     $course = $this->_customdata['course'];
     $context = context_course::instance($course->id);
     $assignable = $this->_customdata['assignable'];
     $assignable = array_reverse($assignable, true);
     // students first
     $ras = get_user_roles($context, $user->id, true);
     foreach ($ras as $ra) {
         unset($assignable[$ra->roleid]);
     }
     $mform->addElement('header', 'general', fullname($user));
     $mform->addElement('select', 'roleid', get_string('addrole', 'role'), $assignable);
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'user');
     $mform->setType('user', PARAM_INT);
     $mform->addElement('hidden', 'action');
     $mform->setType('action', PARAM_ALPHANUMEXT);
     $mform->addElement('hidden', 'ifilter');
     $mform->setType('ifilter', PARAM_ALPHA);
     $mform->addElement('hidden', 'page');
     $mform->setType('page', PARAM_INT);
     $mform->addElement('hidden', 'perpage');
     $mform->setType('perpage', PARAM_INT);
     $mform->addElement('hidden', 'sort');
     $mform->setType('sort', PARAM_ALPHA);
     $mform->addElement('hidden', 'dir');
     $mform->setType('dir', PARAM_ALPHA);
     $this->add_action_buttons();
     $this->set_data(array('action' => 'assign', 'user' => $user->id));
 }
Example #4
0
function logged_in()
{
    global $DB, $ip, $username, $teamid, $teamdata, $userdata;
    if (!empty($username) && !empty($userdata) && !empty($teamdata)) {
        return TRUE;
    }
    // Retrieve userdata for given AUTH_METHOD, assume not logged in
    // when userdata is empty:
    switch (AUTH_METHOD) {
        case 'FIXED':
            $username = FIXED_USER;
            $userdata = $DB->q('MAYBETUPLE SELECT * FROM user
		                    WHERE username = %s AND enabled = 1', $username);
            break;
        case 'EXTERNAL':
            if (empty($_SERVER['REMOTE_USER'])) {
                $username = $userdata = null;
            } else {
                $username = $_SERVER['REMOTE_USER'];
                $userdata = $DB->q('MAYBETUPLE SELECT * FROM user
			                    WHERE username = %s AND enabled = 1', $username);
            }
            break;
        case 'IPADDRESS':
            $userdata = $DB->q('MAYBETUPLE SELECT * FROM user
		                    WHERE ip_address = %s AND enabled = 1', $ip);
            break;
        case 'PHP_SESSIONS':
        case 'LDAP':
            if (session_id() == "") {
                session_start();
            }
            if (isset($_SESSION['username'])) {
                $userdata = $DB->q('MAYBETUPLE SELECT * FROM user
			                    WHERE username = %s AND enabled = 1', $_SESSION['username']);
            }
            break;
        default:
            error("Unknown authentication method '" . AUTH_METHOD . "' requested.");
    }
    if (!empty($userdata)) {
        $username = $userdata['username'];
        $teamdata = $DB->q('MAYBETUPLE SELECT * FROM team
		                    WHERE teamid = %i AND enabled = 1', $userdata['teamid']);
        // Pull the list of roles that a user has
        $userdata['roles'] = get_user_roles($userdata['userid']);
    }
    if (!empty($teamdata)) {
        $teamid = $teamdata['teamid'];
        // Is this the first visit? Record that in the team table.
        if (empty($teamdata['teampage_first_visited'])) {
            $hostname = gethostbyaddr($ip);
            $DB->q('UPDATE team SET teampage_first_visited = %s, hostname = %s
			        WHERE teamid = %i', now(), $hostname, $teamid);
        }
    }
    return $username !== NULL;
}
 function execute($userid, $context, $data) {
     //global $DB, $CFG, $COURSE;
     //$context = ($this->report->courseid == SITEID) ? context_system::instance() : context_course::instance($this->report->courseid);
     //$context = context_course::instance($COURSE->id);
     $roles = get_user_roles($context, $userid);
     if (!empty($roles)) {
         foreach ($roles as $rol) {
             if ($rol->roleid == $data->roleid)
                 return true;
         }
     }
     return false;
 }
Example #6
0
 function is_admin($id = 0)
 {
     $user = new Focalworks\Users\User();
     $current_user = Auth::user();
     if ($id > 0) {
         $current_user = $user::find($id);
     }
     $user_roles = get_user_roles($current_user->id);
     if (in_array(1, $user_roles)) {
         return true;
         //if admin logged in
     }
     return false;
 }
 function execute($userid, $context, $data)
 {
     global $CFG;
     $context = $this->report->courseid == SITEID ? get_context_instance(CONTEXT_SYSTEM) : get_context_instance(CONTEXT_COURSE, $this->report->courseid);
     $roles = get_user_roles($context, $userid);
     if (!empty($roles)) {
         foreach ($roles as $rol) {
             if ($rol->roleid == $data->roleid) {
                 return true;
             }
         }
     }
     return false;
 }
Example #8
0
 public function init()
 {
     parent::init();
     $this->addElement('text', 'username', array('label' => __('Username'), 'description' => __('Username must be 30 characters or fewer. Whitespace is not allowed.'), 'required' => true, 'size' => '30', 'validators' => array(array('validator' => 'NotEmpty', 'breakChainOnFailure' => true, 'options' => array('messages' => array(Zend_Validate_NotEmpty::IS_EMPTY => __('Username is required.')))), array('validator' => 'Regex', 'breakChainOnFailure' => true, 'options' => array('pattern' => '#^[a-zA-Z0-9.*@+!\\-_%\\#\\^&$]*$#u', 'messages' => array(Zend_Validate_Regex::NOT_MATCH => __('Whitespace is not allowed. Only these special characters may be used: %s', ' + ! @ # $ % ^ & * . - _')))), array('validator' => 'StringLength', 'breakChainOnFailure' => true, 'options' => array('min' => User::USERNAME_MIN_LENGTH, 'max' => User::USERNAME_MAX_LENGTH, 'messages' => array(Zend_Validate_StringLength::TOO_SHORT => __('Username must be at least %min% characters long.'), Zend_Validate_StringLength::TOO_LONG => __('Username must be at most %max% characters long.')))), array('validator' => 'Db_NoRecordExists', 'options' => array('table' => $this->_user->getTable()->getTableName(), 'field' => 'username', 'exclude' => array('field' => 'id', 'value' => (int) $this->_user->id), 'adapter' => $this->_user->getDb()->getAdapter(), 'messages' => array('recordFound' => __('This username is already in use.')))))));
     $this->addElement('text', 'name', array('label' => __('Display Name'), 'description' => __('Name as it should be displayed on the site'), 'size' => '30', 'required' => true, 'validators' => array(array('validator' => 'NotEmpty', 'breakChainOnFailure' => true, 'options' => array('messages' => array(Zend_Validate_NotEmpty::IS_EMPTY => __('Real Name is required.')))))));
     $invalidEmailMessage = __('This email address is invalid.');
     $this->addElement('text', 'email', array('label' => __('Email'), 'size' => '30', 'required' => true, 'validators' => array(array('validator' => 'NotEmpty', 'breakChainOnFailure' => true, 'options' => array('messages' => array(Zend_Validate_NotEmpty::IS_EMPTY => __('Email is required.')))), array('validator' => 'EmailAddress', 'options' => array('messages' => array(Zend_Validate_EmailAddress::INVALID => $invalidEmailMessage, Zend_Validate_EmailAddress::INVALID_FORMAT => $invalidEmailMessage, Zend_Validate_EmailAddress::INVALID_HOSTNAME => $invalidEmailMessage))), array('validator' => 'Db_NoRecordExists', 'options' => array('table' => $this->_user->getTable()->getTableName(), 'field' => 'email', 'exclude' => array('field' => 'id', 'value' => (int) $this->_user->id), 'adapter' => $this->_user->getDb()->getAdapter(), 'messages' => array('recordFound' => __('This email address is already in use.')))))));
     if ($this->_hasRoleElement) {
         $this->addElement('select', 'role', array('label' => __('Role'), 'description' => __("Roles describe the permissions a user has. See <a href='http://omeka.org/codex/User_Roles' target='_blank'>documentation</a> for details."), 'multiOptions' => get_user_roles(), 'required' => true));
     }
     if ($this->_hasActiveElement) {
         $description = __('Inactive users cannot log in to the site.');
         if ($this->_user->active == 0 && $this->_usersActivations) {
             $description .= '<br>' . __('Activation has been pending since %s.', format_date($this->_usersActivations->added));
         }
         $this->addElement('checkbox', 'active', array('label' => __('Active?'), 'description' => $description));
     }
     $this->addElement('hash', 'user_csrf', array('timeout' => 3600));
 }
Example #9
0
/**
* filters types against roles of the current user. Checks in global configuration keys
* for custom label.
* @uses $CFG.
* @uses $USER;
*
*/
function customlabel_filter_role_disabled(&$classes, $context)
{
    global $CFG, $USER;
    $roleids = array();
    $roles = get_user_roles($context, $USER->id, true);
    foreach ($roles as $role) {
        $roleids[] = $role->roleid;
    }
    for ($i = 0; $i < count($classes); $i++) {
        $typename = $classes[$i]->id;
        $globparm = "customlabel_{$typename}_hiddenfor";
        $disabledrolelist = explode(",", @$CFG->{$globparm});
        $diff = array_diff($roleids, $disabledrolelist);
        // if all roles held by user here are in disabled list, put it out.
        if (empty($diff)) {
            unset($classes[$i]);
        }
    }
}
Example #10
0
File: User.php Project: kyfr59/cg35
 public function init()
 {
     parent::init();
     $this->addElement('text', 'username', array('label' => __('Username'), 'placeholder' => "Nom d'utilisateur", 'required' => true, 'validators' => array(array('validator' => 'NotEmpty', 'options' => array('messages' => array('isEmpty' => __('Nom d\'utilisateur obligatoire.')))))));
     $this->addElement('hidden', 'name', array('label' => __('Display Name'), 'value' => 'aucun', 'placeholder' => "Nom et prénom", 'size' => '30', 'required' => true, 'validators' => array(array('validator' => 'NotEmpty', 'breakChainOnFailure' => true, 'options' => array('messages' => array(Zend_Validate_NotEmpty::IS_EMPTY => __('Nom et prénom obligatoires.')))))));
     $invalidEmailMessage = __('Adresse e-mail invalide.');
     $this->addElement('text', 'email', array('label' => __('Email'), 'placeholder' => "Adresse e-mail", 'size' => '30', 'required' => true, 'validators' => array(array('validator' => 'NotEmpty', 'breakChainOnFailure' => true, 'options' => array('messages' => array(Zend_Validate_NotEmpty::IS_EMPTY => __('Adresse  e-mail obligatoire.')))), array('validator' => 'EmailAddress', 'options' => array('messages' => array(Zend_Validate_EmailAddress::INVALID => $invalidEmailMessage, Zend_Validate_EmailAddress::INVALID_FORMAT => $invalidEmailMessage, Zend_Validate_EmailAddress::INVALID_HOSTNAME => $invalidEmailMessage))), array('validator' => 'Db_NoRecordExists', 'options' => array('table' => $this->_user->getTable()->getTableName(), 'field' => 'email', 'exclude' => array('field' => 'id', 'value' => (int) $this->_user->id), 'adapter' => $this->_user->getDb()->getAdapter(), 'messages' => array('recordFound' => __('Cette adresse e-mail est déjà utilisée.')))))));
     if ($this->_hasRoleElement) {
         $this->addElement('select', 'role', array('label' => __('Role'), 'description' => __("Les roles décrivent les permissions des utilisateurs. Voir <a href='http://omeka.org/codex/User_Roles' target='_blank'>documentation</a> pour plus d'infos."), 'multiOptions' => get_user_roles(), 'required' => true));
     }
     if ($this->_hasActiveElement) {
         $description = __('Inactive users cannot log in to the site.');
         if ($this->_user->active == 0 && $this->_usersActivations) {
             $description .= '<br>' . __('Activation en attente depuis %s.', format_date($this->_usersActivations->added));
         }
         $this->addElement('checkbox', 'active', array('label' => __('Active?'), 'description' => $description));
     }
     $this->addElement('hash', 'user_csrf', array('timeout' => 3600));
 }
Example #11
0
 /**
  * Observe the events, and dispatch them if necessary.
  *
  * @param \core\event\base $event The event.
  * @return void
  */
 protected static function verifyEvent(\core\event\base $event)
 {
     if (is_siteadmin()) {
         return;
     }
     // So executa as acoes de bloqueio caso seja aluno
     $context = context_course::instance($event->courseid);
     $userRoles = get_user_roles($context, $event->userid);
     $isStudent = false;
     if (!empty($userRoles)) {
         foreach ($userRoles as $r => $role) {
             if ($role->roleid == 5) {
                 $isStudent = true;
                 break;
             }
         }
     }
     if ($isStudent) {
         $manager = local_wsmiidle_manager::get($event->courseid);
         $manager->capture_event($event);
     }
 }
Example #12
0
/**
 * Checks if a user can assign users to a particular role in this context
 *
 * @param context $context
 * @param int $targetroleid - the id of the role you want to assign users to
 * @return boolean
 */
function user_can_assign(context $context, $targetroleid)
{
    global $DB;
    // first check if user has override capability
    // if not return false;
    if (!has_capability('moodle/role:assign', $context)) {
        return false;
    }
    // pull out all active roles of this user from this context(or above)
    if ($userroles = get_user_roles($context)) {
        foreach ($userroles as $userrole) {
            // if any in the role_allow_override table, then it's ok
            if ($DB->get_record('role_allow_assign', array('roleid' => $userrole->roleid, 'allowassign' => $targetroleid))) {
                return true;
            }
        }
    }
    return false;
}
 /**
  * Make a role assignment in the specified course using the specified role
  * id for the user whose id information is passed in the line data.
  *
  * @access public
  * @static
  * @param stdClass      $course           Course in which to make the role assignment
  * @param stdClass      $enrol_instance   Enrol instance to use for adding users to course
  * @param string        $ident_field      The field (column) name in Moodle user rec against which to query using the imported data
  * @param int           $role_id          Id of the role to use in the role assignment
  * @param boolean       $group_assign     Whether or not to assign users to groups
  * @param int           $group_id         Id of group to assign to, 0 indicates use group name from import file
  * @param boolean       $group_create     Whether or not to create new groups if needed
  * @param stored_file   $import_file      File in local repository from which to get enrollment and group data
  * @return string                         String message with results
  *
  * @uses $DB
  */
 public static function import_file(stdClass $course, stdClass $enrol_instance, $ident_field, $role_id, $group_assign, $group_id, $group_create, stored_file $import_file)
 {
     global $DB;
     // Default return value
     $result = '';
     // Need one of these in the loop
     $course_context = context_course::instance($course->id);
     // Choose the regex pattern based on the $ident_field
     switch ($ident_field) {
         case 'email':
             $regex_pattern = '/^"?\\s*([a-z0-9][\\w.%-]*@[a-z0-9][a-z0-9.-]{0,61}[a-z0-9]\\.[a-z]{2,6})\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
         case 'idnumber':
             $regex_pattern = '/^"?\\s*(\\d{1,32})\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
         default:
             $regex_pattern = '/^"?\\s*([a-z0-9][\\w@.-]*)\\s*"?(?:\\s*[;,\\t]\\s*"?\\s*([a-z0-9][\\w\' .,&-]*))?\\s*"?$/Ui';
             break;
     }
     // If doing group assignments, want to know the valid
     // groups for the course
     $selected_group = null;
     if ($group_assign) {
         if (false === ($existing_groups = groups_get_all_groups($course->id))) {
             $existing_groups = array();
         }
         if ($group_id > 0) {
             if (array_key_exists($group_id, $existing_groups)) {
                 $selected_group = $existing_groups[$group_id];
             } else {
                 // Error condition
                 return sprintf(get_string('ERR_INVALID_GROUP_ID', self::PLUGIN_NAME), $group_id);
             }
         }
     }
     // Iterate the list of active enrol plugins looking for
     // the meta course plugin
     $metacourse = false;
     $enrols_enabled = enrol_get_instances($course->id, true);
     foreach ($enrols_enabled as $enrol) {
         if ($enrol->enrol == 'meta') {
             $metacourse = true;
             break;
         }
     }
     // Get an instance of the enrol_manual_plugin (not to be confused
     // with the enrol_instance arg)
     $manual_enrol_plugin = enrol_get_plugin('manual');
     $user_rec = $new_group = $new_grouping = null;
     // Open and fetch the file contents
     $fh = $import_file->get_content_file_handle();
     $line_num = 0;
     while (false !== ($line = fgets($fh))) {
         $line_num++;
         // Clean these up for each iteration
         unset($user_rec, $new_group, $new_grouping);
         if (!($line = trim($line))) {
             continue;
         }
         // Parse the line, from which we may get one or two
         // matches since the group name is an optional item
         // on a line by line basis
         if (!preg_match($regex_pattern, $line, $matches)) {
             $result .= sprintf(get_string('ERR_PATTERN_MATCH', self::PLUGIN_NAME), $line_num, $line);
             continue;
         }
         $ident_value = $matches[1];
         $group_name = isset($matches[2]) ? $matches[2] : '';
         // User must already exist, we import enrollments
         // into courses, not users into the system. Exclude
         // records marked as deleted. Because idnumber is
         // not enforced unique, possible multiple records
         // returned when using that identifying field, so
         // use ->get_records method to make that detection
         // and inform user
         $user_rec_array = $DB->get_records('user', array($ident_field => addslashes($ident_value), 'deleted' => 0));
         // Should have one and only one record, otherwise
         // report it and move on to the next
         $user_rec_count = count($user_rec_array);
         if ($user_rec_count == 0) {
             // No record found
             $result .= sprintf(get_string('ERR_USERID_INVALID', self::PLUGIN_NAME), $line_num, $ident_value);
             continue;
         } elseif ($user_rec_count > 1) {
             // Too many records
             $result .= sprintf(get_string('ERR_USER_MULTIPLE_RECS', self::PLUGIN_NAME), $line_num, $ident_value);
             continue;
         }
         $user_rec = array_shift($user_rec_array);
         // Fetch all the role assignments this user might have for this course's context
         $roles = get_user_roles($course_context, $user_rec->id, false);
         // If a user has a role in this course, then we leave it alone and move on
         // to the group assignment if there is one. If they have no role, then we
         // should go ahead and add one, as long as it is not a metacourse.
         if (!$roles && $role_id > 0) {
             if ($metacourse) {
                 $result .= sprintf(get_string('ERR_ENROLL_META', self::PLUGIN_NAME), $line_num, $ident_value);
             } else {
                 try {
                     $manual_enrol_plugin->enrol_user($enrol_instance, $user_rec->id, $role_id);
                 } catch (Exception $exc) {
                     $result .= sprintf(get_string('ERR_ENROLL_FAILED', self::PLUGIN_NAME), $line_num, $ident_value);
                     $result .= $exc->getMessage();
                     continue;
                 }
             }
         }
         // If no group assignments, or group is from file, but no
         // group found, next line
         if (!$group_assign || $group_id == 0 && empty($group_name)) {
             continue;
         }
         // If no group pre-selected, see if group from import already
         // created for that course
         $assign_group_id = 0;
         $assign_group_name = '';
         if ($selected_group != null) {
             $assign_group_id = $selected_group->id;
             $assign_group_name = $selected_group->name;
         } else {
             foreach ($existing_groups as $existing_group) {
                 if ($existing_group->name != $group_name) {
                     continue;
                 }
                 $assign_group_id = $existing_group->id;
                 $assign_group_name = $existing_group->name;
                 break;
             }
             // No group by that name
             if ($assign_group_id == 0) {
                 // Can not create one, next line
                 if (!$group_create) {
                     continue;
                 }
                 // Make a new group for this course
                 $new_group = new stdClass();
                 $new_group->name = addslashes($group_name);
                 $new_group->courseid = $course->id;
                 if (false === ($assign_group_id = groups_create_group($new_group))) {
                     $result .= sprintf(get_string('ERR_CREATE_GROUP', self::PLUGIN_NAME), $line_num, $group_name);
                     continue;
                 } else {
                     // Add the new group to our list for the benefit of
                     // the next contestant. Strip the slashes off the
                     // name since we do a name comparison earlier when
                     // trying to find the group in our local cache and
                     // an escaped semi-colon will cause the test to fail.
                     $new_group->name = $assign_group_name = stripslashes($new_group->name);
                     $new_group->id = $assign_group_id;
                     $existing_groups[] = $new_group;
                 }
             }
             // if ($assign_group_id == 0)
         }
         // Put the user in the group if not aleady in it
         if (!groups_is_member($assign_group_id, $user_rec->id) && !groups_add_member($assign_group_id, $user_rec->id)) {
             $result .= sprintf(get_string('ERR_GROUP_MEMBER', self::PLUGIN_NAME), $line_num, $ident_value, $assign_group_name);
             continue;
         }
         // Any other work...
     }
     // while fgets
     fclose($fh);
     return empty($result) ? get_string('INF_IMPORT_SUCCESS', self::PLUGIN_NAME) : $result;
 }
/**
 * Return a list of teachers that the current user is able to open a dialogue with
 * 
 * Called by dialogue_get_available_users(). The list is used to populate a drop-down
 * list in the UI. The returned array of usernames is filtered to hide teacher names
 * if those teachers have a hidden role assignment, unless the list is being returned
 * for a teacher in which case those hidden teachers are listed
 * @param   object  $dialogue
 * @param   object  $context    for a user in this activity
 * @param   int     $editconversationid
 * @return  array   usernames and ids
 */
function dialogue_get_available_teachers($dialogue, $context, $editconversationid = 0)
{
    global $USER, $CFG;
    $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
    if (!($course = get_record('course', 'id', $dialogue->course))) {
        error('Course is misconfigured');
    }
    if (!($cm = get_coursemodule_from_instance('dialogue', $dialogue->id, $course->id))) {
        error('Course Module ID was incorrect');
    }
    // get the list of teachers (actually, those who have dialogue:manage capability)
    $hiddenTeachers = array();
    if ($users = get_users_by_capability($context, 'mod/dialogue:manage', '', null, null, null, null, null, null, true, null)) {
        foreach ($users as $user) {
            $userRoles = get_user_roles($context, $user->id, true);
            foreach ($userRoles as $role) {
                if ($role->hidden == 1) {
                    $hiddenTeachers[$user->id] = 1;
                    break;
                }
            }
        }
        $canSeeHidden = false;
        if (has_capability('moodle/role:viewhiddenassigns', $context)) {
            $canSeeHidden = true;
        }
        $groupid = get_current_group($course->id);
        foreach ($users as $otheruser) {
            // ...exclude self and ...
            if ($USER->id != $otheruser->id) {
                // ...if groupmode is SEPARATEGROUPS then exclude teachers not in student's group
                if ($groupid and groupmode($course, $cm) == SEPARATEGROUPS) {
                    if (!ismember($groupid, $otheruser->id)) {
                        continue;
                    }
                }
                if (!$canSeeHidden && array_key_exists($otheruser->id, $hiddenTeachers) && $hiddenTeachers[$otheruser->id] == 1) {
                    continue;
                }
                // ...any already in open conversations unless multiple conversations allowed
                if ($dialogue->multipleconversations or count_records_select('dialogue_conversations', "dialogueid = {$dialogue->id} AND id != {$editconversationid} AND ((userid = {$USER->id} AND \n                        recipientid = {$otheruser->id}) OR (userid = {$otheruser->id} AND \n                        recipientid = {$USER->id})) AND closed = 0") == 0) {
                    $names[$otheruser->id] = fullname($otheruser);
                }
            }
        }
    }
    if (isset($names)) {
        natcasesort($names);
        return $names;
    }
    return;
}
Example #15
0
    // Bye!
}
/// Check if the course is a meta course  (bug 5734)
if ($course->metacourse) {
    print_header_simple();
    notice(get_string('coursenotaccessible'), "{$CFG->wwwroot}/index.php");
}
/// Users can't enroll to site course
if ($course->id == SITEID) {
    print_header_simple();
    notice(get_string('enrollfirst'), "{$CFG->wwwroot}/index.php");
}
/// Double check just in case they are enrolled to start in the future
if ($course->enrolperiod) {
    // Only active if the course has an enrolment period in effect
    if ($roles = get_user_roles($context, $USER->id)) {
        foreach ($roles as $role) {
            if ($role->timestart and $role->timestart >= time()) {
                $message = get_string('enrolmentnotyet', '', userdate($student->timestart));
                print_header();
                notice($message, "{$CFG->wwwroot}/index.php");
            }
        }
    }
}
/// Check if the course is enrollable
if (!method_exists($enrol, 'print_entry')) {
    print_header_simple();
    notice(get_string('enrolmentnointernal'), "{$CFG->wwwroot}/index.php");
}
if (!$course->enrollable || $course->enrollable == 2 && $course->enrolstartdate > 0 && $course->enrolstartdate > time() || $course->enrollable == 2 && $course->enrolenddate > 0 && $course->enrolenddate <= time()) {
Example #16
0
                <span class="quick-filter-heading"><?php 
echo __("Quick Filter");
?>
</span>
            </li>
            <li>
                <a href="<?php 
echo url('guest-user/user/browse');
?>
"><?php 
echo __("View All");
?>
</a>
            </li>
            <?php 
foreach (get_user_roles() as $value => $name) {
    ?>
            <li>
                <a href="<?php 
    echo url('guest-user/user/browse', array('role' => $value));
    ?>
"><?php 
    echo __("%s", $name);
    ?>
</a>
            </li>
            <?php 
}
?>
            <li>
                <a href="<?php 
Example #17
0
function organizer_send_message($sender, $receiver, $slot, $type, $digest = null, $customdata = array())
{
    global $DB;
    if ($type == 'register_reminder:student') {
        $organizer = $slot;
    } else {
        $organizer = $DB->get_record('organizer', array('id' => $slot->organizerid));
    }
    $sender = is_int($sender) ? $DB->get_record('user', array('id' => $sender)) : $sender;
    $receiver = is_int($receiver) ? $DB->get_record('user', array('id' => $receiver)) : $receiver;
    $module = $DB->get_record('modules', array('name' => 'organizer'));
    $cm = $DB->get_record('course_modules', array('module' => $module->id, 'instance' => $organizer->id));
    $course = $DB->get_record('course', array('id' => $cm->course));
    $context = context_course::instance($cm->course);
    $roles = get_user_roles($context, $receiver->id);
    $now = time();
    if (!$cm->visible || $cm->availablefrom && $cm->availablefrom > $now || $cm->availableuntil && $cm->availableuntil < $now || count($roles) == 0) {
        return false;
    }
    $namesplit = explode(':', $type);
    $strings = new stdClass();
    $strings->sendername = fullname($sender);
    $strings->receivername = fullname($receiver);
    if ($type != 'register_reminder:student') {
        $strings->date = userdate($slot->starttime, get_string('datetemplate', 'organizer'));
        $strings->time = userdate($slot->starttime, get_string('timetemplate', 'organizer'));
        $strings->location = $slot->location;
    }
    $strings->organizername = $organizer->name;
    $strings->coursefullname = $course->fullname;
    $strings->courseshortname = $course->shortname;
    $strings->courseid = $course->idnumber == "" ? "" : $course->idnumber . ' ';
    if ($namesplit[0] == "edit_notify") {
        $strings->slot_teacher = $slot->teachervisible == 1 ? fullname($DB->get_record('user', array('id' => $slot->teacherid))) : get_string('teacherinvisible', 'organizer');
        $strings->slot_location = organizer_location_link($slot);
        $strings->slot_maxparticipants = $slot->maxparticipants;
        $strings->slot_comments = $slot->comments;
    }
    $courseurl = new moodle_url('/mod/organizer/view.php', array('id' => $cm->id));
    $strings->courselink = html_writer::link($courseurl, $course->fullname);
    if ($organizer->isgrouporganizer) {
        if (strpos($type, 'register_notify') !== false || strpos($type, 'group_registration_notify') !== false) {
            $group = groups_get_user_groups($organizer->course, $sender->id);
            $group = reset($group);
            $group = reset($group);
            $group = groups_get_group($group);
        } else {
            $group = groups_get_user_groups($organizer->course, $receiver->id);
            $group = reset($group);
            $group = reset($group);
            $group = groups_get_group($group);
        }
        $strings->groupname = $group->name;
        $type .= ":group";
    }
    if ($namesplit[0] == "eval_notify_newappointment") {
        $namesplit[0] = "eval_notify";
    }
    $message = new stdClass();
    $message->modulename = 'organizer';
    $message->component = 'mod_organizer';
    $message->name = "{$namesplit['0']}:{$namesplit['1']}";
    $message->notification = 1;
    $message->fullmessageformat = FORMAT_PLAIN;
    $message->userfrom = $sender;
    $message->userto = $receiver;
    if (isset($digest)) {
        $strings->digest = $digest;
        $type .= ":digest";
    }
    $message->subject = get_string("{$type}:subject", 'organizer', $strings);
    $message->message = get_string("{$type}:fullmessage", 'organizer', $strings);
    $message->fullmessage = get_string("{$type}:fullmessage", 'organizer', $strings);
    $message->fullmessagehtml = organizer_make_html(get_string("{$type}:fullmessage", 'organizer', $strings), $organizer, $cm, $course);
    if (isset($customdata['custommessage'])) {
        $message->fullmessage = str_replace('{$a->custommessage}', $customdata['custommessage'], $message->fullmessage);
        $message->fullmessagehtml = str_replace('{$a->custommessage}', $customdata['custommessage'], $message->fullmessagehtml);
    }
    $message->smallmessage = get_string("{$type}:smallmessage", 'organizer', $strings);
    if (ORGANIZER_ENABLE_MESSAGING) {
        return message_send($message);
    } else {
        return false;
    }
}
Example #18
0
if (!has_capability('moodle/site:accessallgroups', $context)) {
    $mastercap = false;
    $mygroups = groups_get_user_groups($courseid);
    $gids = implode(',', array_values($mygroups['0']));
    $groups = empty($gids) ? array() : $DB->get_records_select('groups', 'id IN (' . $gids . ')');
}
$globalaccess = empty($allgroups);
// Fill the course users by.
$users = array();
$users_to_roles = array();
$users_to_groups = array();
$everyone = get_enrolled_users($context, '', 0, user_picture::fields('u', array('mailformat', 'maildisplay')), "", 0, 0, true);
foreach ($everyone as $userid => $user) {
    $usergroups = groups_get_user_groups($courseid, $userid);
    $gids = ($globalaccess or $mastercap) ? array_values($usergroups['0']) : array_intersect(array_values($mygroups['0']), array_values($usergroups['0']));
    $userroles = get_user_roles($context, $userid);
    $filterd = clampmail::filter_roles($userroles, $roles);
    // Available groups.
    if (!$globalaccess and !$mastercap and empty($gids) or empty($filterd) or $userid == $USER->id) {
        continue;
    }
    $groupmapper = function ($id) use($allgroups) {
        return $allgroups[$id];
    };
    $users_to_groups[$userid] = array_map($groupmapper, $gids);
    $users_to_roles[$userid] = $filterd;
    $users[$userid] = $user;
}
if (empty($users)) {
    print_error('no_users', 'block_clampmail');
}
Example #19
0
 /**
  * Gets the roles assigned to this user that are applicable for this course.
  *
  * @param int $userid
  * @return array
  */
 public function get_user_roles($userid)
 {
     $roles = array();
     $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
     $plugins = $this->get_enrolment_plugins(false);
     foreach ($ras as $ra) {
         if ($ra->contextid != $this->context->id) {
             if (!array_key_exists($ra->roleid, $roles)) {
                 $roles[$ra->roleid] = null;
             }
             // higher ras, course always takes precedence
             continue;
         }
         if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
             continue;
         }
         $changeable = true;
         if ($ra->component) {
             $changeable = false;
             if (strpos($ra->component, 'enrol_') === 0) {
                 $plugin = substr($ra->component, 6);
                 if (isset($plugins[$plugin])) {
                     $changeable = !$plugins[$plugin]->roles_protected();
                 }
             }
         }
         $roles[$ra->roleid] = $changeable;
     }
     return $roles;
 }
Example #20
0
 function get_content()
 {
     global $CFG, $USER, $SITE, $COURSE;
     if ($this->content !== NULL) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->items = array();
     $this->content->icons = array();
     $this->content->footer = '';
     if (empty($this->instance)) {
         return $this->content = '';
     } else {
         if ($this->instance->pageid == SITEID) {
             // return $this->content = '';
         }
     }
     if (!empty($this->instance->pageid)) {
         $context = get_context_instance(CONTEXT_COURSE, $this->instance->pageid);
         if ($COURSE->id == $this->instance->pageid) {
             $course = $COURSE;
         } else {
             $course = get_record('course', 'id', $this->instance->pageid);
         }
     } else {
         $context = get_context_instance(CONTEXT_SYSTEM);
         $course = $SITE;
     }
     if (!has_capability('moodle/course:view', $context)) {
         // Just return
         return $this->content;
     }
     if (empty($CFG->loginhttps)) {
         $securewwwroot = $CFG->wwwroot;
     } else {
         $securewwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
     }
     /// Course editing on/off
     if ($course->id !== SITEID and has_capability('moodle/course:update', $context)) {
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/edit.gif" class="icon" alt="" />';
         if (isediting($this->instance->pageid)) {
             $this->content->items[] = '<a href="view.php?id=' . $this->instance->pageid . '&amp;edit=off&amp;sesskey=' . sesskey() . '">' . get_string('turneditingoff') . '</a>';
         } else {
             $this->content->items[] = '<a href="view.php?id=' . $this->instance->pageid . '&amp;edit=on&amp;sesskey=' . sesskey() . '">' . get_string('turneditingon') . '</a>';
         }
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/course/edit.php?id=' . $this->instance->pageid . '">' . get_string('settings') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/settings.gif" class="icon" alt="" />';
     }
     /// Assign roles to the course
     if ($course->id !== SITEID and has_capability('moodle/role:assign', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/' . $CFG->admin . '/roles/assign.php?contextid=' . $context->id . '">' . get_string('assignroles', 'role') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/roles.gif" class="icon" alt="" />';
     }
     /// View course grades (or just your own grades, same link)
     /// find all accessible reports
     if ($course->id !== SITEID) {
         $reportavailable = false;
         if (has_capability('moodle/grade:viewall', $context)) {
             $reportavailable = true;
         } else {
             if (!empty($course->showgrades)) {
                 if ($reports = get_list_of_plugins('grade/report')) {
                     // Get all installed reports
                     arsort($reports);
                     // user is last, we want to test it first
                     foreach ($reports as $plugin) {
                         if (has_capability('gradereport/' . $plugin . ':view', $context)) {
                             //stop when the first visible plugin is found
                             $reportavailable = true;
                             break;
                         }
                     }
                 }
             }
         }
         if ($reportavailable) {
             $this->content->items[] = '<a href="' . $CFG->wwwroot . '/grade/report/index.php?id=' . $this->instance->pageid . '">' . get_string('grades') . '</a>';
             $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/grades.gif" class="icon" alt="" />';
         }
     }
     /// Course outcomes (to help give it more prominence because it's important)
     if (!empty($CFG->enableoutcomes)) {
         if ($course->id !== SITEID and has_capability('moodle/course:update', $context)) {
             $this->content->items[] = '<a href="' . $CFG->wwwroot . '/grade/edit/outcome/course.php?id=' . $this->instance->pageid . '">' . get_string('outcomes', 'grades') . '</a>';
             $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/outcomes.gif" class="icon" alt="" />';
         }
     }
     /// Manage metacourses
     if ($course->metacourse) {
         if (has_capability('moodle/course:managemetacourse', $context)) {
             $strchildcourses = get_string('childcourses');
             $this->content->items[] = '<a href="importstudents.php?id=' . $this->instance->pageid . '">' . $strchildcourses . '</a>';
             $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/course.gif" class="icon" alt="" />';
         } else {
             if (has_capability('moodle/role:assign', $context)) {
                 $strchildcourses = get_string('childcourses');
                 $this->content->items[] = '<span class="dimmed_text">' . $strchildcourses . '</span>';
                 $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/course.gif" class="icon" alt="" />';
             }
         }
     }
     /// Manage groups in this course
     if ($course->id !== SITEID && ($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $context)) {
         $strgroups = get_string('groups');
         $this->content->items[] = '<a title="' . $strgroups . '" href="' . $CFG->wwwroot . '/group/index.php?id=' . $this->instance->pageid . '">' . $strgroups . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/group.gif" class="icon" alt="" />';
     }
     /// Backup this course
     if ($course->id !== SITEID and has_capability('moodle/site:backup', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/backup/backup.php?id=' . $this->instance->pageid . '">' . get_string('backup') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/backup.gif" class="icon" alt="" />';
     }
     /// Restore to this course
     if ($course->id !== SITEID and has_capability('moodle/site:restore', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/files/index.php?id=' . $this->instance->pageid . '&amp;wdir=/backupdata">' . get_string('restore') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/restore.gif" class="icon" alt="" />';
     }
     /// Import data from other courses
     if ($course->id !== SITEID and has_capability('moodle/site:import', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/course/import.php?id=' . $this->instance->pageid . '">' . get_string('import') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/restore.gif" class="icon" alt="" />';
     }
     /// update this course
     //TODO fix the capability used here!!!
     if ($course->id !== SITEID and has_capability('moodle/site:restore', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/backup/get_incremental.php?id=' . $COURSE->id . '">' . get_string('update') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/restore.gif" class="icon" alt="" />';
     }
     /// export this course to an offline user.
     //TODO fix the capability used here!!!
     if ($course->id !== SITEID and has_capability('moodle/site:restore', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/backup/export_incremental.php?id=' . $COURSE->id . '">' . get_string('export', 'local') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/restore.gif" class="icon" alt="" />';
     }
     /// Reset this course
     if ($course->id !== SITEID and has_capability('moodle/course:reset', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/course/reset.php?id=' . $this->instance->pageid . '">' . get_string('reset') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/return.gif" class="icon" alt="" />';
     }
     /// View course reports
     if ($course->id !== SITEID and has_capability('moodle/site:viewreports', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/course/report.php?id=' . $this->instance->pageid . '">' . get_string('reports') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/stats.gif" class="icon" alt="" />';
     }
     /// Manage questions
     if ($course->id !== SITEID) {
         $questionlink = '';
         $questioncaps = array('moodle/question:add', 'moodle/question:editmine', 'moodle/question:editall', 'moodle/question:viewmine', 'moodle/question:viewall', 'moodle/question:movemine', 'moodle/question:moveall');
         foreach ($questioncaps as $questioncap) {
             if (has_capability($questioncap, $context)) {
                 $questionlink = 'edit.php';
                 break;
             }
         }
         if (!$questionlink && has_capability('moodle/question:managecategory', $context)) {
             $questionlink = 'category.php';
         }
         if ($questionlink) {
             $this->content->items[] = '<a href="' . $CFG->wwwroot . '/question/' . $questionlink . '?courseid=' . $this->instance->pageid . '">' . get_string('questions', 'quiz') . '</a>';
             $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/questions.gif" class="icon" alt="" />';
         }
     }
     /// Manage files
     if ($course->id !== SITEID and has_capability('moodle/course:managefiles', $context)) {
         $this->content->items[] = '<a href="' . $CFG->wwwroot . '/files/index.php?id=' . $this->instance->pageid . '">' . get_string('files') . '</a>';
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/files.gif" class="icon" alt="" />';
     }
     /// Authorize hooks
     if ($course->enrol == 'authorize' || empty($course->enrol) && $CFG->enrol == 'authorize' && $course->id !== SITEID) {
         require_once $CFG->dirroot . '/enrol/authorize/const.php';
         $paymenturl = '<a href="' . $CFG->wwwroot . '/enrol/authorize/index.php?course=' . $course->id . '">' . get_string('payments') . '</a> ';
         if (has_capability('enrol/authorize:managepayments', $context)) {
             if ($cnt = count_records('enrol_authorize', 'status', AN_STATUS_AUTH, 'courseid', $course->id)) {
                 $paymenturl .= '<a href="' . $CFG->wwwroot . '/enrol/authorize/index.php?status=' . AN_STATUS_AUTH . '&amp;course=' . $course->id . '">' . get_string('paymentpending', 'moodle', $cnt) . '</a>';
             }
         }
         $this->content->items[] = $paymenturl;
         $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/payment.gif" class="icon" alt="" />';
     }
     /// Unenrol link
     if (empty($course->metacourse) && $course->id !== SITEID) {
         if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
             // Are a guest now
             $this->content->items[] = '<a href="enrol.php?id=' . $this->instance->pageid . '">' . get_string('enrolme', '', format_string($course->shortname)) . '</a>';
             $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/user.gif" class="icon" alt="" />';
         } else {
             if (has_capability('moodle/role:unassignself', $context, NULL, false) and get_user_roles($context, $USER->id, false)) {
                 // Have some role
                 $this->content->items[] = '<a href="unenrol.php?id=' . $this->instance->pageid . '">' . get_string('unenrolme', '', format_string($course->shortname)) . '</a>';
                 $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/user.gif" class="icon" alt="" />';
             }
         }
     }
     /// Link to the user own profile
     $this->content->items[] = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $USER->id . '&amp;course=' . $course->id . '">' . get_string('profile') . '</a>';
     $this->content->icons[] = '<img src="' . $CFG->pixpath . '/i/user.gif" alt="" />';
     return $this->content;
 }
Example #21
0
/**
 *
 * Give user record from mdl_user, build an array conntains
 * all user details
 *
 * Warning: description file urls are 'webservice/pluginfile.php' is use.
 *          it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
 *
 * @param stdClass $user user record from mdl_user
 * @param stdClass $context context object
 * @param stdClass $course moodle course
 * @param array $userfields required fields
 * @return array|null
 */
function user_get_user_details($user, $course = null, array $userfields = array())
{
    global $USER, $DB, $CFG;
    require_once $CFG->dirroot . "/user/profile/lib.php";
    //custom field library
    require_once $CFG->dirroot . "/lib/filelib.php";
    // file handling on description and friends
    $defaultfields = user_get_default_fields();
    if (empty($userfields)) {
        $userfields = $defaultfields;
    }
    foreach ($userfields as $thefield) {
        if (!in_array($thefield, $defaultfields)) {
            throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
        }
    }
    // Make sure id and fullname are included
    if (!in_array('id', $userfields)) {
        $userfields[] = 'id';
    }
    if (!in_array('fullname', $userfields)) {
        $userfields[] = 'fullname';
    }
    if (!empty($course)) {
        $context = context_course::instance($course->id);
        $usercontext = context_user::instance($user->id);
        $canviewdetailscap = has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext);
    } else {
        $context = context_user::instance($user->id);
        $usercontext = $context;
        $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
    }
    $currentuser = $user->id == $USER->id;
    $isadmin = is_siteadmin($USER);
    $showuseridentityfields = get_extra_user_fields($context);
    if (!empty($course)) {
        $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
    } else {
        $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
    }
    $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
    if (!empty($course)) {
        $canviewuseremail = has_capability('moodle/course:useremail', $context);
    } else {
        $canviewuseremail = false;
    }
    $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
    if (!empty($course)) {
        $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
    } else {
        $canaccessallgroups = false;
    }
    if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
        // skip this user details
        return null;
    }
    $userdetails = array();
    $userdetails['id'] = $user->id;
    if (($isadmin or $currentuser) and in_array('username', $userfields)) {
        $userdetails['username'] = $user->username;
    }
    if ($isadmin or $canviewfullnames) {
        if (in_array('firstname', $userfields)) {
            $userdetails['firstname'] = $user->firstname;
        }
        if (in_array('lastname', $userfields)) {
            $userdetails['lastname'] = $user->lastname;
        }
    }
    $userdetails['fullname'] = fullname($user);
    if (in_array('customfields', $userfields)) {
        $fields = $DB->get_recordset_sql("SELECT f.*\n                                            FROM {user_info_field} f\n                                            JOIN {user_info_category} c\n                                                 ON f.categoryid=c.id\n                                        ORDER BY c.sortorder ASC, f.sortorder ASC");
        $userdetails['customfields'] = array();
        foreach ($fields as $field) {
            require_once $CFG->dirroot . '/user/profile/field/' . $field->datatype . '/field.class.php';
            $newfield = 'profile_field_' . $field->datatype;
            $formfield = new $newfield($field->id, $user->id);
            if ($formfield->is_visible() and !$formfield->is_empty()) {
                $userdetails['customfields'][] = array('name' => $formfield->field->name, 'value' => $formfield->data, 'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
            }
        }
        $fields->close();
        // unset customfields if it's empty
        if (empty($userdetails['customfields'])) {
            unset($userdetails['customfields']);
        }
    }
    // profile image
    if (in_array('profileimageurl', $userfields)) {
        $profileimageurl = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f1');
        $userdetails['profileimageurl'] = $profileimageurl->out(false);
    }
    if (in_array('profileimageurlsmall', $userfields)) {
        $profileimageurlsmall = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f2');
        $userdetails['profileimageurlsmall'] = $profileimageurlsmall->out(false);
    }
    //hidden user field
    if ($canviewhiddenuserfields) {
        $hiddenfields = array();
        // address, phone1 and phone2 not appears in hidden fields list
        // but require viewhiddenfields capability
        // according to user/profile.php
        if ($user->address && in_array('address', $userfields)) {
            $userdetails['address'] = $user->address;
        }
    } else {
        $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
    }
    if ($user->phone1 && in_array('phone1', $userfields) && (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
        $userdetails['phone1'] = $user->phone1;
    }
    if ($user->phone2 && in_array('phone2', $userfields) && (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
        $userdetails['phone2'] = $user->phone2;
    }
    if (isset($user->description) && (!isset($hiddenfields['description']) && !$cannotviewdescription or $isadmin)) {
        if (in_array('description', $userfields)) {
            // Always return the descriptionformat if description is requested.
            list($userdetails['description'], $userdetails['descriptionformat']) = external_format_text($user->description, $user->descriptionformat, $usercontext->id, 'user', 'profile', null);
        }
    }
    if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
        $userdetails['country'] = $user->country;
    }
    if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
        $userdetails['city'] = $user->city;
    }
    if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
        $url = $user->url;
        if (strpos($user->url, '://') === false) {
            $url = 'http://' . $url;
        }
        $user->url = clean_param($user->url, PARAM_URL);
        $userdetails['url'] = $user->url;
    }
    if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
        $userdetails['icq'] = $user->icq;
    }
    if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
        $userdetails['skype'] = $user->skype;
    }
    if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
        $userdetails['yahoo'] = $user->yahoo;
    }
    if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
        $userdetails['aim'] = $user->aim;
    }
    if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
        $userdetails['msn'] = $user->msn;
    }
    if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
        if ($user->firstaccess) {
            $userdetails['firstaccess'] = $user->firstaccess;
        } else {
            $userdetails['firstaccess'] = 0;
        }
    }
    if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
        if ($user->lastaccess) {
            $userdetails['lastaccess'] = $user->lastaccess;
        } else {
            $userdetails['lastaccess'] = 0;
        }
    }
    if (in_array('email', $userfields) && ($isadmin or $currentuser or $canviewuseremail or in_array('email', $showuseridentityfields) or $user->maildisplay == 1 or $user->maildisplay == 2 and enrol_sharing_course($user, $USER))) {
        $userdetails['email'] = $user->email;
    }
    if (in_array('interests', $userfields) && !empty($CFG->usetags)) {
        require_once $CFG->dirroot . '/tag/lib.php';
        if ($interests = tag_get_tags_csv('user', $user->id, TAG_RETURN_TEXT)) {
            $userdetails['interests'] = $interests;
        }
    }
    //Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
    if ($isadmin or $currentuser or in_array('idnumber', $showuseridentityfields)) {
        if (in_array('idnumber', $userfields) && $user->idnumber) {
            $userdetails['idnumber'] = $user->idnumber;
        }
    }
    if ($isadmin or $currentuser or in_array('institution', $showuseridentityfields)) {
        if (in_array('institution', $userfields) && $user->institution) {
            $userdetails['institution'] = $user->institution;
        }
    }
    if ($isadmin or $currentuser or in_array('department', $showuseridentityfields)) {
        if (in_array('department', $userfields) && isset($user->department)) {
            //isset because it's ok to have department 0
            $userdetails['department'] = $user->department;
        }
    }
    if (in_array('roles', $userfields) && !empty($course)) {
        // not a big secret
        $roles = get_user_roles($context, $user->id, false);
        $userdetails['roles'] = array();
        foreach ($roles as $role) {
            $userdetails['roles'][] = array('roleid' => $role->roleid, 'name' => $role->name, 'shortname' => $role->shortname, 'sortorder' => $role->sortorder);
        }
    }
    // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group
    if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
        $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name,g.description,g.descriptionformat');
        $userdetails['groups'] = array();
        foreach ($usergroups as $group) {
            list($group->description, $group->descriptionformat) = external_format_text($group->description, $group->descriptionformat, $context->id, 'group', 'description', $group->id);
            $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name, 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
        }
    }
    //list of courses where the user is enrolled
    if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
        $enrolledcourses = array();
        if ($mycourses = enrol_get_users_courses($user->id, true)) {
            foreach ($mycourses as $mycourse) {
                if ($mycourse->category) {
                    $coursecontext = context_course::instance($mycourse->id);
                    $enrolledcourse = array();
                    $enrolledcourse['id'] = $mycourse->id;
                    $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
                    $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
                    $enrolledcourses[] = $enrolledcourse;
                }
            }
            $userdetails['enrolledcourses'] = $enrolledcourses;
        }
    }
    //user preferences
    if (in_array('preferences', $userfields) && $currentuser) {
        $preferences = array();
        $userpreferences = get_user_preferences();
        foreach ($userpreferences as $prefname => $prefvalue) {
            $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
        }
        $userdetails['preferences'] = $preferences;
    }
    return $userdetails;
}
Example #22
0
/**
 * Add navigation nodes
 * @param navigation_node $coursenode
 * @param object $course
 * @return void
 */
function enrol_add_course_navigation(navigation_node $coursenode, $course)
{
    global $CFG;
    $coursecontext = context_course::instance($course->id);
    $instances = enrol_get_instances($course->id, true);
    $plugins = enrol_get_plugins(true);
    // we do not want to break all course pages if there is some borked enrol plugin, right?
    foreach ($instances as $k => $instance) {
        if (!isset($plugins[$instance->enrol])) {
            unset($instances[$k]);
        }
    }
    $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
    if ($course->id != SITEID) {
        // list all participants - allows assigning roles, groups, etc.
        if (has_capability('moodle/course:enrolreview', $coursecontext)) {
            $url = new moodle_url('/enrol/users.php', array('id' => $course->id));
            $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/enrolusers', ''));
        }
        // manage enrol plugin instances
        if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
            $url = new moodle_url('/enrol/instances.php', array('id' => $course->id));
        } else {
            $url = NULL;
        }
        $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
        // each instance decides how to configure itself or how many other nav items are exposed
        foreach ($instances as $instance) {
            if (!isset($plugins[$instance->enrol])) {
                continue;
            }
            $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
        }
        if (!$url) {
            $instancesnode->trim_if_empty();
        }
    }
    // Manage groups in this course or even frontpage
    if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
        $url = new moodle_url('/group/index.php', array('id' => $course->id));
        $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
    }
    if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:review'), $coursecontext)) {
        // Override roles
        if (has_capability('moodle/role:review', $coursecontext)) {
            $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $coursecontext->id));
        } else {
            $url = NULL;
        }
        $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
        // Add assign or override roles if allowed
        if ($course->id == SITEID or !empty($CFG->adminsassignrolesincourse) and is_siteadmin()) {
            if (has_capability('moodle/role:assign', $coursecontext)) {
                $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $coursecontext->id));
                $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
            }
        }
        // Check role permissions
        if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
            $url = new moodle_url('/admin/roles/check.php', array('contextid' => $coursecontext->id));
            $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
        }
    }
    // Deal somehow with users that are not enrolled but still got a role somehow
    if ($course->id != SITEID) {
        //TODO, create some new UI for role assignments at course level
        if (has_capability('moodle/role:assign', $coursecontext)) {
            /* Added for Subadmin */
            $context = get_context_instance(CONTEXT_SYSTEM);
            $roles = get_user_roles($context, $USER->id, false);
            $role = key($roles);
            $currentuserrolename = $roles[$role]->shortname;
            /* End of Subadmin */
            if ($currentuserrolename != "subadmin") {
                $url = new moodle_url('/enrol/otherusers.php', array('id' => $course->id));
                $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
            }
        }
    }
    // just in case nothing was actually added
    $usersnode->trim_if_empty();
    if ($course->id != SITEID) {
        if (isguestuser() or !isloggedin()) {
            // guest account can not be enrolled - no links for them
        } else {
            if (is_enrolled($coursecontext)) {
                // unenrol link if possible
                foreach ($instances as $instance) {
                    if (!isset($plugins[$instance->enrol])) {
                        continue;
                    }
                    $plugin = $plugins[$instance->enrol];
                    if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
                        $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
                        $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
                        break;
                        //TODO. deal with multiple unenrol links - not likely case, but still...
                    }
                }
            } else {
                // enrol link if possible
                if (is_viewing($coursecontext)) {
                    // better not show any enrol link, this is intended for managers and inspectors
                } else {
                    foreach ($instances as $instance) {
                        if (!isset($plugins[$instance->enrol])) {
                            continue;
                        }
                        $plugin = $plugins[$instance->enrol];
                        if ($plugin->show_enrolme_link($instance)) {
                            $url = new moodle_url('/enrol/index.php', array('id' => $course->id));
                            $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
                            $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
                            break;
                        }
                    }
                }
            }
        }
    }
}
Example #23
0
/**
 * Like get_user_roles, but adds in the authenticated user role, and the front
 * page roles, if applicable.
 *
 * @param context $context the context.
 * @param int $userid optional. Defaults to $USER->id
 * @return array of objects with fields ->userid, ->contextid and ->roleid.
 */
function get_user_roles_with_special(context $context, $userid = 0) {
    global $CFG, $USER;

    if (empty($userid)) {
        if (empty($USER->id)) {
            return array();
        }
        $userid = $USER->id;
    }

    $ras = get_user_roles($context, $userid);

    // Add front-page role if relevant.
    $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
    $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
            is_inside_frontpage($context);
    if ($defaultfrontpageroleid && $isfrontpage) {
        $frontpagecontext = context_course::instance(SITEID);
        $ra = new stdClass();
        $ra->userid = $userid;
        $ra->contextid = $frontpagecontext->id;
        $ra->roleid = $defaultfrontpageroleid;
        $ras[] = $ra;
    }

    // Add authenticated user role if relevant.
    $defaultuserroleid      = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
    if ($defaultuserroleid && !isguestuser($userid)) {
        $systemcontext = context_system::instance();
        $ra = new stdClass();
        $ra->userid = $userid;
        $ra->contextid = $systemcontext->id;
        $ra->roleid = $defaultuserroleid;
        $ras[] = $ra;
    }

    return $ras;
}
Example #24
0
                </header>
            </div>
            <div class="clear"></div>
            <nav id="menu">
                <ul>
                    <li class="active"><a href="<?php 
    echo $CFG->wwwroot;
    ?>
/local/tpelearning/index.php?id=2"><?php 
    echo get_string("title_livesesson", "local_tpelearning");
    ?>
</a></li>
                    <?php 
    if ($viewmanager) {
        $context = context_course::instance($CFG->tpe_config->courseid);
        $roles = get_user_roles($context, $USER->id, true);
        foreach ($roles as $value) {
            $rolePOHC = $value->shortname;
        }
        if ($rolePOHC == 'pohc') {
            ?>
                            <li><a href="<?php 
            echo $CFG->wwwroot;
            ?>
/local/tpebbb/techroom.php?id=2"><?php 
            echo get_string("techroom", "theme_topmito");
            ?>
</a></li>
                            <li><a href="<?php 
            echo $CFG->wwwroot;
            ?>
Example #25
0
<?php

// This file defines settingpages and externalpages under the "users" category
/*Added for subadmin */
$context = get_context_instance(CONTEXT_SYSTEM);
$roles = get_user_roles($context, $USER->id, false);
$role = key($roles);
$rolename = $roles[$role]->shortname;
/* End of subadmin */
$ADMIN->add('users', new admin_category('accounts', new lang_string('accounts', 'admin')));
if ($rolename != 'subadmin') {
    $ADMIN->add('users', new admin_category('roles', new lang_string('permissions', 'role')));
    $ADMIN->add('users', new admin_category('subadmin', new lang_string('subadmin', 'admin')));
    $ADMIN->add('subadmin', new admin_externalpage('regionlist', new lang_string('regionlist', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/user/region_user_list.php", array('moodle/role:assign', 'moodle/role:manage')));
    $ADMIN->add('subadmin', new admin_externalpage('assignregions', new lang_string('assignregions', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/user/add_region_user.php", array('moodle/role:assign', 'moodle/role:manage')));
}
if ($hassiteconfig or has_capability('moodle/user:create', $systemcontext) or has_capability('moodle/user:update', $systemcontext) or has_capability('moodle/user:delete', $systemcontext) or has_capability('moodle/role:manage', $systemcontext) or has_capability('moodle/role:assign', $systemcontext) or has_capability('moodle/cohort:manage', $systemcontext) or has_capability('moodle/cohort:view', $systemcontext)) {
    // speedup for non-admins, add all caps used on this page
    if (empty($CFG->loginhttps)) {
        $securewwwroot = $CFG->wwwroot;
    } else {
        $securewwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
    }
    // stuff under the "accounts" subcategory
    $ADMIN->add('accounts', new admin_externalpage('editusers', new lang_string('userlist', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/user.php", array('moodle/user:update', 'moodle/user:delete')));
    if ($rolename != 'subadmin') {
        $ADMIN->add('accounts', new admin_externalpage('userbulk', new lang_string('userbulk', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/user/user_bulk.php", array('moodle/user:update', 'moodle/user:delete')));
    }
    $ADMIN->add('accounts', new admin_externalpage('addnewuser', new lang_string('addnewuser'), "{$securewwwroot}/user/editadvanced.php?id=-1", 'moodle/user:create'));
    $ADMIN->add('accounts', new admin_externalpage('profilefields', new lang_string('profilefields', 'admin'), "{$CFG->wwwroot}/user/profile/index.php", 'moodle/site:config'));
    if ($rolename != 'subadmin') {
Example #26
0
 /**
  * Gets the roles assigned to this user that are applicable for this course.
  *
  * @param int $userid
  * @return array
  */
 public function get_user_roles($userid) {
     $roles = array();
     $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
     foreach ($ras as $ra) {
         if ($ra->contextid != $this->context->id) {
             if (!array_key_exists($ra->roleid, $roles)) {
                 $roles[$ra->roleid] = null;
             }
             // higher ras, course always takes precedence
             continue;
         }
         if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
             continue;
         }
         $roles[$ra->roleid] = ($ra->itemid == 0 and $ra->component === '');
     }
     return $roles;
 }
Example #27
0
    $userid = 0;
}
if (!($course = $DB->get_record('course', array('id' => $id)))) {
    print_error('invalidcourseid');
}
if (!($context = get_context_instance(CONTEXT_COURSE, $course->id))) {
    print_error('invalidcontext');
}
require_login($course->id);
if ($course->metacourse) {
    print_error('cantunenrollfrommetacourse', '', $CFG->wwwroot . '/course/view.php?id=' . $course->id);
}
if ($userid) {
    // Unenrolling someone else
    require_capability('moodle/role:assign', $context, NULL, false);
    $roles = get_user_roles($context, $userid, false);
    // verify user may unassign all roles at course context
    foreach ($roles as $role) {
        if (!user_can_assign($context, $role->roleid)) {
            print_error('cannotunassignrolefrom', '', '', $role->roleid);
        }
    }
} else {
    // Unenrol yourself
    require_capability('moodle/role:unassignself', $context, NULL, false);
}
if (!empty($USER->access['rsw'][$context->path])) {
    print_error('cantunenrollinthisrole', '', $CFG->wwwroot . '/course/view.php?id=' . $course->id);
}
if ($confirm and confirm_sesskey()) {
    if ($userid) {
Example #28
0
/**
 * Prints a summary of a user in a nice little box.
 *
 * @uses $CFG
 * @uses $USER
 * @param user $user A {@link $USER} object representing a user
 * @param course $course A {@link $COURSE} object representing a course
 */
function print_user($user, $course, $messageselect = false, $return = false)
{
    global $CFG, $USER;
    $output = '';
    static $string;
    static $datestring;
    static $countries;
    $context = get_context_instance(CONTEXT_COURSE, $course->id);
    if (isset($user->context->id)) {
        $usercontext = $user->context;
    } else {
        $usercontext = get_context_instance(CONTEXT_USER, $user->id);
    }
    if (empty($string)) {
        // Cache all the strings for the rest of the page
        $string->email = get_string('email');
        $string->city = get_string('city');
        $string->lastaccess = get_string('lastaccess');
        $string->activity = get_string('activity');
        $string->unenrol = get_string('unenrol');
        $string->loginas = get_string('loginas');
        $string->fullprofile = get_string('fullprofile');
        $string->role = get_string('role');
        $string->name = get_string('name');
        $string->never = get_string('never');
        $datestring->day = get_string('day');
        $datestring->days = get_string('days');
        $datestring->hour = get_string('hour');
        $datestring->hours = get_string('hours');
        $datestring->min = get_string('min');
        $datestring->mins = get_string('mins');
        $datestring->sec = get_string('sec');
        $datestring->secs = get_string('secs');
        $datestring->year = get_string('year');
        $datestring->years = get_string('years');
        $countries = get_list_of_countries();
    }
    /// Get the hidden field list
    if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
        $hiddenfields = array();
    } else {
        $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
    }
    $output .= '<table class="userinfobox">';
    $output .= '<tr>';
    $output .= '<td class="left side">';
    $output .= print_user_picture($user, $course->id, $user->picture, true, true);
    $output .= '</td>';
    $output .= '<td class="content">';
    $output .= '<div class="username">' . fullname($user, has_capability('moodle/site:viewfullnames', $context)) . '</div>';
    $output .= '<div class="info">';
    if (!empty($user->role)) {
        $output .= $string->role . ': ' . $user->role . '<br />';
    }
    if ($user->maildisplay == 1 or $user->maildisplay == 2 and $course->id != SITEID and !isguest() or has_capability('moodle/course:viewhiddenuserfields', $context)) {
        $output .= $string->email . ': <a href="mailto:' . $user->email . '">' . $user->email . '</a><br />';
    }
    if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
        $output .= $string->city . ': ';
        if ($user->city && !isset($hiddenfields['city'])) {
            $output .= $user->city;
        }
        if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
            if ($user->city && !isset($hiddenfields['city'])) {
                $output .= ', ';
            }
            $output .= $countries[$user->country];
        }
        $output .= '<br />';
    }
    if (!isset($hiddenfields['lastaccess'])) {
        if ($user->lastaccess) {
            $output .= $string->lastaccess . ': ' . userdate($user->lastaccess);
            $output .= '&nbsp; (' . format_time(time() - $user->lastaccess, $datestring) . ')';
        } else {
            $output .= $string->lastaccess . ': ' . $string->never;
        }
    }
    $output .= '</div></td><td class="links">';
    //link to blogs
    if ($CFG->bloglevel > 0) {
        $output .= '<a href="' . $CFG->wwwroot . '/blog/index.php?userid=' . $user->id . '">' . get_string('blogs', 'blog') . '</a><br />';
    }
    //link to notes
    if (!empty($CFG->enablenotes) and has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) {
        $output .= '<a href="' . $CFG->wwwroot . '/notes/index.php?course=' . $course->id . '&amp;user='******'">' . get_string('notes', 'notes') . '</a><br />';
    }
    if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
        $output .= '<a href="' . $CFG->wwwroot . '/course/user.php?id=' . $course->id . '&amp;user='******'">' . $string->activity . '</a><br />';
    }
    if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id, false)) {
        // I can unassing and user has some role
        $output .= '<a href="' . $CFG->wwwroot . '/course/unenrol.php?id=' . $course->id . '&amp;user='******'">' . $string->unenrol . '</a><br />';
    }
    if ($USER->id != $user->id && !session_is_loggedinas() && has_capability('moodle/user:loginas', $context) && !has_capability('moodle/site:doanything', $context, $user->id, false)) {
        $output .= '<a href="' . $CFG->wwwroot . '/course/loginas.php?id=' . $course->id . '&amp;user='******'&amp;sesskey=' . sesskey() . '">' . $string->loginas . '</a><br />';
    }
    $output .= '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '&amp;course=' . $course->id . '">' . $string->fullprofile . '...</a>';
    if (!empty($messageselect)) {
        $output .= '<br /><input type="checkbox" name="user' . $user->id . '" /> ';
    }
    $output .= '</td></tr></table>';
    if ($return) {
        return $output;
    } else {
        echo $output;
    }
}
Example #29
0
                 $topleveladmin = true;
             }
         }
     }
     foreach ($frm->removeselect as $removeuser) {
         $removeuser = clean_param($removeuser, PARAM_INT);
         if ($topleveladmin && $removeuser == $USER->id) {
             // Prevent unassigning oneself from being admin
             continue;
         }
         if (!role_unassign($roleid, $removeuser, 0, $context->id)) {
             $errors[] = "Could not remove user with id {$removeuser} from this role!";
         } else {
             if ($inmeta) {
                 sync_metacourse($courseid);
                 $newroles = get_user_roles($context, $removeuser, false);
                 if (!empty($newroles) and !array_key_exists($roleid, $newroles)) {
                     $erruser = get_record('user', 'id', $removeuser, '', '', '', '', 'id, firstname, lastname');
                     $errors[] = get_string('metaunassignerror', 'role', fullname($erruser));
                     $allow = false;
                 }
             }
         }
     }
     $rolename = get_field('role', 'name', 'id', $roleid);
     add_to_log($course->id, 'role', 'unassign', 'admin/roles/assign.php?contextid=' . $context->id . '&roleid=' . $roleid, $rolename, '', $USER->id);
 } else {
     if ($showall) {
         $searchtext = '';
         $previoussearch = 0;
     }
                 default:
                     $ok = enrol_student($user->id, $course->id);
                     break;
             }
         }
         if ($ok) {
             // OK
             echo $strindent . get_string('enrolledincourse', '', $addcourse) . '<br />';
         } else {
             notify(get_string('erroronline', 'error', $linenum) . ': ' . get_string('enrolledincoursenot', '', $addcourse));
         }
         // find group to add to
         if ($addgroup = @$user->{'group' . $ncourses}) {
             if ($gid =& groups_get_group_by_name($course->id, $addgroup)) {
                 $coursecontext =& get_context_instance(CONTEXT_COURSE, $course->id);
                 if (count(get_user_roles($coursecontext, $user->id))) {
                     if (groups_add_member($gid, $user->id)) {
                         echo $strindent . get_string('addedtogroup', '', $addgroup) . '<br />';
                     } else {
                         notify(get_string('erroronline', 'error', $linenum) . ': ' . get_string('addedtogroupnot', '', $addgroup));
                     }
                 } else {
                     notify(get_string('erroronline', 'error', $linenum) . ': ' . get_string('addedtogroupnotenrolled', '', $addgroup));
                 }
             } else {
                 notify(get_string('erroronline', 'error', $linenum) . ': ' . get_string('groupunknown', 'error', $addgroup));
             }
         }
     }
 }
 echo '</p>';