diff --git a/web/modules/custom/yufu_concept/src/Plugin/rest/resource/AddConcept.php b/web/modules/custom/yufu_concept/src/Plugin/rest/resource/AddConcept.php index 44f77e5..258d09d 100644 --- a/web/modules/custom/yufu_concept/src/Plugin/rest/resource/AddConcept.php +++ b/web/modules/custom/yufu_concept/src/Plugin/rest/resource/AddConcept.php @@ -4,10 +4,10 @@ namespace Drupal\yufu_concept\Plugin\rest\resource; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; -use Drupal\Core\Mail\MailManagerInterface; use Drupal\Core\Session\AccountProxyInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; use Drupal\Core\TypedData\Exception\MissingDataException; +use Drupal\node\NodeInterface; use Drupal\rest\Plugin\ResourceBase; use Drupal\rest\ResourceResponse; use Psr\Log\LogLevel; @@ -39,20 +39,6 @@ class AddConcept extends ResourceBase { */ protected $currentUser; - /** - * Mail manager service. - * - * @var \Drupal\Core\Mail\MailManagerInterface - */ - protected $mailManager; - - /** - * Site configs. - * - * @var \Drupal\Core\Config\ImmutableConfig - */ - protected $config; - /** * Entity type manager service. * @@ -75,10 +61,6 @@ class AddConcept extends ResourceBase { * A logger instance. * @param \Drupal\Core\Session\AccountProxyInterface $current_user * A current user instance. - * @param \Drupal\Core\Mail\MailManagerInterface $mailManager - * Mail manager service. - * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory - * Config factory service. */ public function __construct( array $configuration, @@ -87,13 +69,9 @@ class AddConcept extends ResourceBase { array $serializer_formats, LoggerInterface $logger, AccountProxyInterface $current_user, - MailManagerInterface $mailManager, - ConfigFactoryInterface $configFactory, EntityTypeManagerInterface $entity_type_manager) { parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger); $this->currentUser = $current_user; - $this->mailManager = $mailManager; - $this->config = $configFactory; $this->entityTypeManager = $entity_type_manager; } @@ -106,10 +84,8 @@ class AddConcept extends ResourceBase { $plugin_id, $plugin_definition, $container->getParameter('serializer.formats'), - $container->get('logger.factory')->get('yufu_concept'), + $container->get('logger.channel.yufu_concept'), $container->get('current_user'), - $container->get('plugin.manager.mail'), - $container->get('config.factory'), $container->get('entity_type.manager') ); } @@ -117,6 +93,11 @@ class AddConcept extends ResourceBase { /** * Ustvari nov koncept. * + * Logika: + * 1. Zloadamo uporabnika preko emaila, ce ne obstaja, ga ustvarimo. + * 2. Zloadamo koncept prek uuid, ce ne obstaja, da ustvarimo. + * - avtor je zloadan prek maila + * * @param \Symfony\Component\HttpFoundation\Request; * Post request. * @@ -133,48 +114,108 @@ class AddConcept extends ResourceBase { } // Fields: naslov, text, povezani pojmi, email // Optional fields: language, related concept. - if (!empty($data['title']) && !empty($data['text'])) { - throw new MissingDataException('Title or text missing.'); + if (empty($data['title']) || empty($data['text']) || empty($data['uuid'])) { + throw new MissingDataException('Title, uuid or text missing.'); + } + $uid = $this->getUserIdByEmail($data['email'] ?? null); + if ($concept = $this->getConceptFromUuid($data['uuid'])) { + // Concept exists - create a new revision. + $concept->setNewRevision(TRUE); + $concept->setRevisionUserId($uid); + $concept->set('title', $data['title']); + $concept->set('body', $data['text'] ?? $concept->body->value); + $concept->isDefaultRevision(FALSE); + $concept->setRevisionLogMessage('New revision by concept endpoint.'); + $concept->moderation_state->target_id = 'draft'; + $concept->save(); + $this->logger->notice('New concept @title revision @revid created by uid @uid.', [ + '@title' => $concept->getTitle(), + '@revid' => $concept->getRevisionId(), + '@uid' => $uid, + ]); + } + else { + // Concept does not exist - create a new node. + $concept = [ + 'type' => 'concept', + 'title' => $data['title'], + 'body' => $data['text'], + 'uuid' => $data['uuid'], + 'uid' => $uid, + 'moderation_state' => 'draft', + ]; + // @TODO Check if related concepts are set and add them to the concept. + // @TODO Check language and add set it on concept if exists. + /** @var \Drupal\node\Entity\NodeInterface $concept */ + $concept = $this->entityTypeManager->getStorage('node')->create($concept); + $concept->save(); + $this->logger->log(LogLevel::NOTICE, $this->t('Creating concept: @title', [ + '@title' => $concept->getTitle(), + ])); } - $concept = [ - 'type' => 'concept', - 'title' => $data['title'], - 'body' => $data['body'], - ]; - $this->logger->log(LogLevel::NOTICE, $this->t('Creating concept: @title', [ - '@title' => $concept['title'], - ])); - // @TODO Check if related concepts are set and add them to the concept. - // @TODO Check language and add set it on concept if exists. - /** @var \Drupal\node\Entity\NodeInterface $concept */ - $concept = $this->entityTypeManager->getStorage('node')->create($concept); - $concept->save(); $response_status['concept'] = [ 'title' => $concept->label(), 'id' => $concept->id(), 'uuid' => $concept->uuid(), + 'revision_id' => $concept->getRevisionId(), + 'revision_create_time' => $concept->getRevisionCreationTime(), + 'revision_uid' => $concept->getRevisionUserId(), + 'uid' => $concept->uid->target_id, ]; - - if (!empty($data['email'])) { - // @TODO Poslji mail uporabniku, da se lahko registrira. - $site_email = $this->config->get('system.site')->get('mail'); - $module = 'yufu_concept'; - $key = 'add_concept_rest_resource'; - $to = $site_email; - // Send email to user to make him register to the website. - $params['message'] = $this->t('Creating concept: @title', [ - '@title' => $concept->label(), - ]); - $params['subject'] = $data['title']; - $params['from'] = $data['email']; - // @TODO Add validation for langode (must be from system configured endpoints). - $langcode = $data['lang'] ?? 'en'; - $send = TRUE; - $result = $this->mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send); - $response_status['status'] = $result['result']; - } $response = new ResourceResponse($response_status); return $response; } + /** + * Get concept from uuid. + * + * If concept is new, return null. + * + * @param string|null $uuid + * Uuid of the node. + * + * @return \Drupal\node\NodeInterface|null + */ + protected function getConceptFromUuid(?string $uuid): ?NodeInterface { + if (!$uuid) { + return NULL; + } + $node_storage = $this->entityTypeManager->getStorage('node'); + if ($concept = end($node_storage->loadByProperties(['uuid' => $uuid]))) { + return $concept; + } + return NULL; + } + + /** + * Loads user from email or creates a new blocked user. + * + * Side effect is to create a new user. + * + * @param string|null $email + * Email provided by the fe call to endpoint. + * + * @return int + * Id of the user. + * + */ + protected function getUserIdByEmail(?string $email): int { + if (!$email) { + return 0; + } + // Load user by email. If it doesn't exist, create one. + $user_storage = $this->entityTypeManager->getStorage('user'); + if ($user = end($user_storage->loadByProperties(['mail' => $email]))) { + return $user->id(); + } + $user = [ + 'mail' => $email, + 'name' => $email, + 'status' => 0, + ]; + $new_user = $user_storage->create($user); + $new_user->save(); + return $new_user->id(); + } + } diff --git a/web/modules/custom/yufu_concept/tests/local-emacs-test.rest b/web/modules/custom/yufu_concept/tests/local-emacs-test.rest index 25e3397..f024295 100644 --- a/web/modules/custom/yufu_concept/tests/local-emacs-test.rest +++ b/web/modules/custom/yufu_concept/tests/local-emacs-test.rest @@ -1,6 +1,7 @@ # _*_ restclient _*_ # Makes post http request to a resource from yufu_concept module. +# Make sure uuid is uniq or it will create new revision. POST https://yufu-manifest.ddev.site/api/pojem/dodaj User-Agent: Emacs Restclient @@ -8,7 +9,8 @@ Content-Type: application/json Cookies: "SSESSb6f5da6ef565138b872e3e58509d8150=0z6Zk4tRwTF4WAR%2CSO6rH0K5F7hqKpbe28XRRHwvTxo%2CUnpC" { -"title": "Emacs restclient test 102", -"body": "O wau. Emacs restclient. How nice.", -"email": "lio.novelli@radiostudent.si" +"title": "888 Emacs restclient test 888", +"text": "O wau. Emacs restclient. How nice. Dodam text. Spet.", +"email": "lio.novelli@radiostudent.si", +"uuid": "70c1ace2-aaaa-4dc5-84ed-3f21b83cb23a" } diff --git a/web/modules/custom/yufu_concept/yufu_concept.module b/web/modules/custom/yufu_concept/yufu_concept.module index 32304d1..0a8a750 100644 --- a/web/modules/custom/yufu_concept/yufu_concept.module +++ b/web/modules/custom/yufu_concept/yufu_concept.module @@ -4,23 +4,3 @@ * @file * Primary module hooks for Yufu Concept module. */ - -/** - * Implements hook_mail(). - * - * @TODO this should go into hook presave. - */ -function yufu_concept_mail($key, &$message, $params) { - $options = [ - 'langcode' => $message['langcode'], - ]; - - switch ($key) { - case 'add_concept_rest_resource': - // This is just a test implementation for sending emails. - $message['from'] = $params['from']; - $message['subject'] = $params['subject']; - $message['body'][] = $params['message']; - break; - } -}