User name with a link to profile

@param stdClass $user
@param bool $profilelink show link to profile (when we are downloading never show links)
@return string
501894
protected function username($user, $profilelink = true) {
        $canviewfullnames = has_capability('moodle/site:viewfullnames', \context_system::instance()) ||
            has_capability('moodle/site:viewfullnames', \context_user::instance($user->id));
        $name = fullname($user, $canviewfullnames);
        if (!$this->is_downloading() && $profilelink) {
            $profileurl = new \moodle_url('/user/profile.php', array('id' => $user->id));
            return \html_writer::link($profileurl, $name);
        }
        return $name;
    }
18295
public function profileShow()
    {
        if (!$this->isAuthenticated()) {
            return $this->redirect('/login');
        }

        $userModel = $this->session()->get('user');
        return $this->twig()->render('User\profile.twig', array('user' => $userModel));
    }
142154
function link($target, $link)
    {
        $this->files->ensureDirExists(
            $linkPath = $this->sitesPath(), user()
        );

        $this->config->prependPath($linkPath);

        $this->files->symlinkAsUser($target, $linkPath.'/'.$link);

        return $linkPath.'/'.$link;
    }
653275
public function resolveProfilePath($path, $profile)
    {
        $path = $this->resolvePath($path);
        return preg_replace_callback('|\[\[([\w\_/]+)\]\]|', function ($matches) use ($profile) {
            $name = $matches[1];
            switch ($name) {
                case 'profile':
                    return $profile;
            }
            return '[[' . $name . ']]';
        }, $path);
    }
1029730
public function user_menu($user = null, $withlinks = null) {
        global $USER, $CFG;
        require_once($CFG->dirroot . '/user/lib.php');

        if (is_null($user)) {
            $user = $USER;
        }

        // Note: this behaviour is intended to match that of core_renderer::login_info,
        // but should not be considered to be good practice; layout options are
        // intended to be theme-specific. Please don't copy this snippet anywhere else.
        if (is_null($withlinks)) {
            $withlinks = empty($this->page->layout_options['nologinlinks']);
        }

        // Add a class for when $withlinks is false.
        $usermenuclasses = 'usermenu';
        if (!$withlinks) {
            $usermenuclasses .= ' withoutlinks';
        }

        $returnstr = "";

        // If during initial install, return the empty return string.
        if (during_initial_install()) {
            return $returnstr;
        }

        $loginpage = $this->is_login_page();
        $loginurl = get_login_url();
        // If not logged in, show the typical not-logged-in string.
        if (!isloggedin()) {
            $returnstr = get_string('loggedinnot', 'moodle');
            if (!$loginpage) {
                $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
            }
            return html_writer::div(
                html_writer::span(
                    $returnstr,
                    'login'
                ),
                $usermenuclasses
            );

        }

        // If logged in as a guest user, show a string to that effect.
        if (isguestuser()) {
            $returnstr = get_string('loggedinasguest');
            if (!$loginpage && $withlinks) {
                $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
            }

            return html_writer::div(
                html_writer::span(
                    $returnstr,
                    'login'
                ),
                $usermenuclasses
            );
        }

        // Get some navigation opts.
        $opts = user_get_user_navigation_info($user, $this->page);

        $avatarclasses = "avatars";
        $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
        $usertextcontents = $opts->metadata['userfullname'];

        // Other user.
        if (!empty($opts->metadata['asotheruser'])) {
            $avatarcontents .= html_writer::span(
                $opts->metadata['realuseravatar'],
                'avatar realuser'
            );
            $usertextcontents = $opts->metadata['realuserfullname'];
            $usertextcontents .= html_writer::tag(
                'span',
                get_string(
                    'loggedinas',
                    'moodle',
                    html_writer::span(
                        $opts->metadata['userfullname'],
                        'value'
                    )
                ),
                array('class' => 'meta viewingas')
            );
        }

        // Role.
        if (!empty($opts->metadata['asotherrole'])) {
            $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
            $usertextcontents .= html_writer::span(
                $opts->metadata['rolename'],
                'meta role role-' . $role
            );
        }

        // User login failures.
        if (!empty($opts->metadata['userloginfail'])) {
            $usertextcontents .= html_writer::span(
                $opts->metadata['userloginfail'],
                'meta loginfailures'
            );
        }

        // MNet.
        if (!empty($opts->metadata['asmnetuser'])) {
            $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
            $usertextcontents .= html_writer::span(
                $opts->metadata['mnetidprovidername'],
                'meta mnet mnet-' . $mnet
            );
        }

        $returnstr .= html_writer::span(
            html_writer::span($usertextcontents, 'usertext mr-1') .
            html_writer::span($avatarcontents, $avatarclasses),
            'userbutton'
        );

        // Create a divider (well, a filler).
        $divider = new action_menu_filler();
        $divider->primary = false;

        $am = new action_menu();
        $am->set_menu_trigger(
            $returnstr
        );
        $am->set_action_label(get_string('usermenu'));
        $am->set_alignment(action_menu::TR, action_menu::BR);
        $am->set_nowrap_on_items();
        if ($withlinks) {
            $navitemcount = count($opts->navitems);
            $idx = 0;
            foreach ($opts->navitems as $key => $value) {

                switch ($value->itemtype) {
                    case 'divider':
                        // If the nav item is a divider, add one and skip link processing.
                        $am->add($divider);
                        break;

                    case 'invalid':
                        // Silently skip invalid entries (should we post a notification?).
                        break;

                    case 'link':
                        // Process this as a link item.
                        $pix = null;
                        if (isset($value->pix) && !empty($value->pix)) {
                            $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
                        } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
                            $value->title = html_writer::img(
                                $value->imgsrc,
                                $value->title,
                                array('class' => 'iconsmall')
                            ) . $value->title;
                        }

                        $al = new action_menu_link_secondary(
                            $value->url,
                            $pix,
                            $value->title,
                            array('class' => 'icon')
                        );
                        if (!empty($value->titleidentifier)) {
                            $al->attributes['data-title'] = $value->titleidentifier;
                        }
                        $am->add($al);
                        break;
                }

                $idx++;

                // Add dividers after the first item and before the last item.
                if ($idx == 1 || $idx == $navitemcount - 1) {
                    $am->add($divider);
                }
            }
        }

        return html_writer::div(
            $this->render($am),
            $usermenuclasses
        );
    }
956826
private function getUsernameForGitHubMatching(User $user)
    {
        $identity = $user->identities()->first();

        if ($identity->provider()->type() === IdentityProviderEnum::TYPE_INTERNAL) {
            return $user->name();
        } elseif ($identity->provider()->type() === IdentityProviderEnum::TYPE_LDAP) {
            return $identity->providerUniqueID();
        }

        return $user->name();
    }
100646
protected function _getUser($profile)
    {
        $user = null;

        if ($profile->get('user_id')) {
            $userPkField = $this->_userModel->aliasField((string)$this->_userModel->getPrimaryKey());

            $user = $this->_userModel->find()
                ->where([
                    $userPkField => $profile->get('user_id'),
                ])
                ->find($this->getConfig('finder'))
                ->first();
        }

        if (!$user) {
            if ($profile->get('user_id')) {
                $this->_error = 'finder_failure';

                return null;
            }

            $user = $this->_getUserEntity($profile);
            $profile->set('user_id', $user->id);
        }

        if ($profile->isDirty()) {
            $this->_saveProfile($profile);
        }

        $user->set('social_profile', $profile);
        $user->unsetProperty($this->getConfig('fields.password'));

        return $user;
    }
876636
public function Link($action = null)
    {
        if (!$action
            && Member::currentUserID()
            && !$this->AllowProfileEditing
            && $this->CanAddMembers()
        ) {
            $action = 'add';
        }

        return parent::Link($action);
    }
126257
public function get_userinfo() {
        $url = $this->get_issuer()->get_endpoint_url('userinfo');
        $response = $this->get($url);
        if (!$response) {
            return false;
        }
        $userinfo = new stdClass();
        try {
            $userinfo = json_decode($response);
        } catch (\Exception $e) {
            return false;
        }

        $map = $this->get_userinfo_mapping();

        $user = new stdClass();
        foreach ($map as $openidproperty => $moodleproperty) {
            // We support nested objects via a-b-c syntax.
            $getfunc = function($obj, $prop) use (&$getfunc) {
                $proplist = explode('-', $prop, 2);
                if (empty($proplist[0]) || empty($obj->{$proplist[0]})) {
                    return false;
                }
                $obj = $obj->{$proplist[0]};

                if (count($proplist) > 1) {
                    return $getfunc($obj, $proplist[1]);
                }
                return $obj;
            };

            $resolved = $getfunc($userinfo, $openidproperty);
            if (!empty($resolved)) {
                $user->$moodleproperty = $resolved;
            }
        }

        if (empty($user->username) && !empty($user->email)) {
            $user->username = $user->email;
        }

        if (!empty($user->picture)) {
            $user->picture = download_file_content($user->picture, null, null, false, 10, 10, true, null, false);
        } else {
            $pictureurl = $this->issuer->get_endpoint_url('userpicture');
            if (!empty($pictureurl)) {
                $user->picture = $this->get($pictureurl);
            }
        }

        if (!empty($user->picture)) {
            // If it doesn't look like a picture lets unset it.
            if (function_exists('imagecreatefromstring')) {
                $img = @imagecreatefromstring($user->picture);
                if (empty($img)) {
                    unset($user->picture);
                } else {
                    imagedestroy($img);
                }
            }
        }

        return (array)$user;
    }
1080470
private function getCustomerData(UserProfile $profile)
    {
        $customerData = [];
        foreach (['firstName', 'lastName', 'email'] as $field) {
            $data = $profile->{$field};
            $customerData[strtolower($field)] = $data !== null ? $data : '-';
        }
        return $customerData;
    }
337207
public function oAuthLink()
    {
        $providerName = $_REQUEST["provider"];
        $userProfile = $this->getAuthProvider()->authenticate($providerName);

        $this->_getUser()->first_name = $userProfile->firstName;
        $this->_getUser()->last_name = $userProfile->lastName;
        $this->_getUser()->email = $userProfile->email;

        foreach (['login', 'register'] as $_action) {
            $form = $this->_getUser()->getForm($_action);

            if ($form->execute()) {
                $userLogin = User_Logins::instance()->getNew();
                $userLogin->id_user = $this->_getUser()->id;
                $userLogin->provider_name = $providerName;
                $userLogin->provider_uid = $userProfile->identifier;
                $userLogin->insert();


                $this->{'after' . ucfirst($_action) . 'Redirect'}();
            }
            $this->forms[$_action] = $form;
        }

        $this->setLoginMeta('login');
    }
1028538
public function getProfileAlias()
    {
        $link = $this->getProfile();
        if ($link && $link->href) {
            $guidOrAlias = explode('/', $link->href);
            $guidOrAlias = end($guidOrAlias);
            return isset(self::$_profileAliases[$guidOrAlias]) ? self::$_profileAliases[$guidOrAlias] : $guidOrAlias;
        } else {
            return null;
        }
    }
1130734
public function setPublicProfileUrl($url)
    {
        // Avoids errors like: "[invalid.param.url]. Public profile URL is not correct, {url=xyz should be
        // {https://www.linkedin.com/pub/[member-name/]x/y/z}.  LinkedIn won't validate it's own public urls that
        // have a language / country code appended
        $matches = array();
        preg_match('"^https?://((www|\w\w)\.)?linkedin.com/((in/[^/]+/?)|(pub/[^/]+/((\w|\d)+/?){3}))"', $url, $matches);
        if (count($matches)) {
            $url = current($matches);
        }
        $url = rtrim($url, '/');
        
        //according to their manual and forums, all linkedin public urls should begin with 'https://www.linkedin.com'
        //(they said they'd always support it even if it did ever change, which is highly unlikely)
        //so just chop it off and force it to be that
        $url = preg_replace('/^(.*)linkedin.com\//i', 'https://www.linkedin.com/', $url);

        $this->_public_profile_url = $url;

        return $this;
    }
758884
public function isProfileAssignedToAnotherUser($curentUserId, $identifier, $provider)
    {
        $qb = $this->createQueryBuilder(null);
        $qb->field('_id')->notEqual($curentUserId)
            ->addAnd(
                $qb->expr()
                    ->addOr($qb->expr()->field('profiles.' . $provider . '.auth.identifier' )->equals($identifier))
                    ->addOr($qb->expr()->field('profile.identifier')->equals($identifier))
            );
        
        return $qb->count()
            ->getQuery()
            ->execute() > 0;
    }
1050161
public function getProfile($name){
        if(isset($this->profiles[$name])){
            return $this->profiles[$name];
        }
        return NULL;
    }
63717
public function loadUser($user)
    {

        $ok = false;
        if (!empty($user->getRecordId())) {
            $sql = sprintf('SELECT user_pk, resource_link_pk, lti_user_id, lti_result_sourcedid, created, updated ' .
                           "FROM {$this->dbTableNamePrefix}" . DataConnector::USER_RESULT_TABLE_NAME . ' ' .
                           'WHERE (user_pk = %d)',
            $user->getRecordId());
        } else {
            $sql = sprintf('SELECT user_pk, resource_link_pk, lti_user_id, lti_result_sourcedid, created, updated ' .
                           "FROM {$this->dbTableNamePrefix}" . DataConnector::USER_RESULT_TABLE_NAME . ' ' .
                           'WHERE (resource_link_pk = %d) AND (lti_user_id = %s)',
                           $user->getResourceLink()->getRecordId(),
                           DataConnector::quoted($user->getId(ToolProvider\ToolProvider::ID_SCOPE_ID_ONLY)));
        }
        $rsUser = mysql_query($sql);
        if ($rsUser) {
            $row = mysql_fetch_object($rsUser);
            if ($row) {
                $user->setRecordId(intval($row->user_pk));
                $user->setResourceLinkId(intval($row->resource_link_pk));
                $user->ltiUserId = $row->lti_user_id;
                $user->ltiResultSourcedId = $row->lti_result_sourcedid;
                $user->created = strtotime($row->created);
                $user->updated = strtotime($row->updated);
                $ok = true;
            }
        }

        return $ok;

    }
675648
public function format($user)
    {
        $id = null;
        $name = '';
        $userInfo = null;
        if (isset($user) && $user) {
            if (is_int($user) || (is_string($user) && is_numeric($user))) {
                $user = \User::getByUserID($user);
            }
            try {
                if ($user instanceof ConcreteUser && $user->getUserID() && $user->isRegistered()) {
                    $id = (int) $user->getUserID();
                    $name = $user->getUserName();
                } elseif ($user instanceof UserInfo && $user->getUserID()) {
                    $id = (int) $user->getUserID();
                    $name = $user->getUserName();
                    $userInfo = $user;
                } elseif ($user instanceof ConcreteUserEntity && $user->getUserID()) {
                    $id = (int) $user->getUserID();
                    $name = $user->getUserName();
                }
            } catch (EntityNotFoundException $x) {
                $id = null;
            }
        }
        if ($id === null) {
            $result = '<i class="comtra-user comtra-user-removed">' . t('removed user') . '</i>';
        } elseif ($id == USER_SUPER_ID) {
            $result = '<i class="comtra-user comtra-user-system">' . t('system') . '</i>';
        } else {
            $profileURL = null;
            if ($userInfo === null) {
                $userInfo = $this->app->make(UserInfoRepository::class)->getByID($id);
            }
            if ($userInfo !== null) {
                $profileURL = $userInfo->getUserPublicProfileUrl();
            }
            if ($profileURL === null) {
                $result = '<span';
            } else {
                $result = '<a href="' . h((string) $profileURL) . '"';
            }
            $result .= ' class="comtra-user comtra-user-found">' . h($name);
            if ($profileURL === null) {
                $result .= '</span>';
            } else {
                $result .= '</a>';
            }
        }

        return $result;
    }