o365-2.0.3/modules/o365_profile_rest/src/Plugin/rest/resource/O365ProfileRestResource.php
modules/o365_profile_rest/src/Plugin/rest/resource/O365ProfileRestResource.php
<?php
namespace Drupal\o365_profile_rest\Plugin\rest\resource;
use Drupal\Component\Utility\Html;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\externalauth\AuthmapInterface;
use Drupal\o365\AuthenticationService;
use Drupal\o365_profile\O365ProfileGetDataService;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\user\Entity\User;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
/**
* Provides a resource for get the Microsoft 365 profile data.
*
* @RestResource(
* id = "o365_profile_rest_status",
* label = @Translation("Microsoft 365 Connector - Profile status"),
* uri_paths = {
* "canonical" = "/o365/profile/user_status/{uid}",
* }
* )
*/
class O365ProfileRestResource extends ResourceBase {
/**
* The service we use to get user data.
*
* @var \Drupal\o365_profile\O365ProfileGetDataService
*/
protected O365ProfileGetDataService $getDataService;
/**
* The Microsoft 365 authentication service.
*
* @var \Drupal\o365\AuthenticationService
*/
protected AuthenticationService $authService;
/**
* The page request.
*
* @var \Symfony\Component\HttpFoundation\Request|null
*/
protected $request;
/**
* The externalauth mapping.
*
* @var \Drupal\externalauth\AuthmapInterface
*/
private AuthmapInterface $authmap;
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, O365ProfileGetDataService $getDataService, AuthenticationService $authenticationService, RequestStack $requestStack, AuthmapInterface $authmap) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->getDataService = $getDataService;
$this->authService = $authenticationService;
$this->request = $requestStack->getCurrentRequest();
$this->authmap = $authmap;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
// @phpstan-ignore-next-line
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('o365_profile'),
$container->get('o365_profile.get_data'),
$container->get('o365.authentication'),
$container->get('request_stack'),
$container->get('externalauth.authmap')
);
}
/**
* Get the user data from Drupal and Microsoft 365.
*
* @param string $uid
* The user ID.
*
* @return \Drupal\rest\ResourceResponse
* The REST response containing the profile.
*
* @throws \Drupal\Core\TempStore\TempStoreException
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
* @throws \Microsoft\Graph\Exception\GraphException
*/
public function get(string $uid): ResourceResponse {
// Check if we have a UID.
if ($uid) {
$data = ['uid' => $uid];
$auth = $this->authmap->get((int) $uid, 'o365_sso');
// Setup caching.
$cache = new CacheableMetadata();
$cacheTags = ['user:' . $uid];
$cacheContexts = ['user.permissions', 'url.query_args'];
// Check if the user is logged in with Microsoft 365.
if ($auth) {
$data['auth'] = $auth;
$user = User::load($uid);
if ($user) {
$data['mail'] = $user->getEmail();
$data['displayName'] = $user->getDisplayName();
// Check if we need to get the profile pic based on query parameter.
$getPhoto = FALSE;
if ($this->request->get('get_profile_pic')) {
$getPhoto = TRUE;
}
// Get data from Microsoft.
$userData = $this->getDataService->getProfileData($auth, '64x64', $getPhoto);
$data['initials'] = $userData['initials'];
if ($getPhoto) {
$data['user_img'] = $userData['imageSrc'];
}
if (!empty($userData['presenceData']['activity'])) {
$data['presence'] = $userData['presenceData']['activity'];
$class = Html::cleanCssIdentifier($userData['presenceData']['activity']);
$data['presence_class'] = strtolower($class);
}
if (!empty($userData['userData']['givenName'])) {
$data['givenName'] = $userData['userData']['givenName'];
}
if (!empty($userData['userData']['surname'])) {
$data['surname'] = $userData['userData']['surname'];
}
if (!empty($userData['userData']['businessPhones'])) {
$businessText = new TranslatableMarkup('Call on business phone');
$data['businessPhones'] = [
'number' => $userData['userData']['businessPhones'][0],
'text' => $businessText->render(),
];
}
if (!empty($userData['userData']['mobilePhone'])) {
$mobileText = new TranslatableMarkup('Call on mobile phone');
$data['mobilePhone'] = [
'number' => $userData['userData']['mobilePhone'],
'text' => $mobileText->render(),
];
}
$callText = new TranslatableMarkup('Call with Teams');
$data['call'] = [
'url' => 'https://teams.microsoft.com/l/call/0/0?users=' . $user->getEmail(),
'text' => $callText->render(),
];
$chatText = new TranslatableMarkup('Chat with Teams');
$data['chat'] = [
'url' => 'https://teams.microsoft.com/l/chat/0/0?users=' . $user->getEmail(),
'text' => $chatText->render(),
];
$videocallText = new TranslatableMarkup('Video call with Teams');
$data['videocall'] = [
'url' => 'https://teams.microsoft.com/l/call/0/0?users=' . $user->getEmail() . '&Withvideo=true',
'text' => $videocallText->render(),
];
}
}
// Generate the response.
$response = new ResourceResponse($data);
// Add the caching to the response.
$cache->setCacheTags($cacheTags);
$cache->setCacheContexts($cacheContexts);
$cache->setCacheMaxAge(3600);
$response->addCacheableDependency($cache);
// Return the response.
return $response;
}
// Throw an exception when there is no UID.
throw new BadRequestHttpException('No UID was provided');
}
}
