Show user avatar next to its name, in all possible locations

This commit is contained in:
Jan Böhmer 2023-01-23 23:01:57 +01:00
parent 29bce6f19f
commit 97b87dee5f
9 changed files with 143 additions and 47 deletions

View file

@ -11,9 +11,17 @@ liip_imagine:
size: [150, 150]
mode: inset
thumbnail_md:
quality: 75
filters:
thumbnail:
size: [250, 250]
mode: inset
thumbnail_xs:
quality: 70
filters:
thumbnail:
size: [50, 50]
mode: inset

View file

@ -17,6 +17,7 @@ twig:
error_page_show_help: '%partdb.error_pages.show_help%'
sidebar_items: '%partdb.sidebar.items%'
sidebar_tree_updater: '@App\Services\Trees\SidebarTreeUpdater'
avatar_helper: '@App\Services\UserSystem\UserAvatarHelper'
when@test:
twig:

View file

@ -182,6 +182,10 @@ services:
tags:
- { name: 'translation.extractor', alias: 'permissionExtractor'}
App\Services\UserSystem\UserAvatarHelper:
arguments:
$use_gravatar: '%partdb.users.use_gravatar%'
####################################################################################################################
# Label system

View file

@ -220,13 +220,6 @@ class UserController extends AdminPages\BaseAdminController
return $table->getResponse();
}
if ($this->getParameter('partdb.users.use_gravatar')) {
//If no email is existing just set some string to show a gravatar
$avatar = $this->getGravatar($user->getEmail() ?? 'partdb', 200, 'identicon');
} else {
$avatar = $packages->getUrl('/img/default_avatar.png');
}
//Show permissions to user
$builder = $this->createFormBuilder()->add('permissions', PermissionsType::class, [
'mapped' => false,
@ -237,42 +230,8 @@ class UserController extends AdminPages\BaseAdminController
return $this->renderForm('Users/user_info.html.twig', [
'user' => $user,
'avatar' => $avatar,
'form' => $builder->getForm(),
'datatable' => $table,
]);
}
/**
* Get either a Gravatar URL or complete image tag for a specified email address.
*
* @param string|null $email The email address
* @param int $s Size in pixels, defaults to 80px [ 1 - 2048 ]
* @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
* @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
* @param bool $img True to return a complete IMG tag False for just the URL
* @param array $atts Optional, additional key/value attributes to include in the IMG tag
*
* @return string containing either just a URL or a complete image tag
* @source https://gravatar.com/site/implement/images/php/
*/
public function getGravatar(?string $email, int $s = 80, string $d = 'mm', string $r = 'g', bool $img = false, array $atts = []): string
{
if (null === $email) {
return '';
}
$url = 'https://www.gravatar.com/avatar/';
$url .= md5(strtolower(trim($email)));
$url .= "?s=${s}&d=${d}&r=${r}";
if ($img) {
$url = '<img src="'.$url.'"';
foreach ($atts as $key => $val) {
$url .= ' '.$key.'="'.$val.'"';
}
$url .= ' />';
}
return $url;
}
}

View file

@ -44,6 +44,7 @@ use App\Exceptions\EntityNotSupportedException;
use App\Repository\LogEntryRepository;
use App\Services\ElementTypeNameGenerator;
use App\Services\EntityURLGenerator;
use App\Services\UserSystem\UserAvatarHelper;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Omines\DataTablesBundle\Adapter\Doctrine\ORM\SearchCriteriaProvider;
@ -66,9 +67,11 @@ class LogDataTable implements DataTableTypeInterface
protected EntityURLGenerator $entityURLGenerator;
protected LogEntryRepository $logRepo;
protected Security $security;
protected UserAvatarHelper $userAvatarHelper;
public function __construct(ElementTypeNameGenerator $elementTypeNameGenerator, TranslatorInterface $translator,
UrlGeneratorInterface $urlGenerator, EntityURLGenerator $entityURLGenerator, EntityManagerInterface $entityManager, Security $security)
UrlGeneratorInterface $urlGenerator, EntityURLGenerator $entityURLGenerator, EntityManagerInterface $entityManager,
Security $security, UserAvatarHelper $userAvatarHelper)
{
$this->elementTypeNameGenerator = $elementTypeNameGenerator;
$this->translator = $translator;
@ -76,6 +79,7 @@ class LogDataTable implements DataTableTypeInterface
$this->entityURLGenerator = $entityURLGenerator;
$this->logRepo = $entityManager->getRepository(AbstractLogEntry::class);
$this->security = $security;
$this->userAvatarHelper = $userAvatarHelper;
}
public function configureOptions(OptionsResolver $optionsResolver): void
@ -227,8 +231,11 @@ class LogDataTable implements DataTableTypeInterface
);
}
$img_url = $this->userAvatarHelper->getAvatarSmURL($user);
return sprintf(
'<a href="%s">%s</a>',
'<img src="%s" class="rounded" style="height: 1.2rem;"> <a href="%s">%s</a>',
$img_url,
$this->urlGenerator->generate('user_info', ['id' => $user->getID()]),
htmlentities($user->getFullName(true))
);

View file

@ -0,0 +1,111 @@
<?php
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2023 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Services\UserSystem;
use App\Entity\UserSystem\User;
use App\Services\Attachments\AttachmentURLGenerator;
use Liip\ImagineBundle\Service\FilterService;
use Symfony\Component\Asset\Packages;
class UserAvatarHelper
{
private bool $use_gravatar;
private Packages $packages;
private AttachmentURLGenerator $attachmentURLGenerator;
private FilterService $filterService;
public function __construct(bool $use_gravatar, Packages $packages, AttachmentURLGenerator $attachmentURLGenerator, FilterService $filterService)
{
$this->use_gravatar = $use_gravatar;
$this->packages = $packages;
$this->attachmentURLGenerator = $attachmentURLGenerator;
$this->filterService = $filterService;
}
/**
* Returns the URL to the profile picture of the given user (in big size)
* @param User $user
* @return string
*/
public function getAvatarURL(User $user): string
{
//Check if the user has a master attachment defined (meaning he has explicitly defined a profile picture)
if ($user->getMasterPictureAttachment() !== null) {
return $this->attachmentURLGenerator->getThumbnailURL($user->getMasterPictureAttachment());
}
//If not check if gravatar is enabled (then use gravatar URL)
if ($this->use_gravatar) {
return $this->getGravatar($user, 200); //200px wide picture
}
//Fallback to the default avatar picture
return $this->packages->getUrl('/img/default_avatar.png');
}
public function getAvatarSmURL(User $user): string
{
//Check if the user has a master attachment defined (meaning he has explicitly defined a profile picture)
if ($user->getMasterPictureAttachment() !== null) {
return $this->attachmentURLGenerator->getThumbnailURL($user->getMasterPictureAttachment(), 'thumbnail_xs');
}
//If not check if gravatar is enabled (then use gravatar URL)
if ($this->use_gravatar) {
return $this->getGravatar($user, 50); //50px wide picture
}
try {
//Otherwise we can serve the relative path via Asset component
return $this->filterService->getUrlOfFilteredImage('/img/default_avatar.png', 'thumbnail_xs');
} catch (\Imagine\Exception\RuntimeException $e) {
//If the filter fails, we can not serve the thumbnail and fall back to the original image and log an warning
return $this->packages->getUrl('/img/default_avatar.png');
}
}
/**
* Get either a Gravatar URL or complete image tag for a specified email address.
*
* @param User $user The user for which the gravator should be generated
* @param int $s Size in pixels, defaults to 80px [ 1 - 2048 ]
* @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
* @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
*
* @return string containing either just a URL or a complete image tag
* @source https://gravatar.com/site/implement/images/php/
*/
private function getGravatar(User $user, int $s = 80, string $d = 'identicon', string $r = 'g'): string
{
$email = $user->getEmail();
if (empty($email)) {
$email = 'Part-DB';
}
$url = 'https://www.gravatar.com/avatar/';
$url .= md5(strtolower(trim($email)));
$url .= "?s=${s}&d=${d}&r=${r}";
return $url;
}
}

View file

@ -9,7 +9,7 @@
<div class="card-body row">
<div class="col-md-2">
<div class="mx-auto">
<img class="img-fluid img-thumbnail img-rounded " alt="User avatar" src="{{ avatar }}">
<img class="img-fluid img-thumbnail rounded" alt="User avatar" src="{{ avatar_helper.avatarURL(user) }}">
</div>
</div>
<div class="col-md-5">

View file

@ -1,3 +1,5 @@
{% import "helper.twig" as helper %}
<nav class="navbar navbar-expand-md navbar-light bg-light border-bottom shadow-sm fixed-top py-0" id="navbar">
<div class="container-fluid">
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#sidebar-container">
@ -41,7 +43,7 @@
<ul class="dropdown-menu dropdown-menu-end" id="login-menu" aria-labelledby="navbar-user-dropdown-btn">
{% if app.user %}
<a class="dropdown-item disabled" href="#">{% trans %}user.loggedin.label{% endtrans %}
<b>{{ app.user.firstName }} {{ app.user.lastName }}</b> (@{{ app.user.name }})</a>
{{ helper.user_icon(app.user) }} <b>{{ app.user.firstName }} {{ app.user.lastName }}</b> (@{{ app.user.name }})</a>
<a class="dropdown-item" href="{{ path("user_settings") }}"><i class="fa fa-cogs fa-fw"
aria-hidden="true"></i> {% trans %}user.settings.label{% endtrans %}
</a>

View file

@ -160,14 +160,18 @@
{% if user is not null %}
{% if user.fullName is not empty %}
(<a href="{{ path('user_info', {"id": user.id}) }}" title="@{{ user.name }}">{{ user.fullName }}</a>)
({{ _self.user_icon(user) }} <a href="{{ path('user_info', {"id": user.id}) }}" title="@{{ user.name }}">{{ user.fullName }}</a>)
{% else %}
(<a href="{{ path('user_info', {"id": user.id}) }}" title="@{{ user.name }}">@{{ user.name }}</a>)
({{ _self.user_icon(user) }} <a href="{{ path('user_info', {"id": user.id}) }}" title="@{{ user.name }}">@{{ user.name }}</a>)
{% endif %}
{% endif %}
{% endif %}
{% endmacro %}
{% macro user_icon(user) %}
<img src="{{ avatar_helper.avatarSmURL(user) }}" class="rounded" style="height: 1.2rem;" alt="User avatar">
{% endmacro %}
{% macro parameters_table(parameters) %}
<table class="table table-hover table-striped table-sm">
<thead>