protected function get_other_values(renderer_base $output) { global $PAGE, $CFG; // Add user picture. $userpicture = new \user_picture($this->data); $userpicture->size = 1; // Size f1. $profileimageurl = $userpicture->get_url($PAGE)->out(false); $userpicture->size = 0; // Size f2. $profileimageurlsmall = $userpicture->get_url($PAGE)->out(false); $profileurl = (new moodle_url('/user/profile.php', array('id' => $this->data->id)))->out(false); $identityfields = array_flip(explode(',', $CFG->showuseridentity)); $data = $this->data; foreach ($identityfields as $field => $index) { if (!empty($data->{$field})) { $identityfields[$field] = $data->{$field}; } else { unset($identityfields[$field]); } } $identity = implode(', ', $identityfields); return array('fullname' => fullname($this->data), 'profileimageurl' => $profileimageurl, 'profileimageurlsmall' => $profileimageurlsmall, 'profileurl' => $profileurl, 'identity' => $identity); }
/** * Test the update user profile image function. */ public function test_update_user_profile_image() { global $DB, $CFG; // Set the profile image. \enrol_lti\helper::update_user_profile_image($this->user1->id, $this->getExternalTestFileUrl('/test.jpg')); // Get the new user record. $this->user1 = $DB->get_record('user', array('id' => $this->user1->id)); // Set the page details. $page = new moodle_page(); $page->set_url('/user/profile.php'); $page->set_context(context_system::instance()); $renderer = $page->get_renderer('core'); $usercontext = context_user::instance($this->user1->id); // Get the user's profile picture and make sure it is correct. $userpicture = new user_picture($this->user1); $this->assertSame($CFG->wwwroot . '/pluginfile.php/' . $usercontext->id . '/user/icon/clean/f2?rev=' . $this->user1->picture, $userpicture->get_url($page, $renderer)->out(false)); }
/** * Adds the extra fields to user object required for * displaying user avatar. * * @global moodle_page $PAGE * @param stdClass $user */ function dialogue_add_user_picture_fields(stdClass &$user) { global $PAGE; $user->fullname = fullname($user); $userpic = new user_picture($user); $imageurl = $userpic->get_url($PAGE); $user->imageurl = $imageurl->out(); if (empty($user->imagealt)) { $user->imagealt = get_string('pictureof', '', $user->fullname); } return; }
/** * Test get forum discussions paginated */ public function test_mod_forum_get_forum_discussions_paginated() { global $USER, $CFG, $DB, $PAGE; $this->resetAfterTest(true); // Set the CFG variable to allow track forums. $CFG->forum_trackreadposts = true; // Create a user who can track forums. $record = new stdClass(); $record->trackforums = true; $user1 = self::getDataGenerator()->create_user($record); // Create a bunch of other users to post. $user2 = self::getDataGenerator()->create_user(); $user3 = self::getDataGenerator()->create_user(); $user4 = self::getDataGenerator()->create_user(); // Set the first created user to the test user. self::setUser($user1); // Create courses to add the modules. $course1 = self::getDataGenerator()->create_course(); // First forum with tracking off. $record = new stdClass(); $record->course = $course1->id; $record->trackingtype = FORUM_TRACKING_OFF; $forum1 = self::getDataGenerator()->create_module('forum', $record); // Add discussions to the forums. $record = new stdClass(); $record->course = $course1->id; $record->userid = $user1->id; $record->forum = $forum1->id; $discussion1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_discussion($record); // Add three replies to the discussion 1 from different users. $record = new stdClass(); $record->discussion = $discussion1->id; $record->parent = $discussion1->firstpost; $record->userid = $user2->id; $discussion1reply1 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record); $record->parent = $discussion1reply1->id; $record->userid = $user3->id; $discussion1reply2 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record); $record->userid = $user4->id; $discussion1reply3 = self::getDataGenerator()->get_plugin_generator('mod_forum')->create_post($record); // Enrol the user in the first course. $enrol = enrol_get_plugin('manual'); // We don't use the dataGenerator as we need to get the $instance2 to unenrol later. $enrolinstances = enrol_get_instances($course1->id, true); foreach ($enrolinstances as $courseenrolinstance) { if ($courseenrolinstance->enrol == "manual") { $instance1 = $courseenrolinstance; break; } } $enrol->enrol_user($instance1, $user1->id); // Delete one user. delete_user($user4); // Assign capabilities to view discussions for forum 1. $cm = get_coursemodule_from_id('forum', $forum1->cmid, 0, false, MUST_EXIST); $context = context_module::instance($cm->id); $newrole = create_role('Role 2', 'role2', 'Role 2 description'); $this->assignUserCapability('mod/forum:viewdiscussion', $context->id, $newrole); // Create what we expect to be returned when querying the forums. $post1 = $DB->get_record('forum_posts', array('id' => $discussion1->firstpost), '*', MUST_EXIST); // User pictures are initially empty, we should get the links once the external function is called. $expecteddiscussions = array('id' => $discussion1->firstpost, 'name' => $discussion1->name, 'groupid' => $discussion1->groupid, 'timemodified' => $discussion1reply3->created, 'usermodified' => $discussion1reply3->userid, 'timestart' => $discussion1->timestart, 'timeend' => $discussion1->timeend, 'discussion' => $discussion1->id, 'parent' => 0, 'userid' => $discussion1->userid, 'created' => $post1->created, 'modified' => $post1->modified, 'mailed' => $post1->mailed, 'subject' => $post1->subject, 'message' => $post1->message, 'messageformat' => $post1->messageformat, 'messagetrust' => $post1->messagetrust, 'attachment' => $post1->attachment, 'totalscore' => $post1->totalscore, 'mailnow' => $post1->mailnow, 'userfullname' => fullname($user1), 'usermodifiedfullname' => fullname($user4), 'userpictureurl' => '', 'usermodifiedpictureurl' => '', 'numreplies' => 3, 'numunread' => 0, 'pinned' => FORUM_DISCUSSION_UNPINNED); // Call the external function passing forum id. $discussions = mod_forum_external::get_forum_discussions_paginated($forum1->id); $discussions = external_api::clean_returnvalue(mod_forum_external::get_forum_discussions_paginated_returns(), $discussions); $expectedreturn = array('discussions' => array($expecteddiscussions), 'warnings' => array()); // Wait the theme to be loaded (the external_api call does that) to generate the user profiles. $userpicture = new user_picture($user1); $userpicture->size = 1; // Size f1. $expectedreturn['discussions'][0]['userpictureurl'] = $userpicture->get_url($PAGE)->out(false); $userpicture = new user_picture($user4); $userpicture->size = 1; // Size f1. $expectedreturn['discussions'][0]['usermodifiedpictureurl'] = $userpicture->get_url($PAGE)->out(false); $this->assertEquals($expectedreturn, $discussions); // Call without required view discussion capability. $this->unassignUserCapability('mod/forum:viewdiscussion', $context->id, $newrole); try { mod_forum_external::get_forum_discussions_paginated($forum1->id); $this->fail('Exception expected due to missing capability.'); } catch (moodle_exception $e) { $this->assertEquals('noviewdiscussionspermission', $e->errorcode); } // Unenrol user from second course. $enrol->unenrol_user($instance1, $user1->id); // Call for the second course we unenrolled the user from, make sure exception thrown. try { mod_forum_external::get_forum_discussions_paginated($forum1->id); $this->fail('Exception expected due to being unenrolled from the course.'); } catch (moodle_exception $e) { $this->assertEquals('requireloginerror', $e->errorcode); } }
/** * Update or delete the user picture in the site * * @param int $draftitemid id of the user draft file to use as image * @param bool $delete if we should delete the user picture * @param int $userid id of the user, 0 for current user * @return array warnings and success status * @since Moodle 3.2 * @throws moodle_exception */ public static function update_picture($draftitemid, $delete = false, $userid = 0) { global $CFG, $USER, $PAGE; $params = self::validate_parameters(self::update_picture_parameters(), array('draftitemid' => $draftitemid, 'delete' => $delete, 'userid' => $userid)); $context = context_system::instance(); self::validate_context($context); if (!empty($CFG->disableuserimages)) { throw new moodle_exception('userimagesdisabled', 'admin'); } if (empty($params['userid']) or $params['userid'] == $USER->id) { $user = $USER; require_capability('moodle/user:editownprofile', $context); } else { $user = core_user::get_user($params['userid'], '*', MUST_EXIST); core_user::require_active_user($user); $personalcontext = context_user::instance($user->id); require_capability('moodle/user:editprofile', $personalcontext); if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins. throw new moodle_exception('useradmineditadmin'); } } // Load the appropriate auth plugin. $userauth = get_auth_plugin($user->auth); if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) { throw new moodle_exception('noprofileedit', 'auth'); } $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image'); $user->deletepicture = $params['delete']; $user->imagefile = $params['draftitemid']; $success = core_user::update_picture($user, $filemanageroptions); $result = array('success' => $success, 'warnings' => array()); if ($success) { $userpicture = new user_picture(core_user::get_user($user->id)); $userpicture->size = 1; // Size f1. $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); } return $result; }
/** * Helper function for creating a contact object. * * @param \stdClass $contact * @param string $prefix * @return \stdClass */ public static function create_contact($contact, $prefix = '') { global $PAGE; // Create the data we are going to pass to the renderable. $userfields = \user_picture::unalias($contact, array('lastaccess'), $prefix . 'id', $prefix); $data = new \stdClass(); $data->userid = $userfields->id; $data->useridfrom = null; $data->fullname = fullname($userfields); // Get the user picture data. $userpicture = new \user_picture($userfields); $userpicture->size = 1; // Size f1. $data->profileimageurl = $userpicture->get_url($PAGE)->out(false); $userpicture->size = 0; // Size f2. $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false); // Store the message if we have it. $data->ismessaging = false; $data->lastmessage = null; $data->messageid = null; if (isset($contact->smallmessage)) { $data->ismessaging = true; // Strip the HTML tags from the message for displaying in the contact area. $data->lastmessage = clean_param($contact->smallmessage, PARAM_NOTAGS); $data->useridfrom = $contact->useridfrom; if (isset($contact->messageid)) { $data->messageid = $contact->messageid; } } // Check if the user is online. $data->isonline = self::is_online($userfields->lastaccess); $data->isblocked = isset($contact->blocked) ? (bool) $contact->blocked : false; $data->isread = isset($contact->isread) ? (bool) $contact->isread : false; $data->unreadcount = isset($contact->unreadcount) ? $contact->unreadcount : null; return $data; }
/** * Internal implementation of user image rendering. * * @param user_picture $userpicture * @return string */ protected function render_user_picture(user_picture $userpicture) { global $CFG, $DB; $user = $userpicture->user; if ($userpicture->alttext) { if (!empty($user->imagealt)) { $alt = $user->imagealt; } else { $alt = get_string('pictureof', '', fullname($user)); } } else { $alt = ''; } if (empty($userpicture->size)) { $size = 35; } else if ($userpicture->size === true or $userpicture->size == 1) { $size = 100; } else { $size = $userpicture->size; } $class = $userpicture->class; if ($user->picture == 0) { $class .= ' defaultuserpic'; } $src = $userpicture->get_url($this->page, $this); $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class, 'width'=>$size, 'height'=>$size); if (!$userpicture->visibletoscreenreaders) { $attributes['role'] = 'presentation'; } // get the image html output fisrt $output = html_writer::empty_tag('img', $attributes); // then wrap it in link if needed if (!$userpicture->link) { return $output; } if (empty($userpicture->courseid)) { $courseid = $this->page->course->id; } else { $courseid = $userpicture->courseid; } if ($courseid == SITEID) { $url = new moodle_url('/user/profile.php', array('id' => $user->id)); } else { $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid)); } $attributes = array('href'=>$url); if (!$userpicture->visibletoscreenreaders) { $attributes['tabindex'] = '-1'; $attributes['aria-hidden'] = 'true'; } if ($userpicture->popup) { $id = html_writer::random_id('userpicture'); $attributes['id'] = $id; $this->add_action_handler(new popup_action('click', $url), $id); } return html_writer::tag('a', $output, $attributes); }
/** * Get the list of users in the given chat session. * * @param int $chatsid the chat session id * @return array of warnings and the user lists * @since Moodle 3.0 * @throws moodle_exception */ public static function get_chat_users($chatsid) { global $DB, $PAGE; $params = self::validate_parameters(self::get_chat_users_parameters(), array('chatsid' => $chatsid)); $warnings = array(); // Request and permission validation. if (!($chatuser = $DB->get_record('chat_users', array('sid' => $params['chatsid'])))) { throw new moodle_exception('notlogged', 'chat'); } $chat = $DB->get_record('chat', array('id' => $chatuser->chatid), '*', MUST_EXIST); list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat'); $context = context_module::instance($cm->id); self::validate_context($context); require_capability('mod/chat:chat', $context); // First, delete old users from the chats. chat_delete_old_users(); $users = chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid); $returnedusers = array(); foreach ($users as $user) { $userpicture = new user_picture($user); $userpicture->size = 1; // Size f1. $profileimageurl = $userpicture->get_url($PAGE)->out(false); $returnedusers[] = array('id' => $user->id, 'fullname' => fullname($user), 'profileimageurl' => $profileimageurl); } $result = array(); $result['users'] = $returnedusers; $result['warnings'] = $warnings; return $result; }
/** * Return user information including profile picture + basic site information * Note: * - no capability checking because we return only known information about logged user * * @param array $serviceshortnames - DEPRECATED PARAMETER - values will be ignored - * it was an original design error, we keep for backward compatibility. * @return array site info * @since Moodle 2.2 */ public static function get_site_info($serviceshortnames = array()) { global $USER, $SITE, $CFG, $DB, $PAGE; $params = self::validate_parameters(self::get_site_info_parameters(), array('serviceshortnames' => $serviceshortnames)); $context = context_user::instance($USER->id); $userpicture = new user_picture($USER); $userpicture->size = 1; // Size f1. $profileimageurl = $userpicture->get_url($PAGE); // Site information. $siteinfo = array('sitename' => $SITE->fullname, 'siteurl' => $CFG->wwwroot, 'username' => $USER->username, 'firstname' => $USER->firstname, 'lastname' => $USER->lastname, 'fullname' => fullname($USER), 'lang' => current_language(), 'userid' => $USER->id, 'userpictureurl' => $profileimageurl->out(false)); // Retrieve the service and functions from the web service linked to the token // If you call this function directly from external (not a web service call), // then it will still return site info without information about a service // Note: wsusername/wspassword ws authentication is not supported. $functions = array(); if ($CFG->enablewebservices) { // No need to check token if web service are disabled and not a ws call. $token = optional_param('wstoken', '', PARAM_ALPHANUM); if (!empty($token)) { // No need to run if not a ws call. // Retrieve service shortname. $servicesql = 'SELECT s.* FROM {external_services} s, {external_tokens} t WHERE t.externalserviceid = s.id AND token = ? AND t.userid = ? AND s.enabled = 1'; $service = $DB->get_record_sql($servicesql, array($token, $USER->id)); $siteinfo['downloadfiles'] = $service->downloadfiles; $siteinfo['uploadfiles'] = $service->uploadfiles; if (!empty($service)) { // Return the release and version number for web service users only. $siteinfo['release'] = $CFG->release; $siteinfo['version'] = $CFG->version; // Retrieve the functions. $functionssql = "SELECT f.*\n FROM {external_functions} f, {external_services_functions} sf\n WHERE f.name = sf.functionname AND sf.externalserviceid = ?"; $functions = $DB->get_records_sql($functionssql, array($service->id)); } else { throw new coding_exception('No service found in get_site_info: something is buggy, \\ it should have fail at the ws server authentication layer.'); } } } // Build up the returned values of the list of functions. $componentversions = array(); $availablefunctions = array(); foreach ($functions as $function) { $functioninfo = array(); $functioninfo['name'] = $function->name; if ($function->component == 'moodle' || $function->component == 'core') { $version = $CFG->version; // Moodle version. } else { $versionpath = core_component::get_component_directory($function->component) . '/version.php'; if (is_readable($versionpath)) { // We store the component version once retrieved (so we don't load twice the version.php). if (!isset($componentversions[$function->component])) { $plugin = new stdClass(); include $versionpath; $componentversions[$function->component] = $plugin->version; $version = $plugin->version; } else { $version = $componentversions[$function->component]; } } else { // Function component should always have a version.php, // otherwise the function should have been described with component => 'moodle'. throw new moodle_exception('missingversionfile', 'webservice', '', $function->component); } } $functioninfo['version'] = $version; $availablefunctions[] = $functioninfo; } $siteinfo['functions'] = $availablefunctions; // Mobile CSS theme and alternative login url. $siteinfo['mobilecssurl'] = $CFG->mobilecssurl; // Retrieve some advanced features. Only enable/disable ones (bool). $advancedfeatures = array("usecomments", "usetags", "enablenotes", "messaging", "enableblogs", "enablecompletion", "enablebadges"); foreach ($advancedfeatures as $feature) { if (isset($CFG->{$feature})) { $siteinfo['advancedfeatures'][] = array('name' => $feature, 'value' => (int) $CFG->{$feature}); } } // Special case mnet_dispatcher_mode. $siteinfo['advancedfeatures'][] = array('name' => 'mnet_dispatcher_mode', 'value' => $CFG->mnet_dispatcher_mode == 'strict' ? 1 : 0); // User can manage own files. $siteinfo['usercanmanageownfiles'] = has_capability('moodle/user:manageownfiles', $context); // User quota. 0 means user can ignore the quota. $siteinfo['userquota'] = 0; if (!has_capability('moodle/user:ignoreuserquota', $context)) { $siteinfo['userquota'] = $CFG->userquota; } // User max upload file size. -1 means the user can ignore the upload file size. $siteinfo['usermaxuploadfilesize'] = get_user_max_upload_file_size($context, $CFG->maxbytes); // User home page. $siteinfo['userhomepage'] = get_home_page(); return $siteinfo; }
/** Function to build the user's menu for the top navigation bar @param bool $withlinks - not sure if we want this @return string HTML fragment **/ public function user_menu($user = NULL, $withlinks = NULL) { global $USER, $CFG, $DB, $SESSION, $PAGE; // if we are during install return an empty string if (during_initial_install()) { return ''; } $course = $this->page->course; // at certain times - i.e. installation course id will be empty or null if (empty($course->id)) { return ''; } // this is the login page so return nothing $loginurl = get_login_url(); if ((string) $this->page->url === $loginurl) { return ''; } // user not logged in so return login link if (!isloggedin()) { return "<li><a href=\"{$loginurl}\">" . get_string('login') . '</a></li>'; } // begin building the user's display name $user_string = ""; // check if the user is logged in as someone else #if (session_is_loggedinas()) { # $realuser = session_get_realuser(); if (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $user_string = fullname($realuser, true) . " pretending to be "; } $user_string .= fullname($USER, true); $role_switched = false; if (is_role_switched($course->id)) { // Has switched roles $context = context_course::instance($course->id); $role_switched = true; $rolename = ''; if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) { $rolename = ': ' . role_get_name($role, $context); } $user_string .= $rolename; } $user_picture = new user_picture($USER); $userimgsrc = $user_picture->get_url($PAGE); $user_menu = array("<li class='dropdown'>"); $user_menu[] = "<a class='dropdown-toggle' data-toggle='dropdown' href='#' style='min-height: 50px'>"; $user_menu[] = "<img class='nav-avatar' src='" . $userimgsrc . "'>"; $user_menu[] = "<span class='hidden-xs'>" . $user_string . "</span>"; $user_menu[] = "</a>"; $user_menu[] = "<ul class='dropdown-menu dropdown-menu-right'>"; if ($role_switched) { $url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false))); $user_menu[] = "<li><a href='" . $url . "'>" . get_string('switchrolereturn') . "</a></li>"; } $user_menu[] = "<li><a href='" . $CFG->wwwroot . "/user/profile.php?id=" . $USER->id . "'>My Profile</a></li>"; $user_menu[] = "<li class='menu-item-resources'><a href='/'>My Modules</a></li>"; $user_menu[] = "<li id='student-email-link' style='display: none'><a href='http://studentmail.falmouth.ac.uk/'>My Email</a></li>"; $user_menu[] = "<li id='staff-email-link' style='display: none'><a href='http://mailspace.falmouth.ac.uk/'>My Email</a></li>"; $user_menu[] = "<li><a href='http://mytimetable.falmouth.ac.uk/'>My Timetable</a></li>"; $user_menu[] = "<li class='divider'></li>"; $user_menu[] = "<li><a href='" . $CFG->wwwroot . "/login/logout.php?sesskey=" . sesskey() . "'>" . get_string('logout') . '</a></li>'; $user_menu[] = "</ul></li>"; return implode("", $user_menu); }
/** * Retrieve a list of ratings for a given item (forum post etc) * * @param string $contextlevel course, module, user... * @param int $instanceid the instance if for the context element * @param string $component the name of the component * @param string $ratingarea rating area * @param int $itemid the item id * @param int $scaleid the scale id * @param string $sort sql order (firstname, rating or timemodified) * @return array Result and possible warnings * @throws moodle_exception * @since Moodle 2.9 */ public static function get_item_ratings($contextlevel, $instanceid, $component, $ratingarea, $itemid, $scaleid, $sort) { global $USER, $PAGE; $warnings = array(); $arrayparams = array('contextlevel' => $contextlevel, 'instanceid' => $instanceid, 'component' => $component, 'ratingarea' => $ratingarea, 'itemid' => $itemid, 'scaleid' => $scaleid, 'sort' => $sort); // Validate and normalize parameters. $params = self::validate_parameters(self::get_item_ratings_parameters(), $arrayparams); $context = self::get_context_from_params($params); self::validate_context($context); // Minimal capability required. $callbackparams = array('contextid' => $context->id, 'component' => $component, 'ratingarea' => $ratingarea, 'itemid' => $itemid, 'scaleid' => $scaleid); if (!has_capability('moodle/rating:view', $context) || !component_callback($component, 'rating_can_see_item_ratings', array($callbackparams), true)) { throw new moodle_exception('noviewrate', 'rating'); } list($context, $course, $cm) = get_context_info_array($context->id); // Can we see all ratings? $canviewallratings = has_capability('moodle/rating:viewall', $context); // Create the Sql sort order string. switch ($params['sort']) { case 'firstname': $sqlsort = "u.firstname ASC"; break; case 'rating': $sqlsort = "r.rating ASC"; break; default: $sqlsort = "r.timemodified ASC"; } $ratingoptions = new stdClass(); $ratingoptions->context = $context; $ratingoptions->component = $params['component']; $ratingoptions->ratingarea = $params['ratingarea']; $ratingoptions->itemid = $params['itemid']; $ratingoptions->sort = $sqlsort; $rm = new rating_manager(); $ratings = $rm->get_all_ratings_for_item($ratingoptions); $scalemenu = make_grades_menu($params['scaleid']); // If the scale was changed after ratings were submitted some ratings may have a value above the current maximum. // We can't just do count($scalemenu) - 1 as custom scales start at index 1, not 0. $maxrating = max(array_keys($scalemenu)); $results = array(); foreach ($ratings as $rating) { if ($canviewallratings || $USER->id == $rating->userid) { if ($rating->rating > $maxrating) { $rating->rating = $maxrating; } // The rating object has all the required fields for generating the picture url. $userpicture = new user_picture($rating); $userpicture->size = 1; // Size f1. $profileimageurl = $userpicture->get_url($PAGE)->out(false); $result = array(); $result['id'] = $rating->id; $result['userid'] = $rating->userid; $result['userpictureurl'] = $profileimageurl; $result['userfullname'] = fullname($rating); $result['rating'] = $scalemenu[$rating->rating]; $result['timemodified'] = $rating->timemodified; $results[] = $result; } } return array('ratings' => $results, 'warnings' => $warnings); }
/** * Update attendee. * * @throws \coding_exception */ protected function api_update_attendee() { $sessionid = $this->collaborate->sessionid; if (has_capability('mod/collaborate:moderate', $this->context)) { $role = 'moderator'; } else { if (has_capability('mod/collaborate:participate', $this->context)) { $role = 'participant'; } else { return new \moodle_url('/mod/collaborate/view.php', ['id' => $this->cm->id]); } } $attendee = new HtmlAttendee($this->user->id, $role); $attendee->setDisplayName(\core_text::substr(fullname($this->user), 0, 80)); $avatar = new \user_picture($this->user); // Note, we get the avatar url for the site instance and don't use the $PAGE object so that this function is // unit testable. $page = new \moodle_page(); $page->set_context(\context_system::instance()); $avatarurl = $avatar->get_url($page); $attendee->setAvatarUrl(new \SoapVar('<ns1:avatarUrl><![CDATA[' . $avatarurl . ']]></ns1:avatarUrl>', XSD_ANYXML)); $satts = new UpdateHtmlSessionAttendee($sessionid, $attendee); $result = $this->api->UpdateHtmlSessionAttendee($satts); if (!$result || !method_exists($result, 'getUrl')) { return false; } $url = $result->getUrl(); return $url; }
function anon_user_picture(stdClass $userin) { global $PAGE; $user = clone $userin; $user->imagealt = ''; $user->picture = ''; $userpicture = new user_picture($user); if (empty($userpicture->size)) { $size = 35; } else { if ($userpicture->size === true or $userpicture->size == 1) { $size = 100; } else { $size = $userpicture->size; } } $class = 'user_picture'; if ($user->picture == 0) { $class .= ''; } $src = $userpicture->get_url($PAGE, null); $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size); // get the image html output fisrt return html_writer::empty_tag('img', $attributes); }
public static function fetch_user_picture($user, $size = 35) { global $CFG, $PAGE; //we ignore size these days Justin 20120705 $upic = new \user_picture($user); if ($upic) { return $upic->get_url($PAGE); } else { return ""; } }
/** * Returns user's results for a specific choice * and a list of those users that did not answered yet. * * @param int $choiceid the choice instance id * @return array of responses details * @since Moodle 3.0 */ public static function get_choice_results($choiceid) { global $USER, $PAGE; $params = self::validate_parameters(self::get_choice_results_parameters(), array('choiceid' => $choiceid)); if (!($choice = choice_get_choice($params['choiceid']))) { throw new moodle_exception("invalidcoursemodule", "error"); } list($course, $cm) = get_course_and_cm_from_instance($choice, 'choice'); $context = context_module::instance($cm->id); self::validate_context($context); $groupmode = groups_get_activity_groupmode($cm); // Check if we have to include responses from inactive users. $onlyactive = $choice->includeinactive ? false : true; $users = choice_get_response_data($choice, $cm, $groupmode, $onlyactive); // Show those who haven't answered the question. if (!empty($choice->showunanswered)) { $choice->option[0] = get_string('notanswered', 'choice'); $choice->maxanswers[0] = 0; } $results = prepare_choice_show_results($choice, $course, $cm, $users); $options = array(); $fullnamecap = has_capability('moodle/site:viewfullnames', $context); foreach ($results->options as $optionid => $option) { $userresponses = array(); $numberofuser = 0; $percentageamount = 0; if (property_exists($option, 'user') and (has_capability('mod/choice:readresponses', $context) or choice_can_view_results($choice))) { $numberofuser = count($option->user); $percentageamount = (double) $numberofuser / (double) $results->numberofuser * 100.0; if ($choice->publish) { foreach ($option->user as $userresponse) { $response = array(); $response['userid'] = $userresponse->id; $response['fullname'] = fullname($userresponse, $fullnamecap); $userpicture = new user_picture($userresponse); $userpicture->size = 1; // Size f1. $response['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); // Add optional properties. foreach (array('answerid', 'timemodified') as $field) { if (property_exists($userresponse, 'answerid')) { $response[$field] = $userresponse->{$field}; } } $userresponses[] = $response; } } } $options[] = array('id' => $optionid, 'text' => external_format_string($option->text, $context->id), 'maxanswer' => $option->maxanswer, 'userresponses' => $userresponses, 'numberofuser' => $numberofuser, 'percentageamount' => $percentageamount); } $warnings = array(); return array('options' => $options, 'warnings' => $warnings); }
/** * Returns a list of forum discussions optionally sorted and paginated. * * @param int $forumid the forum instance id * @param string $sortby sort by this element (id, timemodified, timestart or timeend) * @param string $sortdirection sort direction: ASC or DESC * @param int $page page number * @param int $perpage items per page * * @return array the forum discussion details including warnings * @since Moodle 2.8 */ public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC', $page = -1, $perpage = 0) { global $CFG, $DB, $USER, $PAGE; require_once($CFG->dirroot . "/mod/forum/lib.php"); $warnings = array(); $discussions = array(); $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(), array( 'forumid' => $forumid, 'sortby' => $sortby, 'sortdirection' => $sortdirection, 'page' => $page, 'perpage' => $perpage ) ); // Compact/extract functions are not recommended. $forumid = $params['forumid']; $sortby = $params['sortby']; $sortdirection = $params['sortdirection']; $page = $params['page']; $perpage = $params['perpage']; $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend'); if (!in_array($sortby, $sortallowedvalues)) { throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' . 'allowed values are: ' . implode(',', $sortallowedvalues)); } $sortdirection = strtoupper($sortdirection); $directionallowedvalues = array('ASC', 'DESC'); if (!in_array($sortdirection, $directionallowedvalues)) { throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues)); } $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST); $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST); // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..). $modcontext = context_module::instance($cm->id); self::validate_context($modcontext); // Check they have the view forum capability. require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum'); $sort = 'd.' . $sortby . ' ' . $sortdirection; $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage); if ($alldiscussions) { $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext); // Get the unreads array, this takes a forum id and returns data for all discussions. $unreads = array(); if ($cantrack = forum_tp_can_track_forums($forum)) { if ($forumtracked = forum_tp_is_tracked($forum)) { $unreads = forum_get_discussions_unread($cm); } } // The forum function returns the replies for all the discussions in a given forum. $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage); foreach ($alldiscussions as $discussion) { // This function checks for qanda forums. // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this. $discussionrec = clone $discussion; $discussionrec->id = $discussion->discussion; if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) { $warning = array(); // Function forum_get_discussions returns forum_posts ids not forum_discussions ones. $warning['item'] = 'post'; $warning['itemid'] = $discussion->id; $warning['warningcode'] = '1'; $warning['message'] = 'You can\'t see this discussion'; $warnings[] = $warning; continue; } $discussion->numunread = 0; if ($cantrack && $forumtracked) { if (isset($unreads[$discussion->discussion])) { $discussion->numunread = (int) $unreads[$discussion->discussion]; } } $discussion->numreplies = 0; if (!empty($replies[$discussion->discussion])) { $discussion->numreplies = (int) $replies[$discussion->discussion]->replies; } $picturefields = explode(',', user_picture::fields()); // Load user objects from the results of the query. $user = new stdclass(); $user->id = $discussion->userid; $user = username_load_fields_from_object($user, $discussion, null, $picturefields); // Preserve the id, it can be modified by username_load_fields_from_object. $user->id = $discussion->userid; $discussion->userfullname = fullname($user, $canviewfullname); $userpicture = new user_picture($user); $userpicture->size = 1; // Size f1. $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false); $usermodified = new stdclass(); $usermodified->id = $discussion->usermodified; $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields); // Preserve the id (it can be overwritten due to the prefixed $picturefields). $usermodified->id = $discussion->usermodified; $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname); $userpicture = new user_picture($usermodified); $userpicture->size = 1; // Size f1. $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false); // Rewrite embedded images URLs. list($discussion->message, $discussion->messageformat) = external_format_text($discussion->message, $discussion->messageformat, $modcontext->id, 'mod_forum', 'post', $discussion->id); // List attachments. if (!empty($discussion->attachment)) { $discussion->attachments = array(); $fs = get_file_storage(); if ($files = $fs->get_area_files($modcontext->id, 'mod_forum', 'attachment', $discussion->id, "filename", false)) { foreach ($files as $file) { $filename = $file->get_filename(); $discussion->attachments[] = array( 'filename' => $filename, 'mimetype' => $file->get_mimetype(), 'fileurl' => file_encode_url($CFG->wwwroot.'/webservice/pluginfile.php', '/'.$modcontext->id.'/mod_forum/attachment/'.$discussion->id.'/'.$filename) ); } } } $discussions[] = $discussion; } } $result = array(); $result['discussions'] = $discussions; $result['warnings'] = $warnings; return $result; }
?> " data-prof="<?php echo $student->roleid == 5 ? 'b' : 'a'; ?> " data-order="<?php echo $studentNum++; ?> "> <?php $page = new moodle_page(); $page->set_url('/user/profile.php'); $page->set_context(context_system::instance()); $renderer = $page->get_renderer('core'); $up3 = new user_picture($student); $up3->size = 100; $image = $up3->get_url($page, $renderer)->out(false); ?> <img src="<?php echo $image; ?> " alt="<?php echo $student->firstname; ?> "> <span class="user-name no-text"><?php echo fullname($student); ?> </span> <span class="user-permission no-text"><?php echo $student->roleid == 5 ? get_string('student', 'superchat') : get_string('teacher', 'superchat'); ?>
/** * Get the authors of a glossary. * * @param int $id The glossary ID. * @param int $from Start returning records from here. * @param int $limit Number of records to return. * @param array $options Array of options. * @return array Containing count, authors and warnings. * @since Moodle 3.1 * @throws moodle_exception */ public static function get_authors($id, $from, $limit, $options) { global $PAGE; $params = self::validate_parameters(self::get_authors_parameters(), array('id' => $id, 'from' => $from, 'limit' => $limit, 'options' => $options)); $id = $params['id']; $from = $params['from']; $limit = $params['limit']; $options = $params['options']; $warnings = array(); // Get and validate the glossary. list($glossary, $context) = self::validate_glossary($id); // Fetching the entries. list($users, $count) = glossary_get_authors($glossary, $context, $limit, $from, $options); $canviewfullnames = has_capability('moodle/site:viewfullnames', $context); foreach ($users as $user) { $userpicture = new user_picture($user); $userpicture->size = 1; $author = new stdClass(); $author->id = $user->id; $author->fullname = fullname($user, $canviewfullnames); $author->pictureurl = $userpicture->get_url($PAGE)->out(false); $authors[] = $author; } $users->close(); return array('count' => $count, 'authors' => $authors, 'warnings' => array()); }
public function render_user_picture(user_picture $userpicture) { global $CFG, $DB; $user = $userpicture->user; if ($userpicture->alttext) { if (!empty($user->imagealt)) { $alt = $user->imagealt; } else { $alt = get_string('pictureof', '', fullname($user)); } } else { $alt = ''; } if (empty($userpicture->size)) { $size = 15; } else if ($userpicture->size === true or $userpicture->size == 1) { $size = 100; } else { $size = $userpicture->size; } $class = $userpicture->class; if ($user->picture == 0) { $class .= ' defaultuserpic'; } $src = $userpicture->get_url($this->page, $this); $attributes = array('src'=>$src, 'alt'=>$alt, 'title'=>$alt, 'class'=>$class); // get the image html output fisrt $output = html_writer::empty_tag('img', $attributes); // then wrap it in link if needed if (!$userpicture->link) { return $output; } if (empty($userpicture->courseid)) { $courseid = $this->page->course->id; } else { $courseid = $userpicture->courseid; } //if ($courseid == SITEID) { // $url = new moodle_url('local/users/profile.php', array('id' => $user->id)); //} else { $url = new moodle_url($CFG->wwwroot.'/user/view.php', array('id' => $user->id, 'course' => $courseid)); //} $attributes = array('href'=>$url); if ($userpicture->popup) { $id = html_writer::random_id('userpicture'); $attributes['id'] = $id; $this->add_action_handler(new popup_action('click', $url), $id); } return html_writer::tag('a', $output, $attributes); }
public function test_get_url() { global $DB, $CFG; $this->resetAfterTest(); // Force SVG on so that we have predictable URL's. $CFG->svgicons = true; // verify new install contains expected defaults $this->assertEquals('standard', $CFG->theme); $this->assertEquals(1, $CFG->slasharguments); $this->assertEquals(1, $CFG->themerev); $this->assertEquals(0, $CFG->themedesignermode); $this->assertEquals('http://www.example.com/moodle', $CFG->wwwroot); $this->assertEquals($CFG->wwwroot, $CFG->httpswwwroot); $this->assertEquals(0, $CFG->enablegravatar); $this->assertEquals('mm', $CFG->gravatardefaulturl); // create some users $page = new moodle_page(); $page->set_url('/user/profile.php'); $page->set_context(context_system::instance()); $renderer = $page->get_renderer('core'); $user1 = $this->getDataGenerator()->create_user(array('picture' => 11, 'email' => '*****@*****.**')); $context1 = context_user::instance($user1->id); $user2 = $this->getDataGenerator()->create_user(array('picture' => 0, 'email' => '*****@*****.**')); $context2 = context_user::instance($user2->id); $user3 = $this->getDataGenerator()->create_user(array('picture' => 1, 'deleted' => 1, 'email' => '*****@*****.**')); $context3 = context_user::instance($user3->id, IGNORE_MISSING); $this->assertEquals($user3->picture, 0); $this->assertNotEquals($user3->email, '*****@*****.**'); $this->assertFalse($context3); // try legacy picture == 1 $user1->picture = 1; $up1 = new user_picture($user1); $this->assertEquals($CFG->wwwroot . '/pluginfile.php/' . $context1->id . '/user/icon/standard/f2?rev=1', $up1->get_url($page, $renderer)->out(false)); $user1->picture = 11; // try valid user with picture when user context is not cached - 1 query expected context_helper::reset_caches(); $reads = $DB->perf_get_reads(); $up1 = new user_picture($user1); $this->assertEquals($reads, $DB->perf_get_reads()); $this->assertEquals($CFG->wwwroot . '/pluginfile.php/' . $context1->id . '/user/icon/standard/f2?rev=11', $up1->get_url($page, $renderer)->out(false)); $this->assertEquals($reads + 1, $DB->perf_get_reads()); // try valid user with contextid hint - no queries expected $user1->contextid = $context1->id; context_helper::reset_caches(); $reads = $DB->perf_get_reads(); $up1 = new user_picture($user1); $this->assertEquals($reads, $DB->perf_get_reads()); $this->assertEquals($CFG->wwwroot . '/pluginfile.php/' . $context1->id . '/user/icon/standard/f2?rev=11', $up1->get_url($page, $renderer)->out(false)); $this->assertEquals($reads, $DB->perf_get_reads()); // try valid user without image - no queries expected context_helper::reset_caches(); $reads = $DB->perf_get_reads(); $up2 = new user_picture($user2); $this->assertEquals($reads, $DB->perf_get_reads()); $this->assertEquals($CFG->wwwroot . '/theme/image.php/standard/core/1/u/f2', $up2->get_url($page, $renderer)->out(false)); $this->assertEquals($reads, $DB->perf_get_reads()); // try guessing of deleted users - no queries expected unset($user3->deleted); context_helper::reset_caches(); $reads = $DB->perf_get_reads(); $up3 = new user_picture($user3); $this->assertEquals($reads, $DB->perf_get_reads()); $this->assertEquals($CFG->wwwroot . '/theme/image.php/standard/core/1/u/f2', $up3->get_url($page, $renderer)->out(false)); $this->assertEquals($reads, $DB->perf_get_reads()); // try incorrectly deleted users (with valid email and pciture flag) - some DB reads expected $user3->email = '*****@*****.**'; $user3->picture = 1; $reads = $DB->perf_get_reads(); $up3 = new user_picture($user3); $this->assertEquals($reads, $DB->perf_get_reads()); $this->assertEquals($CFG->wwwroot . '/theme/image.php/standard/core/1/u/f2', $up3->get_url($page, $renderer)->out(false)); $this->assertTrue($reads < $DB->perf_get_reads()); // test gravatar set_config('enablegravatar', 1); // deleted user can not have gravatar $user3->email = 'deleted'; $user3->picture = 0; $up3 = new user_picture($user3); $this->assertEquals($CFG->wwwroot . '/theme/image.php/standard/core/1/u/f2', $up3->get_url($page, $renderer)->out(false)); // verify defaults to misteryman (mm) $up2 = new user_picture($user2); $this->assertEquals('http://www.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?s=35&d=mm', $up2->get_url($page, $renderer)->out(false)); // without gravatardefaulturl, verify we pick own file set_config('gravatardefaulturl', ''); $up2 = new user_picture($user2); $this->assertEquals('http://www.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?s=35&d=http%3A%2F%2Fwww.example.com%2Fmoodle%2Fpix%2Fu%2Ff2.png', $up2->get_url($page, $renderer)->out(false)); // uploaded image takes precedence before gravatar $up1 = new user_picture($user1); $this->assertEquals($CFG->wwwroot . '/pluginfile.php/' . $context1->id . '/user/icon/standard/f2?rev=11', $up1->get_url($page, $renderer)->out(false)); // https version $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); $up1 = new user_picture($user1); $this->assertEquals($CFG->httpswwwroot . '/pluginfile.php/' . $context1->id . '/user/icon/standard/f2?rev=11', $up1->get_url($page, $renderer)->out(false)); $up3 = new user_picture($user3); $this->assertEquals($CFG->httpswwwroot . '/theme/image.php/standard/core/1/u/f2', $up3->get_url($page, $renderer)->out(false)); $up2 = new user_picture($user2); $this->assertEquals('https://secure.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?s=35&d=https%3A%2F%2Fwww.example.com%2Fmoodle%2Fpix%2Fu%2Ff2.png', $up2->get_url($page, $renderer)->out(false)); // now test gravatar with one theme having own images (afterburner) $CFG->httpswwwroot = $CFG->wwwroot; $this->assertTrue(file_exists("{$CFG->dirroot}/theme/afterburner/config.php")); set_config('theme', 'afterburner'); $page = new moodle_page(); $page->set_url('/user/profile.php'); $page->set_context(context_system::instance()); $renderer = $page->get_renderer('core'); $up2 = new user_picture($user2); $this->assertEquals('http://www.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?s=35&d=http%3A%2F%2Fwww.example.com%2Fmoodle%2Ftheme%2Fafterburner%2Fpix_core%2Fu%2Ff2.png', $up2->get_url($page, $renderer)->out(false)); // https version $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); $up2 = new user_picture($user2); $this->assertEquals('https://secure.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?s=35&d=https%3A%2F%2Fwww.example.com%2Fmoodle%2Ftheme%2Fafterburner%2Fpix_core%2Fu%2Ff2.png', $up2->get_url($page, $renderer)->out(false)); // end of gravatar tests // test themed images set_config('enablegravatar', 0); $this->assertTrue(file_exists("{$CFG->dirroot}/theme/formal_white/config.php")); // use any other theme set_config('theme', 'formal_white'); $CFG->httpswwwroot = $CFG->wwwroot; $page = new moodle_page(); $page->set_url('/user/profile.php'); $page->set_context(context_system::instance()); $renderer = $page->get_renderer('core'); $up1 = new user_picture($user1); $this->assertEquals($CFG->wwwroot . '/pluginfile.php/' . $context1->id . '/user/icon/formal_white/f2?rev=11', $up1->get_url($page, $renderer)->out(false)); $up2 = new user_picture($user2); $this->assertEquals($CFG->wwwroot . '/theme/image.php/formal_white/core/1/u/f2', $up2->get_url($page, $renderer)->out(false)); // test non-slashargument images set_config('theme', 'standard'); $CFG->httpswwwroot = $CFG->wwwroot; $CFG->slasharguments = 0; $page = new moodle_page(); $page->set_url('/user/profile.php'); $page->set_context(context_system::instance()); $renderer = $page->get_renderer('core'); $up3 = new user_picture($user3); $this->assertEquals($CFG->wwwroot . '/theme/image.php?theme=standard&component=core&rev=1&image=u%2Ff2', $up3->get_url($page, $renderer)->out(false)); }
/** * * Give user record from mdl_user, build an array contains all user details. * * Warning: description file urls are 'webservice/pluginfile.php' is use. * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile * * @throws moodle_exception * @param stdClass $user user record from mdl_user * @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, $PAGE; 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 (in_array('username', $userfields)) { if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) { $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()) { // TODO: Part of MDL-50728, this conditional coding must be moved to // proper profile fields API so they are self-contained. // We only use display_data in fields that require text formatting. if ($field->datatype == 'text' or $field->datatype == 'textarea') { $fieldvalue = $formfield->display_data(); } else { // Cases: datetime, checkbox and menu. $fieldvalue = $formfield->data; } $userdetails['customfields'][] = array('name' => $formfield->field->name, 'value' => $fieldvalue, '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)) { $userpicture = new user_picture($user); $userpicture->size = 1; // Size f1. $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); } if (in_array('profileimageurlsmall', $userfields)) { if (!isset($userpicture)) { $userpicture = new user_picture($user); } $userpicture->size = 0; // Size f2. $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->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)) { $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false); if ($interests) { $userdetails['interests'] = join(', ', $interests); } } // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile. if (in_array('idnumber', $userfields) && $user->idnumber) { if (in_array('idnumber', $showuseridentityfields) or $currentuser or has_capability('moodle/user:viewalldetails', $context)) { $userdetails['idnumber'] = $user->idnumber; } } if (in_array('institution', $userfields) && $user->institution) { if (in_array('institution', $showuseridentityfields) or $currentuser or has_capability('moodle/user:viewalldetails', $context)) { $userdetails['institution'] = $user->institution; } } // Isset because it's ok to have department 0. if (in_array('department', $userfields) && isset($user->department)) { if (in_array('department', $showuseridentityfields) or $currentuser or has_capability('moodle/user:viewalldetails', $context)) { $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; }
/** * Retrieve a list of users blocked * * @param int $userid the user whose blocked users we want to retrieve * @return external_description * @since 2.9 */ public static function get_blocked_users($userid) { global $CFG, $USER, $PAGE; // Warnings array, it can be empty at the end but is mandatory. $warnings = array(); // Validate params. $params = array('userid' => $userid); $params = self::validate_parameters(self::get_blocked_users_parameters(), $params); $userid = $params['userid']; // Validate context. $context = context_system::instance(); self::validate_context($context); // Check if private messaging between users is allowed. if (empty($CFG->messaging)) { throw new moodle_exception('disabled', 'message'); } $user = core_user::get_user($userid, '*', MUST_EXIST); core_user::require_active_user($user); // Check if we have permissions for retrieve the information. if ($userid != $USER->id and !has_capability('moodle/site:readallmessages', $context)) { throw new moodle_exception('accessdenied', 'admin'); } // Now, we can get safely all the blocked users. $users = message_get_blocked_users($user); $blockedusers = array(); foreach ($users as $user) { $newuser = array('id' => $user->id, 'fullname' => fullname($user)); $userpicture = new user_picture($user); $userpicture->size = 1; // Size f1. $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); $blockedusers[] = $newuser; } $results = array('users' => $blockedusers, 'warnings' => $warnings); return $results; }
/** * Returns the profile information for a contact for a user. * * @param int $userid The user id * @param int $otheruserid The id of the user whose profile we want to view. * @return \stdClass */ public static function get_profile($userid, $otheruserid) { global $CFG, $DB, $PAGE; require_once $CFG->dirroot . '/user/lib.php'; $user = \core_user::get_user($otheruserid, '*', MUST_EXIST); // Create the data we are going to pass to the renderable. $data = new \stdClass(); $data->userid = $otheruserid; $data->fullname = fullname($user); $data->city = ''; $data->country = ''; $data->email = ''; $data->isonline = null; // Get the user picture data - messaging has always shown these to the user. $userpicture = new \user_picture($user); $userpicture->size = 1; // Size f1. $data->profileimageurl = $userpicture->get_url($PAGE)->out(false); $userpicture->size = 0; // Size f2. $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false); $userfields = user_get_user_details($user, null, array('city', 'country', 'email', 'lastaccess')); if ($userfields) { if (isset($userfields['city'])) { $data->city = $userfields['city']; } if (isset($userfields['country'])) { $data->country = $userfields['country']; } if (isset($userfields['email'])) { $data->email = $userfields['email']; } if (isset($userfields['lastaccess'])) { $data->isonline = helper::is_online($userfields['lastaccess']); } } // Check if the contact has been blocked. $contact = $DB->get_record('message_contacts', array('userid' => $userid, 'contactid' => $otheruserid)); if ($contact) { $data->isblocked = (bool) $contact->blocked; $data->iscontact = true; } else { $data->isblocked = false; $data->iscontact = false; } return $data; }