mirror of
https://gitlab.unicamp.br/infimecc_drupal11_modules/site_users.git
synced 2026-05-05 17:55:29 -03:00
Compare commits
9 Commits
0ce327026d
...
39de6a7493
| Author | SHA1 | Date | |
|---|---|---|---|
| 39de6a7493 | |||
| aa24bf79f8 | |||
| ca9b8e8d53 | |||
| 7b747e4eb2 | |||
| a500d9ec09 | |||
| 18a7aa81cb | |||
| 85bc63b250 | |||
| f4d6c49312 | |||
| c96268e09d |
@@ -2,6 +2,7 @@ photos:
|
||||
max_count: 5
|
||||
ldap_attribute: 'jpegPhoto'
|
||||
ldap_sync_enabled: false
|
||||
ldap_min_photo_size: 10240
|
||||
user_editable_fields:
|
||||
field_user_name: true
|
||||
field_user_phone: true
|
||||
@@ -9,3 +10,4 @@ user_editable_fields:
|
||||
field_user_social_links: true
|
||||
field_user_photos: true
|
||||
role_view_modes: { }
|
||||
add_content_links: [ ]
|
||||
|
||||
14
config/optional/pathauto.pattern.user_site_mapping.yml
Normal file
14
config/optional/pathauto.pattern.user_site_mapping.yml
Normal file
@@ -0,0 +1,14 @@
|
||||
langcode: pt-br
|
||||
status: true
|
||||
dependencies:
|
||||
module:
|
||||
- pathauto
|
||||
- user
|
||||
id: user_site_mapping
|
||||
label: 'User site mapping'
|
||||
type: 'canonical_entities:user'
|
||||
pattern: 'user/[user:name]'
|
||||
selection_criteria: { }
|
||||
selection_logic: and
|
||||
weight: 0
|
||||
relationships: { }
|
||||
@@ -15,6 +15,9 @@ site_users.settings:
|
||||
ldap_sync_enabled:
|
||||
type: boolean
|
||||
label: 'Enable LDAP photo synchronization'
|
||||
ldap_min_photo_size:
|
||||
type: integer
|
||||
label: 'Minimum LDAP photo size in bytes'
|
||||
user_editable_fields:
|
||||
type: sequence
|
||||
label: 'User-editable profile fields'
|
||||
@@ -30,3 +33,25 @@ site_users.settings:
|
||||
sequence:
|
||||
type: string
|
||||
label: 'View mode machine name'
|
||||
add_content_links:
|
||||
type: sequence
|
||||
label: 'Add content menu items'
|
||||
sequence:
|
||||
type: mapping
|
||||
label: 'Add content menu item'
|
||||
mapping:
|
||||
label:
|
||||
type: label
|
||||
label: 'Menu item label'
|
||||
route_name:
|
||||
type: string
|
||||
label: 'Route name'
|
||||
route_parameters:
|
||||
type: sequence
|
||||
label: 'Route parameters'
|
||||
sequence:
|
||||
type: string
|
||||
label: 'Parameter value'
|
||||
weight:
|
||||
type: integer
|
||||
label: 'Weight'
|
||||
|
||||
@@ -4,3 +4,9 @@ site_users_microsite.settings:
|
||||
route_name: site_users_microsite.settings
|
||||
parent: site_users.settings
|
||||
weight: 10
|
||||
|
||||
site_users_microsite.my_config:
|
||||
title: 'Configuração'
|
||||
route_name: site_users_microsite.my_config
|
||||
menu_name: account
|
||||
weight: 5
|
||||
|
||||
@@ -18,17 +18,106 @@ function site_users_microsite_theme(): array {
|
||||
'photo_alt' => '',
|
||||
'name' => NULL,
|
||||
'bio' => NULL,
|
||||
'phone' => NULL,
|
||||
'email' => NULL,
|
||||
'homepage' => NULL,
|
||||
'lattes_id' => NULL,
|
||||
'orcid_id' => NULL,
|
||||
'mathscinet_id' => NULL,
|
||||
'department' => NULL,
|
||||
'department_url' => NULL,
|
||||
'work_phone' => NULL,
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_preprocess_structural_pages_menu().
|
||||
*
|
||||
* Remove da árvore de navegação o nó configurado como homepage do microsite,
|
||||
* já que esse conteúdo é exibido diretamente em /user/{id}.
|
||||
*/
|
||||
function site_users_microsite_preprocess_structural_pages_menu(array &$variables): void {
|
||||
$user = site_users_get_microsite_user();
|
||||
if ($user === NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
$homepage_nid = \Drupal::service('user.data')
|
||||
->get('site_users_microsite', $user->id(), 'homepage_nid');
|
||||
if (!$homepage_nid) {
|
||||
return;
|
||||
}
|
||||
|
||||
_site_users_microsite_remove_homepage_from_tree($variables['tree'], (int) $homepage_nid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove recursivamente o nó homepage da árvore do structural_pages_menu.
|
||||
*/
|
||||
function _site_users_microsite_remove_homepage_from_tree(array &$items, int $homepage_nid): void {
|
||||
foreach ($items as $key => $item) {
|
||||
if ((int) ($item['id'] ?? 0) === $homepage_nid) {
|
||||
unset($items[$key]);
|
||||
continue;
|
||||
}
|
||||
if (!empty($item['children'])) {
|
||||
_site_users_microsite_remove_homepage_from_tree($items[$key]['children'], $homepage_nid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_preprocess_block().
|
||||
*
|
||||
* Substitui o título do bloco "Título da Página" pelo título do nó homepage
|
||||
* quando o usuário tiver ativado essa opção nas configurações do microsite.
|
||||
* Sem nó homepage configurado (ou no fallback), mantém o comportamento padrão.
|
||||
*/
|
||||
function site_users_microsite_preprocess_block(&$variables): void {
|
||||
if ($variables['plugin_id'] !== 'page_title_block') {
|
||||
return;
|
||||
}
|
||||
|
||||
$route_match = \Drupal::routeMatch();
|
||||
$route_name = $route_match->getRouteName() ?? '';
|
||||
|
||||
// Rotas com título próprio não devem ser sobrescritas.
|
||||
$excluded = [
|
||||
'site_users_microsite.profile',
|
||||
'site_users_microsite.settings',
|
||||
'site_users_microsite.user_config',
|
||||
];
|
||||
|
||||
$is_microsite = $route_name === 'entity.user.canonical'
|
||||
|| str_starts_with($route_name, 'site_users_microsite.');
|
||||
|
||||
if (!$is_microsite || in_array($route_name, $excluded)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user = $route_match->getParameter('user');
|
||||
if (!($user instanceof UserInterface)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$userData = \Drupal::service('user.data');
|
||||
|
||||
if (!$userData->get('site_users_microsite', $user->id(), 'use_homepage_title')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$homepage_nid = $userData->get('site_users_microsite', $user->id(), 'homepage_nid');
|
||||
if (!$homepage_nid) {
|
||||
return;
|
||||
}
|
||||
|
||||
$node = \Drupal::entityTypeManager()->getStorage('node')->load($homepage_nid);
|
||||
if ($node && $node->isPublished() && $node->access('view')) {
|
||||
$variables['content']['#title'] = $node->label();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_preprocess_page().
|
||||
*
|
||||
|
||||
@@ -2,7 +2,7 @@ site_users_microsite.profile:
|
||||
path: '/user/{user}/profile'
|
||||
defaults:
|
||||
_controller: '\Drupal\site_users_microsite\Controller\MicrositeHomeController::profile'
|
||||
_title_callback: '\Drupal\site_users_microsite\Controller\MicrositeHomeController::title'
|
||||
_title_callback: '\Drupal\site_users_microsite\Controller\MicrositeHomeController::profileTitle'
|
||||
requirements:
|
||||
_entity_access: 'user.view'
|
||||
user: \d+
|
||||
@@ -24,6 +24,27 @@ site_users_microsite.content:
|
||||
user:
|
||||
type: entity:user
|
||||
|
||||
site_users_microsite.user_config:
|
||||
path: '/user/{user}/config'
|
||||
defaults:
|
||||
_form: '\Drupal\site_users_microsite\Form\MicrositeUserConfigForm'
|
||||
_title: 'Microsite settings'
|
||||
requirements:
|
||||
_entity_access: 'user.update'
|
||||
user: \d+
|
||||
options:
|
||||
parameters:
|
||||
user:
|
||||
type: entity:user
|
||||
|
||||
site_users_microsite.my_config:
|
||||
path: '/user/microsite/config'
|
||||
defaults:
|
||||
_controller: '\Drupal\site_users_microsite\Controller\MicrositeHomeController::redirectToMyConfig'
|
||||
_title: 'Microsite settings'
|
||||
requirements:
|
||||
_user_is_logged_in: 'TRUE'
|
||||
|
||||
site_users_microsite.settings:
|
||||
path: '/admin/config/local-modules/site-users/microsite'
|
||||
defaults:
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
services:
|
||||
site_users_microsite.path_processor:
|
||||
class: Drupal\site_users_microsite\PathProcessor\MicrositeSubpagePathProcessor
|
||||
arguments: ['@path_alias.manager', '@language_manager']
|
||||
tags:
|
||||
- { name: path_processor_inbound, priority: 200 }
|
||||
- { name: path_processor_outbound, priority: 200 }
|
||||
|
||||
site_users_microsite.theme_negotiator:
|
||||
class: Drupal\site_users_microsite\Theme\MicrositeThemeNegotiator
|
||||
arguments: ['@path_alias.manager']
|
||||
tags:
|
||||
- { name: theme_negotiator, priority: 100 }
|
||||
|
||||
|
||||
@@ -4,25 +4,53 @@ namespace Drupal\site_users_microsite\Controller;
|
||||
|
||||
use Drupal\Core\Controller\ControllerBase;
|
||||
use Drupal\Core\StringTranslation\TranslatableMarkup;
|
||||
use Drupal\user\UserDataInterface;
|
||||
use Drupal\user\UserInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
|
||||
/**
|
||||
* Controller para a página inicial do micro-site do usuário.
|
||||
*
|
||||
* Carrega e exibe o nó do tipo content_page cujo autor é o usuário
|
||||
* da rota /user/{user}/home.
|
||||
*/
|
||||
class MicrositeHomeController extends ControllerBase {
|
||||
|
||||
public function __construct(
|
||||
protected UserDataInterface $userData,
|
||||
) {}
|
||||
|
||||
public static function create(ContainerInterface $container): static {
|
||||
return new static(
|
||||
$container->get('user.data'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Página inicial do micro-site.
|
||||
*
|
||||
* Exibe o nó configurado pelo usuário ou, como fallback, o primeiro nó
|
||||
* do tipo content_page publicado pelo usuário.
|
||||
*/
|
||||
public function home(UserInterface $user): array {
|
||||
$cache = [
|
||||
'tags' => ['node_list:content_page', 'user:' . $user->id()],
|
||||
'tags' => [
|
||||
'node_list:content_page',
|
||||
'user:' . $user->id(),
|
||||
'site_users_microsite_config:' . $user->id(),
|
||||
],
|
||||
'contexts' => ['route'],
|
||||
];
|
||||
|
||||
$homepage_nid = $this->userData->get('site_users_microsite', $user->id(), 'homepage_nid');
|
||||
|
||||
if ($homepage_nid) {
|
||||
$node = $this->entityTypeManager()->getStorage('node')->load($homepage_nid);
|
||||
if ($node && $node->isPublished() && $node->access('view')) {
|
||||
$build = $this->entityTypeManager()->getViewBuilder('node')->view($node, 'full');
|
||||
$build['#cache'] = $cache;
|
||||
return $build;
|
||||
}
|
||||
}
|
||||
|
||||
$nids = $this->entityTypeManager()->getStorage('node')
|
||||
->getQuery()
|
||||
->condition('uid', $user->id())
|
||||
@@ -53,11 +81,29 @@ class MicrositeHomeController extends ControllerBase {
|
||||
return $this->entityTypeManager()->getViewBuilder('user')->view($user, 'full');
|
||||
}
|
||||
|
||||
/**
|
||||
* Redireciona para a página de configuração do microsite do usuário atual.
|
||||
*
|
||||
* Usada pelo link do menu da conta, que não suporta parâmetros dinâmicos.
|
||||
*/
|
||||
public function redirectToMyConfig(): RedirectResponse {
|
||||
return $this->redirect('site_users_microsite.user_config', [
|
||||
'user' => $this->currentUser()->id(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback de título para a página inicial.
|
||||
*/
|
||||
public function title(UserInterface $user): TranslatableMarkup {
|
||||
return $this->t("@name", ['@name' => $user->getDisplayName()]);
|
||||
return $this->t('@name', ['@name' => $user->getDisplayName()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback de título para a página de perfil.
|
||||
*/
|
||||
public function profileTitle(UserInterface $user): TranslatableMarkup {
|
||||
return $this->t('Perfil de @name', ['@name' => $user->getDisplayName()]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\site_users_microsite\Form;
|
||||
|
||||
use Drupal\Core\Cache\Cache;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Form\FormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\user\UserDataInterface;
|
||||
use Drupal\user\UserInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Formulário de configuração do microsite pessoal do usuário.
|
||||
*/
|
||||
class MicrositeUserConfigForm extends FormBase {
|
||||
|
||||
public function __construct(
|
||||
protected EntityTypeManagerInterface $entityTypeManager,
|
||||
protected UserDataInterface $userData,
|
||||
) {}
|
||||
|
||||
public static function create(ContainerInterface $container): static {
|
||||
return new static(
|
||||
$container->get('entity_type.manager'),
|
||||
$container->get('user.data'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId(): string {
|
||||
return 'site_users_microsite_user_config';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state, ?UserInterface $user = NULL): array {
|
||||
if ($user === NULL) {
|
||||
return $form;
|
||||
}
|
||||
|
||||
$form_state->set('user', $user);
|
||||
|
||||
$homepage_nid = $this->userData->get('site_users_microsite', $user->id(), 'homepage_nid');
|
||||
$use_homepage_title = $this->userData->get('site_users_microsite', $user->id(), 'use_homepage_title');
|
||||
|
||||
$nids = $this->entityTypeManager->getStorage('node')
|
||||
->getQuery()
|
||||
->condition('uid', $user->id())
|
||||
->condition('type', 'content_page')
|
||||
->condition('status', 1)
|
||||
->notExists('field_parent_page')
|
||||
->accessCheck(TRUE)
|
||||
->sort('title')
|
||||
->execute();
|
||||
|
||||
$options = ['' => $this->t('— primeira página publicada —')];
|
||||
if (!empty($nids)) {
|
||||
$nodes = $this->entityTypeManager->getStorage('node')->loadMultiple($nids);
|
||||
foreach ($nodes as $nid => $node) {
|
||||
$options[$nid] = $node->label();
|
||||
}
|
||||
}
|
||||
|
||||
$form['#attributes']['class'][] = 'microsite-form';
|
||||
$form['#attached']['library'][] = 'site_users_microsite_theme/form';
|
||||
|
||||
$form['homepage_nid'] = [
|
||||
'#type' => 'select',
|
||||
'#title' => $this->t('Homepage content'),
|
||||
'#description' => $this->t('Select which content to display on your microsite homepage.'),
|
||||
'#options' => $options,
|
||||
'#default_value' => $homepage_nid ?? '',
|
||||
];
|
||||
|
||||
$form['use_homepage_title'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => $this->t('Use homepage content title as page title'),
|
||||
'#description' => $this->t('When checked, the title of the selected homepage content replaces the default page title (your display name).'),
|
||||
'#default_value' => $use_homepage_title ?? FALSE,
|
||||
];
|
||||
|
||||
$form['actions'] = ['#type' => 'actions'];
|
||||
$form['actions']['submit'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('Save configuration'),
|
||||
];
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state): void {
|
||||
$user = $form_state->get('user');
|
||||
$nid = $form_state->getValue('homepage_nid');
|
||||
|
||||
if (empty($nid)) {
|
||||
$this->userData->delete('site_users_microsite', $user->id(), 'homepage_nid');
|
||||
}
|
||||
else {
|
||||
$this->userData->set('site_users_microsite', $user->id(), 'homepage_nid', (int) $nid);
|
||||
}
|
||||
|
||||
if ($form_state->getValue('use_homepage_title')) {
|
||||
$this->userData->set('site_users_microsite', $user->id(), 'use_homepage_title', TRUE);
|
||||
}
|
||||
else {
|
||||
$this->userData->delete('site_users_microsite', $user->id(), 'use_homepage_title');
|
||||
}
|
||||
|
||||
Cache::invalidateTags(['site_users_microsite_config:' . $user->id()]);
|
||||
$this->messenger()->addStatus($this->t('Configuration saved.'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\site_users_microsite\PathProcessor;
|
||||
|
||||
use Drupal\Core\Language\LanguageInterface;
|
||||
use Drupal\Core\Language\LanguageManagerInterface;
|
||||
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
|
||||
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
|
||||
use Drupal\Core\Render\BubbleableMetadata;
|
||||
use Drupal\path_alias\AliasManagerInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
/**
|
||||
* Processa subpáginas do microsite para funcionar com aliases de usuário.
|
||||
*
|
||||
* Converte /user/{username}/{subpage} <-> /user/{uid}/{subpage} de forma
|
||||
* transparente, complementando o alias exato /user/{username} do Pathauto.
|
||||
*/
|
||||
class MicrositeSubpagePathProcessor implements InboundPathProcessorInterface, OutboundPathProcessorInterface {
|
||||
|
||||
public function __construct(
|
||||
private AliasManagerInterface $aliasManager,
|
||||
private LanguageManagerInterface $languageManager,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* Converte /user/{username}/{subpage} para /user/{uid}/{subpage}.
|
||||
*/
|
||||
public function processInbound($path, Request $request) {
|
||||
if (!preg_match('#^/user/([^/]+)(/.+)$#', $path, $matches)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$segment = $matches[1];
|
||||
$rest = $matches[2];
|
||||
|
||||
// Segmento numérico já é UID — nada a fazer.
|
||||
if (is_numeric($segment)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$alias = '/user/' . $segment;
|
||||
$system_path = $this->lookupSystemPath($alias);
|
||||
|
||||
if ($system_path !== $alias && preg_match('#^/user/\d+$#', $system_path)) {
|
||||
return $system_path . $rest;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* Converte /user/{uid}/{subpage} para /user/{username}/{subpage}.
|
||||
*/
|
||||
public function processOutbound($path, &$options = [], ?Request $request = NULL, ?BubbleableMetadata $bubbleable_metadata = NULL) {
|
||||
if (!preg_match('#^/user/(\d+)(/.+)$#', $path, $matches)) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$uid = $matches[1];
|
||||
$rest = $matches[2];
|
||||
$alias = $this->aliasManager->getAliasByPath('/user/' . $uid);
|
||||
|
||||
if ($alias !== '/user/' . $uid) {
|
||||
if ($bubbleable_metadata) {
|
||||
$bubbleable_metadata->addCacheContexts(['url.path']);
|
||||
}
|
||||
return $alias . $rest;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Busca o caminho interno para um alias tentando todos os idiomas.
|
||||
*
|
||||
* O alias manager só faz fallback para LANGCODE_NOT_SPECIFIED; aliases
|
||||
* armazenados com 'en' não são encontrados quando o idioma atual é 'pt-br'.
|
||||
*/
|
||||
private function lookupSystemPath(string $alias): string {
|
||||
$langcodes = array_keys($this->languageManager->getLanguages());
|
||||
$langcodes[] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
|
||||
|
||||
foreach ($langcodes as $langcode) {
|
||||
$system_path = $this->aliasManager->getPathByAlias($alias, $langcode);
|
||||
if ($system_path !== $alias) {
|
||||
return $system_path;
|
||||
}
|
||||
}
|
||||
|
||||
return $alias;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -66,12 +66,14 @@ class MicrositeHeaderBlock extends BlockBase implements ContainerFactoryPluginIn
|
||||
'#photo_alt' => $this->getPhotoAlt($user),
|
||||
'#name' => $this->getFieldValue($user, 'field_user_name') ?: $user->getDisplayName(),
|
||||
'#bio' => $this->getProcessedValue($user, 'field_user_bio'),
|
||||
'#phone' => $this->getFieldValue($user, 'field_user_phone'),
|
||||
'#email' => $user->getEmail(),
|
||||
'#homepage' => $this->getFieldUri($user, 'field_user_homepage'),
|
||||
'#lattes_id' => $this->getFieldValue($user, 'field_user_id_lattes'),
|
||||
'#orcid_id' => $this->getFieldValue($user, 'field_user_orcid'),
|
||||
'#mathscinet_id' => $this->getFieldValue($user, 'field_user_mathscinetid'),
|
||||
'#department' => $this->getReferencedEntityLabel($user, 'field_user_department'),
|
||||
'#department_url' => $this->getReferencedEntityUrl($user, 'field_user_department'),
|
||||
'#work_phone' => $this->getFieldValue($user, 'field_user_work_phone'),
|
||||
'#cache' => [
|
||||
'tags' => $user->getCacheTags(),
|
||||
'contexts' => ['route'],
|
||||
@@ -81,6 +83,10 @@ class MicrositeHeaderBlock extends BlockBase implements ContainerFactoryPluginIn
|
||||
|
||||
/**
|
||||
* Retorna o usuário da rota atual.
|
||||
*
|
||||
* Primeiro tenta o parâmetro 'user' da rota (rotas próprias do microsite).
|
||||
* Caso não exista (ex: rota entity.node.canonical acessada via alias
|
||||
* /user/{id}/...), extrai o ID do alias do caminho atual.
|
||||
*/
|
||||
protected function getUser(): ?UserInterface {
|
||||
$user = $this->routeMatch->getParameter('user');
|
||||
@@ -90,6 +96,11 @@ class MicrositeHeaderBlock extends BlockBase implements ContainerFactoryPluginIn
|
||||
if (is_numeric($user)) {
|
||||
return $this->entityTypeManager->getStorage('user')->load($user);
|
||||
}
|
||||
|
||||
if (function_exists('site_users_get_microsite_user')) {
|
||||
return site_users_get_microsite_user();
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -136,6 +147,36 @@ class MicrositeHeaderBlock extends BlockBase implements ContainerFactoryPluginIn
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retorna o label da entidade referenciada por um campo entity_reference.
|
||||
*/
|
||||
protected function getReferencedEntityLabel(UserInterface $user, string $field_name): ?string {
|
||||
if (!$user->hasField($field_name) || $user->get($field_name)->isEmpty()) {
|
||||
return NULL;
|
||||
}
|
||||
$entity = $user->get($field_name)->entity;
|
||||
return $entity ? $entity->label() : NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retorna a URL canônica da entidade referenciada por um campo entity_reference.
|
||||
*/
|
||||
protected function getReferencedEntityUrl(UserInterface $user, string $field_name): ?string {
|
||||
if (!$user->hasField($field_name) || $user->get($field_name)->isEmpty()) {
|
||||
return NULL;
|
||||
}
|
||||
$entity = $user->get($field_name)->entity;
|
||||
if (!$entity || !$entity->hasLinkTemplate('canonical')) {
|
||||
return NULL;
|
||||
}
|
||||
try {
|
||||
return $entity->toUrl('canonical')->toString();
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retorna o valor de texto de um campo do usuário.
|
||||
*/
|
||||
|
||||
@@ -4,21 +4,70 @@ namespace Drupal\site_users_microsite\Theme;
|
||||
|
||||
use Drupal\Core\Routing\RouteMatchInterface;
|
||||
use Drupal\Core\Theme\ThemeNegotiatorInterface;
|
||||
use Drupal\path_alias\AliasManagerInterface;
|
||||
use Drupal\user\UserInterface;
|
||||
|
||||
/**
|
||||
* Aplica o tema microsite nas rotas de perfil de usuário e do micro-site.
|
||||
*/
|
||||
class MicrositeThemeNegotiator implements ThemeNegotiatorInterface {
|
||||
|
||||
public function __construct(
|
||||
private AliasManagerInterface $aliasManager,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function applies(RouteMatchInterface $route_match): bool {
|
||||
$route_name = $route_match->getRouteName();
|
||||
$excluded = ['site_users_microsite.settings'];
|
||||
return ($route_name === 'entity.user.canonical'
|
||||
|| str_starts_with($route_name, 'site_users_microsite.'))
|
||||
&& !in_array($route_name, $excluded);
|
||||
$route_name = $route_match->getRouteName() ?? '';
|
||||
|
||||
// Rotas administrativas e de edição nunca recebem o tema do microsite.
|
||||
$excluded = [
|
||||
'site_users_microsite.settings',
|
||||
'site_users_microsite.user_config',
|
||||
'site_users_microsite.my_config',
|
||||
];
|
||||
if (in_array($route_name, $excluded, TRUE)) {
|
||||
return FALSE;
|
||||
}
|
||||
foreach (['entity.user.edit_', 'entity.user.cancel', 'user.admin'] as $prefix) {
|
||||
if (str_starts_with($route_name, $prefix)) {
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
// Rota canônica e rotas próprias do microsite.
|
||||
if ($route_name === 'entity.user.canonical') {
|
||||
return TRUE;
|
||||
}
|
||||
if (str_starts_with($route_name, 'site_users_microsite.')) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// Qualquer rota com parâmetro 'user' (entidade) sob /user/{user}/.
|
||||
$user = $route_match->getParameter('user');
|
||||
if ($user instanceof UserInterface) {
|
||||
$route = $route_match->getRouteObject();
|
||||
$path = $route ? $route->getPath() : '';
|
||||
if (str_starts_with($path, '/user/{user}/')) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
// Nós cujo alias começa com /user/{uid}/ (ex.: structural_pages).
|
||||
if ($route_name === 'entity.node.canonical') {
|
||||
$node = $route_match->getParameter('node');
|
||||
if ($node) {
|
||||
$nid = is_object($node) ? $node->id() : $node;
|
||||
$alias = $this->aliasManager->getAliasByPath('/node/' . $nid);
|
||||
if (preg_match('#^/user/\d+/#', $alias)) {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -37,16 +37,26 @@
|
||||
|
||||
<h1 class="msite-header-block__name">{{ name }}</h1>
|
||||
|
||||
{% if department %}
|
||||
<div class="msite-header-block__department">
|
||||
{% if department_url %}
|
||||
<a href="{{ department_url }}">{{ department }}</a>
|
||||
{% else %}
|
||||
{{ department }}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if bio %}
|
||||
<div class="msite-header-block__bio">{{ bio|raw }}</div>
|
||||
{% endif %}
|
||||
|
||||
{% if phone or email %}
|
||||
{% if work_phone or email %}
|
||||
<ul class="msite-header-block__contact">
|
||||
{% if phone %}
|
||||
{% if work_phone %}
|
||||
<li class="msite-header-block__contact-item">
|
||||
<span class="msite-header-block__contact-label">{{ 'Telefone'|t }}:</span>
|
||||
<a href="tel:{{ phone }}">{{ phone }}</a>
|
||||
<a href="tel:{{ work_phone }}">{{ work_phone }}</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
{% if email %}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
name: 'Site Users User Content'
|
||||
type: module
|
||||
description: 'Provides User entity support as parent type for Structural Pages module.'
|
||||
package: 'Site Users'
|
||||
core_version_requirement: ^10.3 || ^11
|
||||
dependencies:
|
||||
- structural_pages:structural_pages
|
||||
- site_users:site_users
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\site_users_user_content\Plugin\ParentEntityHandler;
|
||||
|
||||
use Drupal\Core\StringTranslation\TranslatableMarkup;
|
||||
use Drupal\structural_pages\Attribute\ParentEntityHandler;
|
||||
use Drupal\structural_pages\ParentEntityHandler\ParentEntityHandlerBase;
|
||||
|
||||
/**
|
||||
* Handler for user entities.
|
||||
*
|
||||
* Allows content_page nodes to use a user entity as their parent, enabling
|
||||
* personal microsite content organisation without a site section.
|
||||
*/
|
||||
#[ParentEntityHandler(
|
||||
id: 'user',
|
||||
label: new TranslatableMarkup('Users (user)'),
|
||||
entity_type_id: 'user',
|
||||
clears_site_section: TRUE,
|
||||
sort_field: 'name',
|
||||
weight: 30,
|
||||
)]
|
||||
class UserHandler extends ParentEntityHandlerBase {}
|
||||
@@ -194,6 +194,79 @@ function site_users_install() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove mídias LDAP geradas sem UID (URI ldap_photo_.jpg/png) de todos os
|
||||
* usuários e apaga os arquivos e mídias correspondentes.
|
||||
*
|
||||
* Causa: durante provisionamento LDAP, $account->id() era vazio antes do
|
||||
* primeiro save, gerando URI única compartilhada por todos os usuários.
|
||||
*/
|
||||
function site_users_update_10011() {
|
||||
$file_storage = \Drupal::entityTypeManager()->getStorage('file');
|
||||
$media_storage = \Drupal::entityTypeManager()->getStorage('media');
|
||||
$user_storage = \Drupal::entityTypeManager()->getStorage('user');
|
||||
|
||||
// Localiza arquivos com URI sem UID (ldap_photo_.jpg, ldap_photo_.png…).
|
||||
$fids = $file_storage->getQuery()
|
||||
->condition('uri', 'public://ldap_photos/ldap_photo_.', 'STARTS_WITH')
|
||||
->accessCheck(FALSE)
|
||||
->execute();
|
||||
|
||||
if (empty($fids)) {
|
||||
return t('Nenhum arquivo LDAP sem UID encontrado.');
|
||||
}
|
||||
|
||||
$removed_media = 0;
|
||||
$affected_users = 0;
|
||||
|
||||
foreach ($fids as $fid) {
|
||||
$medias = $media_storage->loadByProperties([
|
||||
'bundle' => 'image',
|
||||
'field_media_image.target_id' => $fid,
|
||||
]);
|
||||
|
||||
foreach ($medias as $media) {
|
||||
$mid = (int) $media->id();
|
||||
|
||||
$uids = $user_storage->getQuery()
|
||||
->condition('field_user_photos.target_id', $mid)
|
||||
->accessCheck(FALSE)
|
||||
->execute();
|
||||
|
||||
foreach ($uids as $uid) {
|
||||
$user = $user_storage->load($uid);
|
||||
if (!$user) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$photos = array_column($user->get('field_user_photos')->getValue(), 'target_id');
|
||||
$photos = array_values(array_filter($photos, fn($id) => (int) $id !== $mid));
|
||||
$user->set('field_user_photos', array_map(fn($id) => ['target_id' => $id], $photos));
|
||||
|
||||
if ((int) $user->get('field_user_default_photo')->target_id === $mid) {
|
||||
$user->set('field_user_default_photo', empty($photos) ? NULL : $photos[0]);
|
||||
}
|
||||
|
||||
$user->save();
|
||||
$affected_users++;
|
||||
}
|
||||
|
||||
$media->delete();
|
||||
$removed_media++;
|
||||
}
|
||||
|
||||
$file = $file_storage->load($fid);
|
||||
if ($file) {
|
||||
$file->delete();
|
||||
}
|
||||
}
|
||||
|
||||
return t('Removidas @m mídias sem UID de @u usuários.', [
|
||||
'@m' => $removed_media,
|
||||
'@u' => $affected_users,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adiciona o campo field_user_default_photo para seleção de foto padrão.
|
||||
*/
|
||||
@@ -470,10 +543,10 @@ function site_users_update_10006() {
|
||||
$form_display->removeComponent('field_user_selected_view_mode')->save();
|
||||
}
|
||||
|
||||
// 6. Remover de todos os view displays existentes.
|
||||
$displays = $display_storage->loadMultiple();
|
||||
// 6. Remover de todos os view displays de usuário existentes.
|
||||
$displays = $display_storage->loadByProperties(['targetEntityType' => 'user']);
|
||||
foreach ($displays as $display) {
|
||||
if ($display->getTargetEntityTypeId() === 'user' && $display->getComponent('field_user_selected_view_mode')) {
|
||||
if ($display->getComponent('field_user_selected_view_mode')) {
|
||||
$display->removeComponent('field_user_selected_view_mode')->save();
|
||||
}
|
||||
}
|
||||
@@ -614,6 +687,86 @@ function site_users_update_10009() {
|
||||
return t('Campo field_user_homepage criado com sucesso.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove fotos LDAP placeholder (abaixo do tamanho mínimo configurado).
|
||||
*
|
||||
* Limpa field_user_photos e field_user_default_photo dos usuários afetados
|
||||
* e apaga as entidades de mídia e arquivo correspondentes.
|
||||
*/
|
||||
function site_users_update_10010() {
|
||||
$min_size = (int) (\Drupal::config('site_users.settings')->get('photos.ldap_min_photo_size') ?? 10240);
|
||||
|
||||
// Busca arquivos LDAP abaixo do tamanho mínimo.
|
||||
$fids = \Drupal::entityTypeManager()->getStorage('file')->getQuery()
|
||||
->condition('uri', 'public://ldap_photos/', 'STARTS_WITH')
|
||||
->condition('filesize', $min_size, '<')
|
||||
->accessCheck(FALSE)
|
||||
->execute();
|
||||
|
||||
if (empty($fids)) {
|
||||
return t('Nenhuma foto LDAP placeholder encontrada.');
|
||||
}
|
||||
|
||||
$media_storage = \Drupal::entityTypeManager()->getStorage('media');
|
||||
$user_storage = \Drupal::entityTypeManager()->getStorage('user');
|
||||
$removed_media = 0;
|
||||
$affected_users = 0;
|
||||
|
||||
foreach ($fids as $fid) {
|
||||
// Localiza a entidade de mídia que usa este arquivo.
|
||||
$medias = $media_storage->loadByProperties([
|
||||
'bundle' => 'image',
|
||||
'field_media_image.target_id' => $fid,
|
||||
]);
|
||||
|
||||
foreach ($medias as $media) {
|
||||
$mid = (int) $media->id();
|
||||
|
||||
// Busca usuários que têm esta mídia em field_user_photos.
|
||||
$uids = $user_storage->getQuery()
|
||||
->condition('field_user_photos.target_id', $mid)
|
||||
->accessCheck(FALSE)
|
||||
->execute();
|
||||
|
||||
foreach ($uids as $uid) {
|
||||
/** @var \Drupal\user\UserInterface $user */
|
||||
$user = $user_storage->load($uid);
|
||||
if (!$user) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Remove a mídia de field_user_photos.
|
||||
$photos = array_column($user->get('field_user_photos')->getValue(), 'target_id');
|
||||
$photos = array_values(array_filter($photos, fn($id) => (int) $id !== $mid));
|
||||
$user->set('field_user_photos', array_map(fn($id) => ['target_id' => $id], $photos));
|
||||
|
||||
// Limpa field_user_default_photo se apontar para esta mídia.
|
||||
$default_mid = $user->get('field_user_default_photo')->target_id;
|
||||
if ((int) $default_mid === $mid) {
|
||||
$user->set('field_user_default_photo', empty($photos) ? NULL : $photos[0]);
|
||||
}
|
||||
|
||||
$user->save();
|
||||
$affected_users++;
|
||||
}
|
||||
|
||||
$media->delete();
|
||||
$removed_media++;
|
||||
}
|
||||
|
||||
// Apaga o arquivo gerenciado.
|
||||
$file = \Drupal::entityTypeManager()->getStorage('file')->load($fid);
|
||||
if ($file) {
|
||||
$file->delete();
|
||||
}
|
||||
}
|
||||
|
||||
return t('Removidas @m mídias placeholder de @u usuários.', [
|
||||
'@m' => $removed_media,
|
||||
'@u' => $affected_users,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Corrige mapeamentos LDAP com campos de string nulos na config ativa.
|
||||
*/
|
||||
|
||||
@@ -4,3 +4,10 @@ site_users.settings:
|
||||
route_name: site_users.settings
|
||||
parent: site_tools.admin_config
|
||||
weight: 10
|
||||
|
||||
site_users.add_content:
|
||||
title: 'Adicionar'
|
||||
route_name: site_users.add_content
|
||||
menu_name: account
|
||||
weight: -5
|
||||
expanded: true
|
||||
|
||||
@@ -11,6 +11,7 @@ use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
|
||||
use Drupal\Core\Field\FieldDefinitionInterface;
|
||||
use Drupal\Core\Field\FieldItemListInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Menu\MenuLinkDefault;
|
||||
use Drupal\Core\Session\AccountInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\field\FieldConfigInterface;
|
||||
@@ -529,11 +530,35 @@ function site_users_user_format_name_alter(&$name, $account) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retorna o usuário dono do microsite para a requisição atual.
|
||||
*
|
||||
* Tenta o parâmetro 'user' da rota (rotas próprias do microsite) e, se não
|
||||
* encontrar, extrai o ID do alias do caminho atual (ex: /user/229/projetos).
|
||||
*/
|
||||
function site_users_get_microsite_user(): ?UserInterface {
|
||||
$user = \Drupal::routeMatch()->getParameter('user');
|
||||
if ($user instanceof UserInterface) {
|
||||
return $user;
|
||||
}
|
||||
if (is_numeric($user)) {
|
||||
return \Drupal::entityTypeManager()->getStorage('user')->load($user);
|
||||
}
|
||||
|
||||
$alias = \Drupal::service('path_alias.manager')
|
||||
->getAliasByPath(\Drupal::service('path.current')->getPath());
|
||||
if (preg_match('#^/user/(\d+)(/|$)#', $alias, $matches)) {
|
||||
return \Drupal::entityTypeManager()->getStorage('user')->load($matches[1]);
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_site_tools_share_links().
|
||||
*/
|
||||
function site_users_site_tools_share_links(): array {
|
||||
$user = \Drupal::routeMatch()->getParameter('user');
|
||||
$user = site_users_get_microsite_user();
|
||||
|
||||
if (!($user instanceof UserInterface)) {
|
||||
return [];
|
||||
@@ -604,3 +629,44 @@ function site_users_get_default_photo(UserInterface $user): ?MediaInterface {
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_menu_links_discovered_alter().
|
||||
*
|
||||
* Adiciona dinamicamente os subitens do menu "Adicionar" configurados em
|
||||
* site_users.settings:add_content_links.
|
||||
*/
|
||||
function site_users_menu_links_discovered_alter(array &$links): void {
|
||||
$items = \Drupal::config('site_users.settings')->get('add_content_links') ?? [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (empty($item['route_name']) || empty($item['label'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// ID estável derivado da rota e dos parâmetros.
|
||||
$parts = [preg_replace('/[^a-z0-9]/', '_', strtolower($item['route_name']))];
|
||||
foreach ($item['route_parameters'] ?? [] as $value) {
|
||||
$parts[] = preg_replace('/[^a-z0-9]/', '_', strtolower((string) $value));
|
||||
}
|
||||
$id = 'site_users.add_content_child.' . implode('_', $parts);
|
||||
|
||||
$links[$id] = [
|
||||
'id' => $id,
|
||||
'title' => $item['label'],
|
||||
'route_name' => $item['route_name'],
|
||||
'route_parameters' => $item['route_parameters'] ?? [],
|
||||
'menu_name' => 'account',
|
||||
'parent' => 'site_users.add_content',
|
||||
'weight' => (int) ($item['weight'] ?? 0),
|
||||
'provider' => 'site_users',
|
||||
'class' => MenuLinkDefault::class,
|
||||
'form_class' => 'Drupal\Core\Menu\Form\MenuLinkDefaultForm',
|
||||
'metadata' => [],
|
||||
'options' => [],
|
||||
'expanded' => FALSE,
|
||||
'enabled' => TRUE,
|
||||
'discovered' => TRUE,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,3 +5,11 @@ site_users.settings:
|
||||
_title: 'Site Users Settings'
|
||||
requirements:
|
||||
_permission: 'administer site_users settings'
|
||||
|
||||
site_users.add_content:
|
||||
path: '/add-content'
|
||||
defaults:
|
||||
_controller: '\Drupal\site_users\Controller\AddContentController::redirectToFirst'
|
||||
_title: 'Adicionar'
|
||||
requirements:
|
||||
_custom_access: 'site_users.add_content_access::access'
|
||||
|
||||
@@ -6,3 +6,9 @@ services:
|
||||
- '@entity_type.manager'
|
||||
- '@file.repository'
|
||||
- '@file_system'
|
||||
|
||||
site_users.add_content_access:
|
||||
class: Drupal\site_users\Access\AddContentAccessCheck
|
||||
arguments:
|
||||
- '@config.factory'
|
||||
- '@access_manager'
|
||||
|
||||
47
src/Access/AddContentAccessCheck.php
Normal file
47
src/Access/AddContentAccessCheck.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\site_users\Access;
|
||||
|
||||
use Drupal\Core\Access\AccessManagerInterface;
|
||||
use Drupal\Core\Access\AccessResult;
|
||||
use Drupal\Core\Access\AccessResultInterface;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Routing\Access\AccessInterface;
|
||||
use Drupal\Core\Session\AccountInterface;
|
||||
|
||||
/**
|
||||
* Grants access to the "Adicionar" parent menu route when any child is accessible.
|
||||
*/
|
||||
class AddContentAccessCheck implements AccessInterface {
|
||||
|
||||
public function __construct(
|
||||
private readonly ConfigFactoryInterface $configFactory,
|
||||
private readonly AccessManagerInterface $accessManager,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Returns allowed if the user can access at least one configured add route.
|
||||
*/
|
||||
public function access(AccountInterface $account): AccessResultInterface {
|
||||
$items = $this->configFactory
|
||||
->get('site_users.settings')
|
||||
->get('add_content_links') ?? [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (empty($item['route_name'])) {
|
||||
continue;
|
||||
}
|
||||
$params = $item['route_parameters'] ?? [];
|
||||
if ($this->accessManager->checkNamedRoute($item['route_name'], $params, $account)) {
|
||||
return AccessResult::allowed()
|
||||
->addCacheContexts(['user.permissions', 'user.roles']);
|
||||
}
|
||||
}
|
||||
|
||||
return AccessResult::forbidden()
|
||||
->addCacheContexts(['user.permissions', 'user.roles']);
|
||||
}
|
||||
|
||||
}
|
||||
48
src/Controller/AddContentController.php
Normal file
48
src/Controller/AddContentController.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\site_users\Controller;
|
||||
|
||||
use Drupal\Core\Access\AccessManagerInterface;
|
||||
use Drupal\Core\Controller\ControllerBase;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
|
||||
/**
|
||||
* Redirects to the first accessible add-content route for the current user.
|
||||
*/
|
||||
class AddContentController extends ControllerBase {
|
||||
|
||||
public function __construct(
|
||||
private readonly AccessManagerInterface $accessManager,
|
||||
) {}
|
||||
|
||||
public static function create(ContainerInterface $container): static {
|
||||
return new static(
|
||||
$container->get('access_manager'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects to the first accessible add route, or to the front page.
|
||||
*/
|
||||
public function redirectToFirst(): RedirectResponse {
|
||||
$items = $this->config('site_users.settings')
|
||||
->get('add_content_links') ?? [];
|
||||
$account = $this->currentUser();
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (empty($item['route_name'])) {
|
||||
continue;
|
||||
}
|
||||
$params = $item['route_parameters'] ?? [];
|
||||
if ($this->accessManager->checkNamedRoute($item['route_name'], $params, $account)) {
|
||||
return $this->redirect($item['route_name'], $params);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->redirect('<front>');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -118,6 +118,20 @@ class SiteUsersSettingsForm extends ConfigFormBase {
|
||||
],
|
||||
];
|
||||
|
||||
$form['photos']['photos_ldap_min_photo_size'] = [
|
||||
'#type' => 'number',
|
||||
'#title' => $this->t('Minimum LDAP photo size (bytes)'),
|
||||
'#description' => $this->t('Photos smaller than this size are ignored during LDAP sync, avoiding placeholder images. Default: 10240 (10 KB).'),
|
||||
'#default_value' => $config->get('photos.ldap_min_photo_size') ?? 10240,
|
||||
'#min' => 0,
|
||||
'#required' => TRUE,
|
||||
'#states' => [
|
||||
'visible' => [
|
||||
':input[name="photos_ldap_sync_enabled"]' => ['checked' => TRUE],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// Fieldset para campos editáveis pelo próprio usuário.
|
||||
$form['user_editable_fields'] = [
|
||||
'#type' => 'fieldset',
|
||||
@@ -177,6 +191,66 @@ class SiteUsersSettingsForm extends ConfigFormBase {
|
||||
}
|
||||
}
|
||||
|
||||
// Fieldset para itens do menu "Adicionar".
|
||||
$form['add_content_links'] = [
|
||||
'#type' => 'fieldset',
|
||||
'#title' => $this->t('Add content menu items'),
|
||||
'#description' => $this->t('Configure items shown under the "Adicionar" entry in the account menu. Each item points to an entity add route. Leave "Label" empty to remove the row.'),
|
||||
'#tree' => TRUE,
|
||||
];
|
||||
|
||||
$saved_items = $config->get('add_content_links') ?? [];
|
||||
// Append one blank row for adding a new item.
|
||||
$saved_items[] = ['label' => '', 'route_name' => '', 'route_parameters' => [], 'weight' => 0];
|
||||
|
||||
$form['add_content_links']['table'] = [
|
||||
'#type' => 'table',
|
||||
'#header' => [
|
||||
$this->t('Label'),
|
||||
$this->t('Route name'),
|
||||
$this->t('Parameter name'),
|
||||
$this->t('Parameter value'),
|
||||
$this->t('Weight'),
|
||||
],
|
||||
'#empty' => $this->t('No items yet. Fill in the row below to add one.'),
|
||||
];
|
||||
|
||||
foreach ($saved_items as $delta => $item) {
|
||||
$params = $item['route_parameters'] ?? [];
|
||||
$param_name = array_key_first($params) ?? '';
|
||||
$param_value = $params[$param_name] ?? '';
|
||||
|
||||
$form['add_content_links']['table'][$delta]['label'] = [
|
||||
'#type' => 'textfield',
|
||||
'#default_value' => $item['label'] ?? '',
|
||||
'#size' => 20,
|
||||
'#placeholder' => $this->t('e.g. Artigo'),
|
||||
];
|
||||
$form['add_content_links']['table'][$delta]['route_name'] = [
|
||||
'#type' => 'textfield',
|
||||
'#default_value' => $item['route_name'] ?? '',
|
||||
'#size' => 30,
|
||||
'#placeholder' => 'e.g. node.add',
|
||||
];
|
||||
$form['add_content_links']['table'][$delta]['param_name'] = [
|
||||
'#type' => 'textfield',
|
||||
'#default_value' => $param_name,
|
||||
'#size' => 20,
|
||||
'#placeholder' => 'e.g. node_type',
|
||||
];
|
||||
$form['add_content_links']['table'][$delta]['param_value'] = [
|
||||
'#type' => 'textfield',
|
||||
'#default_value' => $param_value,
|
||||
'#size' => 20,
|
||||
'#placeholder' => 'e.g. article',
|
||||
];
|
||||
$form['add_content_links']['table'][$delta]['weight'] = [
|
||||
'#type' => 'number',
|
||||
'#default_value' => (int) ($item['weight'] ?? 0),
|
||||
'#size' => 4,
|
||||
];
|
||||
}
|
||||
|
||||
return parent::buildForm($form, $form_state);
|
||||
}
|
||||
|
||||
@@ -210,7 +284,8 @@ class SiteUsersSettingsForm extends ConfigFormBase {
|
||||
$config
|
||||
->set('photos.max_count', $form_state->getValue('photos_max_count'))
|
||||
->set('photos.ldap_sync_enabled', (bool) $form_state->getValue('photos_ldap_sync_enabled'))
|
||||
->set('photos.ldap_attribute', $form_state->getValue('photos_ldap_attribute'));
|
||||
->set('photos.ldap_attribute', $form_state->getValue('photos_ldap_attribute'))
|
||||
->set('photos.ldap_min_photo_size', (int) $form_state->getValue('photos_ldap_min_photo_size'));
|
||||
|
||||
$definitions = \Drupal::service('entity_field.manager')
|
||||
->getFieldDefinitions('user', 'user');
|
||||
@@ -230,6 +305,32 @@ class SiteUsersSettingsForm extends ConfigFormBase {
|
||||
}
|
||||
}
|
||||
|
||||
// Salvar add_content_links: ignorar linhas sem label ou route_name.
|
||||
$links_raw = $form_state->getValue(['add_content_links', 'table']) ?? [];
|
||||
$add_content_links = [];
|
||||
foreach ($links_raw as $row) {
|
||||
$label = trim($row['label'] ?? '');
|
||||
$route_name = trim($row['route_name'] ?? '');
|
||||
if ($label === '' || $route_name === '') {
|
||||
continue;
|
||||
}
|
||||
$params = [];
|
||||
$param_name = trim($row['param_name'] ?? '');
|
||||
$param_value = trim($row['param_value'] ?? '');
|
||||
if ($param_name !== '') {
|
||||
$params[$param_name] = $param_value;
|
||||
}
|
||||
$add_content_links[] = [
|
||||
'label' => $label,
|
||||
'route_name' => $route_name,
|
||||
'route_parameters' => $params,
|
||||
'weight' => (int) ($row['weight'] ?? 0),
|
||||
];
|
||||
}
|
||||
// Reordena por weight.
|
||||
usort($add_content_links, fn($a, $b) => $a['weight'] <=> $b['weight']);
|
||||
$config->set('add_content_links', $add_content_links);
|
||||
|
||||
// Salvar role_view_modes: apenas os valores marcados (filtrar 0).
|
||||
$role_view_modes_raw = $form_state->getValue('role_view_modes') ?? [];
|
||||
$roles = \Drupal\user\Entity\Role::loadMultiple();
|
||||
|
||||
18
src/Plugin/Menu/AddContentMenuLink.php
Normal file
18
src/Plugin/Menu/AddContentMenuLink.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\site_users\Plugin\Menu;
|
||||
|
||||
use Drupal\Core\Menu\MenuLinkDefault;
|
||||
|
||||
/**
|
||||
* Provides derived menu links for add-content actions in the account menu.
|
||||
*
|
||||
* @MenuLink(
|
||||
* id = "site_users.add_content_child",
|
||||
* deriver = "Drupal\site_users\Plugin\Menu\AddContentMenuLinkDeriver"
|
||||
* )
|
||||
*/
|
||||
class AddContentMenuLink extends MenuLinkDefault {
|
||||
}
|
||||
64
src/Plugin/Menu/AddContentMenuLinkDeriver.php
Normal file
64
src/Plugin/Menu/AddContentMenuLinkDeriver.php
Normal file
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\site_users\Plugin\Menu;
|
||||
|
||||
use Drupal\Component\Plugin\Derivative\DeriverBase;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Generates account menu "Adicionar" child links from site_users.settings.
|
||||
*/
|
||||
class AddContentMenuLinkDeriver extends DeriverBase implements ContainerDeriverInterface {
|
||||
|
||||
public function __construct(
|
||||
private readonly ConfigFactoryInterface $configFactory,
|
||||
) {}
|
||||
|
||||
public static function create(ContainerInterface $container, $base_plugin_id): static {
|
||||
return new static($container->get('config.factory'));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getDerivativeDefinitions($base_plugin_definition): array {
|
||||
$this->derivatives = [];
|
||||
|
||||
$items = $this->configFactory
|
||||
->get('site_users.settings')
|
||||
->get('add_content_links') ?? [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (empty($item['route_name']) || empty($item['label'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$id = $this->buildId($item);
|
||||
$this->derivatives[$id] = $base_plugin_definition;
|
||||
$this->derivatives[$id]['title'] = $item['label'];
|
||||
$this->derivatives[$id]['route_name'] = $item['route_name'];
|
||||
$this->derivatives[$id]['route_parameters'] = $item['route_parameters'] ?? [];
|
||||
$this->derivatives[$id]['weight'] = (int) ($item['weight'] ?? 0);
|
||||
$this->derivatives[$id]['menu_name'] = 'account';
|
||||
$this->derivatives[$id]['parent'] = 'site_users.add_content';
|
||||
}
|
||||
|
||||
return $this->derivatives;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a stable derivative ID from the item's route and parameters.
|
||||
*/
|
||||
private function buildId(array $item): string {
|
||||
$parts = [preg_replace('/[^a-z0-9]/', '_', strtolower($item['route_name']))];
|
||||
foreach ($item['route_parameters'] ?? [] as $value) {
|
||||
$parts[] = preg_replace('/[^a-z0-9]/', '_', strtolower((string) $value));
|
||||
}
|
||||
return implode('_', $parts);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -32,6 +32,11 @@ class LdapPhotoSyncService {
|
||||
* changed since the last sync (same MD5), no file or media write occurs.
|
||||
*/
|
||||
public function syncFromLdapEntry(UserInterface $account, Entry $ldapEntry): void {
|
||||
// Usuário sem ID ainda não foi salvo — não é possível gerar URI única.
|
||||
if (!$account->id()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$config = $this->configFactory->get('site_users.settings');
|
||||
|
||||
if (!$config->get('photos.ldap_sync_enabled')) {
|
||||
@@ -48,6 +53,11 @@ class LdapPhotoSyncService {
|
||||
return;
|
||||
}
|
||||
|
||||
$min_size = (int) ($config->get('photos.ldap_min_photo_size') ?? 10240);
|
||||
if ($min_size > 0 && strlen($binary) < $min_size) {
|
||||
return;
|
||||
}
|
||||
|
||||
$extension = $this->detectExtension($binary);
|
||||
if (!$extension) {
|
||||
return;
|
||||
|
||||
87
themes/site_users_microsite_theme/css/microsite-form.css
Normal file
87
themes/site_users_microsite_theme/css/microsite-form.css
Normal file
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Microsite theme — estilos para formulários de configuração do usuário.
|
||||
*/
|
||||
|
||||
.microsite-form {
|
||||
background: #fff;
|
||||
border-radius: 6px;
|
||||
padding: 2rem;
|
||||
max-width: 600px;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.microsite-form .form-item {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.microsite-form label {
|
||||
display: block;
|
||||
margin-bottom: 0.4rem;
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.microsite-form select,
|
||||
.microsite-form input[type="text"],
|
||||
.microsite-form input[type="email"],
|
||||
.microsite-form textarea {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.95rem;
|
||||
font-family: inherit;
|
||||
color: #222;
|
||||
background: #fff;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
appearance: auto;
|
||||
}
|
||||
|
||||
.microsite-form select:focus,
|
||||
.microsite-form input:focus,
|
||||
.microsite-form textarea:focus {
|
||||
outline: none;
|
||||
border-color: hsl(202, 79%, 50%);
|
||||
box-shadow: 0 0 0 3px hsla(202, 79%, 50%, 0.2);
|
||||
}
|
||||
|
||||
.microsite-form .form-item__description,
|
||||
.microsite-form .description {
|
||||
margin-top: 0.35rem;
|
||||
font-size: 0.85rem;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.microsite-form .form-actions {
|
||||
margin-top: 2rem;
|
||||
padding-top: 1.25rem;
|
||||
border-top: 1px solid #eee;
|
||||
}
|
||||
|
||||
.microsite-form .button,
|
||||
.microsite-form input[type="submit"] {
|
||||
display: inline-block;
|
||||
padding: 0.55rem 1.5rem;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
font-family: inherit;
|
||||
color: #fff;
|
||||
background: hsl(202, 79%, 50%);
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.microsite-form .button:hover,
|
||||
.microsite-form input[type="submit"]:hover {
|
||||
background: hsl(202, 79%, 42%);
|
||||
}
|
||||
|
||||
.microsite-form .button:focus,
|
||||
.microsite-form input[type="submit"]:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px hsla(202, 79%, 50%, 0.35);
|
||||
}
|
||||
@@ -310,8 +310,42 @@ body.microsite {
|
||||
margin-inline-end: 18px;
|
||||
}
|
||||
|
||||
.microsite-top-bar li.menu__item {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.microsite-top-bar ul.menu ul.menu {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
min-width: 160px;
|
||||
flex-direction: column;
|
||||
background-color: hsl(201, 15%, 15%);
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.35);
|
||||
z-index: 100;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.microsite-top-bar li.menu__item:hover > ul.menu,
|
||||
.microsite-top-bar li.menu__item:focus-within > ul.menu {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.microsite-top-bar ul.menu ul.menu li.menu__item {
|
||||
margin-inline-end: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.microsite-top-bar ul.menu ul.menu a.menu__link {
|
||||
padding: 6px 16px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.microsite-top-bar ul.menu ul.menu a.menu__link:hover {
|
||||
background-color: hsl(201, 15%, 25%);
|
||||
}
|
||||
|
||||
.microsite-top-bar a.menu__link {
|
||||
|
||||
@@ -15,7 +15,9 @@ regions:
|
||||
highlighted: Highlighted
|
||||
tabs: Tabs
|
||||
messages: Messages
|
||||
content_above: Content Above
|
||||
content: Content
|
||||
content_below: Content Below
|
||||
sidebar: Sidebar
|
||||
social: Social
|
||||
footer: Footer
|
||||
|
||||
@@ -6,3 +6,10 @@ global:
|
||||
js/social-bar.js: {}
|
||||
dependencies:
|
||||
- core/drupal
|
||||
|
||||
form:
|
||||
css:
|
||||
theme:
|
||||
css/microsite-form.css: {}
|
||||
dependencies:
|
||||
- site_users_microsite_theme/global
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
|
||||
<div class="microsite-main-wrapper{% if page.sidebar %} microsite-main-wrapper--has-sidebar{% endif %}">
|
||||
<main id="main-content" class="microsite-main" role="main">
|
||||
{{ page.content_above }}
|
||||
{{ page.content }}
|
||||
</main>
|
||||
|
||||
@@ -90,6 +91,12 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if page.content_below %}
|
||||
<div class="microsite-content-below">
|
||||
{{ page.content_below }}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if page.footer %}
|
||||
<footer class="microsite-footer">
|
||||
{{ page.footer }}
|
||||
|
||||
Reference in New Issue
Block a user