Exemplo n.º 1
0
  /**
   * {@inheritdoc}
   */
  public function import($currencyCode) {
    if ($existingEntity = $this->storage->load($currencyCode)) {
      // Pretend the currency was just imported.
      return $existingEntity;
    }

    $defaultLangcode = $this->languageManager->getDefaultLanguage()->getId();
    $currency = $this->externalRepository->get($currencyCode, $defaultLangcode, 'en');
    $values = [
      'langcode' => $defaultLangcode,
      'currencyCode' => $currency->getCurrencyCode(),
      'name' => $currency->getName(),
      'numericCode' => $currency->getNumericCode(),
      'symbol' => $currency->getSymbol(),
      'fractionDigits' => $currency->getFractionDigits(),
    ];
    $entity = $this->storage->create($values);
    $entity->trustData()->save();
    if ($this->languageManager->isMultilingual()) {
      // Import translations for any additional languages the site has.
      $languages = $this->languageManager->getLanguages(LanguageInterface::STATE_CONFIGURABLE);
      $languages = array_diff_key($languages, [$defaultLangcode => $defaultLangcode]);
      $langcodes = array_map(function ($language) {
        return $language->getId();
      }, $languages);
      $this->importEntityTranslations($entity, $langcodes);
    }

    return $entity;
  }
Exemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public function sendMailMessages(MessageInterface $message, AccountInterface $sender)
 {
     // Clone the sender, as we make changes to mail and name properties.
     $sender_cloned = clone $this->userStorage->load($sender->id());
     $params = array();
     $current_langcode = $this->languageManager->getCurrentLanguage()->getId();
     $recipient_langcode = $this->languageManager->getDefaultLanguage()->getId();
     $contact_form = $message->getContactForm();
     if ($sender_cloned->isAnonymous()) {
         // At this point, $sender contains an anonymous user, so we need to take
         // over the submitted form values.
         $sender_cloned->name = $message->getSenderName();
         $sender_cloned->mail = $message->getSenderMail();
         // For the email message, clarify that the sender name is not verified; it
         // could potentially clash with a username on this site.
         $sender_cloned->name = $this->t('@name (not verified)', array('@name' => $message->getSenderName()));
     }
     // Build email parameters.
     $params['contact_message'] = $message;
     $params['sender'] = $sender_cloned;
     if (!$message->isPersonal()) {
         // Send to the form recipient(s), using the site's default language.
         $params['contact_form'] = $contact_form;
         $to = implode(', ', $contact_form->getRecipients());
     } elseif ($recipient = $message->getPersonalRecipient()) {
         // Send to the user in the user's preferred language.
         $to = $recipient->getEmail();
         $recipient_langcode = $recipient->getPreferredLangcode();
         $params['recipient'] = $recipient;
     } else {
         throw new MailHandlerException('Unable to determine message recipient');
     }
     // Send email to the recipient(s).
     $key_prefix = $message->isPersonal() ? 'user' : 'page';
     $this->mailManager->mail('contact', $key_prefix . '_mail', $to, $recipient_langcode, $params, $sender_cloned->getEmail());
     // If requested, send a copy to the user, using the current language.
     if ($message->copySender()) {
         $this->mailManager->mail('contact', $key_prefix . '_copy', $sender_cloned->getEmail(), $current_langcode, $params, $sender_cloned->getEmail());
     }
     // If configured, send an auto-reply, using the current language.
     if (!$message->isPersonal() && $contact_form->getReply()) {
         // User contact forms do not support an auto-reply message, so this
         // message always originates from the site.
         if (!$sender_cloned->getEmail()) {
             $this->logger->error('Error sending auto-reply, missing sender e-mail address in %contact_form', ['%contact_form' => $contact_form->label()]);
         } else {
             $this->mailManager->mail('contact', 'page_autoreply', $sender_cloned->getEmail(), $current_langcode, $params);
         }
     }
     if (!$message->isPersonal()) {
         $this->logger->notice('%sender-name (@sender-from) sent an email regarding %contact_form.', array('%sender-name' => $sender_cloned->getUsername(), '@sender-from' => $sender_cloned->getEmail(), '%contact_form' => $contact_form->label()));
     } else {
         $this->logger->notice('%sender-name (@sender-from) sent %recipient-name an email.', array('%sender-name' => $sender_cloned->getUsername(), '@sender-from' => $sender_cloned->getEmail(), '%recipient-name' => $message->getPersonalRecipient()->getUsername()));
     }
 }
Exemplo n.º 3
0
 /**
  * {@inheritdoc}
  */
 protected function doCreate(array $values)
 {
     // Set default language to site default if not provided.
     $values += array('langcode' => $this->languageManager->getDefaultLanguage()->getId());
     $entity = new $this->entityClass($values, $this->entityTypeId);
     return $entity;
 }
Exemplo n.º 4
0
 /**
  * Page callback: Provides the media submission form.
  *
  * @param \Drupal\media_entity\MediaBundleInterface $media_bundle
  *   The media bundle object for the submitted media.
  *
  * @return array
  *   A media submission form.
  */
 public function add(MediaBundleInterface $media_bundle)
 {
     $user = \Drupal::currentUser();
     $bundle = $media_bundle->id();
     $langcode = $this->moduleHandler()->invoke('language', 'get_default_langcode', array('media', $bundle));
     $media = $this->entityManager()->getStorage('media')->create(array('uid' => $user->id(), 'bundle' => $bundle, 'langcode' => $langcode ? $langcode : $this->languageManager->getDefaultLanguage()->getId()));
     return $this->entityFormBuilder()->getForm($media);
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $languages = $this->languageManager->getLanguages();
     // Count repeated values for uniqueness check.
     $count = array_count_values($form_state->getValue('prefix'));
     $default_langcode = $this->config('language.negotiation')->get('selected_langcode');
     if ($default_langcode == LanguageInterface::LANGCODE_SITE_DEFAULT) {
         $default_langcode = $this->languageManager->getDefaultLanguage()->getId();
     }
     foreach ($languages as $langcode => $language) {
         $value = $form_state->getValue(array('prefix', $langcode));
         if ($value === '') {
             if (!($default_langcode == $langcode) && $form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_PATH_PREFIX) {
                 // Throw a form error if the prefix is blank for a non-default language,
                 // although it is required for selected negotiation type.
                 $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix may only be left blank for the <a href=":url">selected detection fallback language.</a>', [':url' => $this->getUrlGenerator()->generate('language.negotiation_selected')]));
             }
         } elseif (strpos($value, '/') !== FALSE) {
             // Throw a form error if the string contains a slash,
             // which would not work.
             $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix may not contain a slash.'));
         } elseif (isset($count[$value]) && $count[$value] > 1) {
             // Throw a form error if there are two languages with the same
             // domain/prefix.
             $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix for %language, %value, is not unique.', array('%language' => $language->getName(), '%value' => $value)));
         }
     }
     // Count repeated values for uniqueness check.
     $count = array_count_values($form_state->getValue('domain'));
     foreach ($languages as $langcode => $language) {
         $value = $form_state->getValue(array('domain', $langcode));
         if ($value === '') {
             if ($form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_DOMAIN) {
                 // Throw a form error if the domain is blank for a non-default language,
                 // although it is required for selected negotiation type.
                 $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain may not be left blank for %language.', array('%language' => $language->getName())));
             }
         } elseif (isset($count[$value]) && $count[$value] > 1) {
             // Throw a form error if there are two languages with the same
             // domain/domain.
             $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain for %language, %value, is not unique.', array('%language' => $language->getName(), '%value' => $value)));
         }
     }
     // Domain names should not contain protocol and/or ports.
     foreach ($languages as $langcode => $language) {
         $value = $form_state->getValue(array('domain', $langcode));
         if (!empty($value)) {
             // Ensure we have exactly one protocol when checking the hostname.
             $host = 'http://' . str_replace(array('http://', 'https://'), '', $value);
             if (parse_url($host, PHP_URL_HOST) != $value) {
                 $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain for %language may only contain the domain name, not a trailing slash, protocol and/or port.', ['%language' => $language->getName()]));
             }
         }
     }
     parent::validateForm($form, $form_state);
 }
Exemplo n.º 6
0
 /**
  * Determine language based on $results.
  */
 protected function getLangcode($results)
 {
     if (isset($results['add_language'])) {
         $langcodes = $results['add_language'];
         $langcode = $langcodes[array_rand($langcodes)];
     } else {
         $langcode = $this->languageManager->getDefaultLanguage()->getId();
     }
     return $langcode;
 }
Exemplo n.º 7
0
 /**
  * {@inheritdoc}
  */
 public function doCreate(array $values = array())
 {
     // Set default language to site default if not provided.
     $values += array($this->getEntityType()->getKey('langcode') => $this->languageManager->getDefaultLanguage()->getId());
     $entity = new $this->entityClass($values, $this->entityTypeId);
     // @todo This is handled by ContentEntityStorageBase, which assumes
     //   FieldableEntityInterface. The current approach in
     //   https://www.drupal.org/node/1867228 improves this but does not solve it
     //   completely.
     if ($entity instanceof FieldableEntityInterface) {
         foreach ($entity as $name => $field) {
             if (isset($values[$name])) {
                 $entity->{$name} = $values[$name];
             } elseif (!array_key_exists($name, $values)) {
                 $entity->get($name)->applyDefaultValue();
             }
             unset($values[$name]);
         }
     }
     return $entity;
 }
 function setUp()
 {
     parent::setUp();
     $this->languageManager = $this->container->get('language_manager');
     $this->installEntitySchema('entity_test_rev');
     $this->installEntitySchema('entity_test_mul');
     $this->installEntitySchema('entity_test_mulrev');
     $this->installConfig(array('language'));
     // Create the test field.
     entity_test_install();
     // Enable translations for the test entity type.
     $this->state->set('entity_test.translation', TRUE);
     // Create a translatable test field.
     $this->field_name = drupal_strtolower($this->randomMachineName() . '_field_name');
     // Create an untranslatable test field.
     $this->untranslatable_field_name = drupal_strtolower($this->randomMachineName() . '_field_name');
     // Create field instances in all entity variations.
     foreach (entity_test_entity_types() as $entity_type) {
         entity_create('field_storage_config', array('name' => $this->field_name, 'entity_type' => $entity_type, 'type' => 'text', 'cardinality' => 4))->save();
         entity_create('field_instance_config', array('field_name' => $this->field_name, 'entity_type' => $entity_type, 'bundle' => $entity_type, 'translatable' => TRUE))->save();
         $this->instance[$entity_type] = entity_load('field_instance_config', $entity_type . '.' . $entity_type . '.' . $this->field_name);
         entity_create('field_storage_config', array('name' => $this->untranslatable_field_name, 'entity_type' => $entity_type, 'type' => 'text', 'cardinality' => 4))->save();
         entity_create('field_instance_config', array('field_name' => $this->untranslatable_field_name, 'entity_type' => $entity_type, 'bundle' => $entity_type, 'translatable' => FALSE))->save();
     }
     // Create the default languages.
     $default_language = language_save($this->languageManager->getDefaultLanguage());
     $languages = $this->languageManager->getDefaultLockedLanguages($default_language->weight);
     foreach ($languages as $language) {
         language_save($language);
     }
     // Create test languages.
     $this->langcodes = array();
     for ($i = 0; $i < 3; ++$i) {
         $language = new Language(array('id' => 'l' . $i, 'name' => $this->randomString(), 'weight' => $i));
         $this->langcodes[$i] = $language->id;
         language_save($language);
     }
 }
Exemplo n.º 9
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $languages = $this->languageManager->getLanguages();
     $language_options = array();
     foreach ($languages as $langcode => $language) {
         if (locale_is_translatable($langcode)) {
             $language_options[$langcode] = $language->getName();
         }
     }
     $language_default = $this->languageManager->getDefaultLanguage();
     if (empty($language_options)) {
         $form['langcode'] = array('#type' => 'value', '#value' => LanguageInterface::LANGCODE_SYSTEM);
         $form['langcode_text'] = array('#type' => 'item', '#title' => $this->t('Language'), '#markup' => $this->t('No language available. The export will only contain source strings.'));
     } else {
         $form['langcode'] = array('#type' => 'select', '#title' => $this->t('Language'), '#options' => $language_options, '#default_value' => $language_default->getId(), '#empty_option' => $this->t('Source text only, no translations'), '#empty_value' => LanguageInterface::LANGCODE_SYSTEM);
         $form['content_options'] = array('#type' => 'details', '#title' => $this->t('Export options'), '#collapsed' => TRUE, '#tree' => TRUE, '#states' => array('invisible' => array(':input[name="langcode"]' => array('value' => LanguageInterface::LANGCODE_SYSTEM))));
         $form['content_options']['not_customized'] = array('#type' => 'checkbox', '#title' => $this->t('Include non-customized translations'), '#default_value' => TRUE);
         $form['content_options']['customized'] = array('#type' => 'checkbox', '#title' => $this->t('Include customized translations'), '#default_value' => TRUE);
         $form['content_options']['not_translated'] = array('#type' => 'checkbox', '#title' => $this->t('Include untranslated text'), '#default_value' => TRUE);
     }
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Export'));
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     parent::submitForm($form, $form_state);
     // Save the default language if changed.
     $new_id = $form_state->getValue('site_default_language');
     if ($new_id != $this->languageManager->getDefaultLanguage()->getId()) {
         $this->configFactory->getEditable('system.site')->set('default_langcode', $new_id)->save();
         $this->languageManager->reset();
     }
     if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
         $this->languageManager->updateLockedLanguageWeights();
     }
     drupal_set_message(t('Configuration saved.'));
     // Force the redirection to the page with the language we have just
     // selected as default.
     $form_state->setRedirectUrl($this->entities[$new_id]->urlInfo('collection', array('language' => $this->entities[$new_id])));
 }
Exemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $form_values = $form_state->getValues();
     // All system mails need to specify the module and template key (mirrored
     // from hook_mail()) that the message they want to send comes from.
     $module = 'email_example';
     $key = 'contact_message';
     // Specify 'to' and 'from' addresses.
     $to = $form_values['email'];
     $from = $this->config('system.site')->get('mail');
     // "params" loads in additional context for email content completion in
     // hook_mail(). In this case, we want to pass in the values the user entered
     // into the form, which include the message body in $form_values['message'].
     $params = $form_values;
     // The language of the e-mail. This will one of three values:
     // - $account->getPreferredLangcode(): Used for sending mail to a particular
     //   website user, so that the mail appears in their preferred language.
     // - \Drupal::currentUser()->getPreferredLangcode(): Used when sending a
     //   mail back to the user currently viewing the site. This will send it in
     //   the language they're currently using.
     // - \Drupal::languageManager()->getDefaultLanguage()->getId: Used when
     //   sending mail to a pre-existing, 'neutral' address, such as the system
     //   e-mail address, or when you're unsure of the language preferences of
     //   the intended recipient.
     //
     // Since in our case, we are sending a message to a random e-mail address
     // that is not necessarily tied to a user account, we will use the site's
     // default language.
     $language_code = $this->languageManager->getDefaultLanguage()->getId();
     // Whether or not to automatically send the mail when we call mail() on the
     // mail manager. This defaults to TRUE, and is normally what you want unless
     // you need to do additional processing before the mail manager sends the
     // message.
     $send_now = TRUE;
     // Send the mail, and check for success. Note that this does not guarantee
     // message delivery; only that there were no PHP-related issues encountered
     // while sending.
     $result = $this->mailManager->mail($module, $key, $to, $language_code, $params, $from, $send_now);
     if ($result['result'] == TRUE) {
         drupal_set_message(t('Your message has been sent.'));
     } else {
         drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
     }
 }
Exemplo n.º 12
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     $form = parent::form($form, $form_state);
     // We always show the internal path here.
     /** @var \Drupal\Core\Url $url */
     $url = $this->getEntity()->getUrlObject();
     if ($url->isExternal()) {
         $default_value = $url->toString();
     } elseif ($url->getRouteName() == '<front>') {
         // The default route for new entities is <front>, but we just want an
         // empty form field.
         $default_value = $this->getEntity()->isNew() ? '' : '<front>';
     } else {
         // @todo Url::getInternalPath() calls UrlGenerator::getPathFromRoute()
         // which need a replacement since it is deprecated.
         // https://www.drupal.org/node/2307061
         $default_value = $url->getInternalPath();
         // @todo Add a helper method to Url to render just the query string and
         // fragment. https://www.drupal.org/node/2305013
         $options = $url->getOptions();
         if (isset($options['query'])) {
             $default_value .= $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
         }
         if (isset($options['fragment']) && $options['fragment'] !== '') {
             $default_value .= '#' . $options['fragment'];
         }
     }
     $form['url'] = array('#title' => $this->t('Link path'), '#type' => 'textfield', '#description' => $this->t('The path for this menu link. This can be an internal Drupal path such as %add-node or an external URL such as %drupal. Enter %front to link to the front page.', array('%front' => '<front>', '%add-node' => 'node/add', '%drupal' => 'http://drupal.org')), '#default_value' => $default_value, '#required' => TRUE, '#weight' => -2);
     $language_configuration = $this->moduleHandler->invoke('language', 'get_default_configuration', array('menu_link_content', 'menu_link_content'));
     if ($this->entity->isNew()) {
         $default_language = isset($language_configuration['langcode']) ? $language_configuration['langcode'] : $this->languageManager->getDefaultLanguage()->getId();
     } else {
         $default_language = $this->entity->getUntranslated()->language()->getId();
     }
     $form['langcode'] = array('#title' => t('Language'), '#type' => 'language_select', '#default_value' => $default_language, '#languages' => Language::STATE_ALL, '#access' => !empty($language_configuration['language_show']));
     $form['enabled'] = array('#type' => 'checkbox', '#title' => $this->t('Enable menu link'), '#description' => $this->t('Menu links that are not enabled will not be listed in any menu.'), '#default_value' => !$this->entity->isHidden(), '#weight' => 0);
     $default = $this->entity->getMenuName() . ':' . $this->entity->getParentId();
     $form['menu_parent'] = $this->menuParentSelector->parentSelectElement($default, $this->entity->getPluginId());
     $form['menu_parent']['#weight'] = 10;
     $form['menu_parent']['#title'] = $this->t('Parent link');
     $form['menu_parent']['#description'] = $this->t('The maximum depth for a link and all its children is fixed. Some menu links may not be available as parents if selecting them would exceed this limit.');
     $form['menu_parent']['#attributes']['class'][] = 'menu-title-select';
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $form['kill'] = array('#type' => 'checkbox', '#title' => $this->t('<strong>Delete all products</strong> before generating new.'), '#default_value' => $this->getSetting('kill'));
     $form['num'] = array('#type' => 'number', '#title' => $this->t('How many products would you like to generate?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0);
     $form['title_length'] = array('#type' => 'number', '#title' => $this->t('Maximum number of characters in titles'), '#default_value' => $this->getSetting('title_length'), '#required' => TRUE, '#min' => 1, '#max' => 255);
     $form['num_var'] = array('#type' => 'number', '#title' => $this->t('How many variations of products would you like to generate?'), '#default_value' => $this->getSetting('num_var'), '#required' => TRUE, '#min' => 0);
     $form['title_var_length'] = array('#type' => 'number', '#title' => $this->t("Maximum number of characters in variation's titles"), '#default_value' => $this->getSetting('title_var_length'), '#required' => FALSE, '#min' => 1, '#max' => 255);
     $form['amount'] = array('#type' => 'fieldset', '#title' => t('Amount'));
     $form['amount']['price_min'] = array('#type' => 'number', '#title' => $this->t('Minimum of variations price to generate?'), '#default_value' => $this->getSetting('price_min'), '#min' => 0);
     $form['amount']['price_max'] = array('#type' => 'number', '#title' => $this->t('Maximum of variations price to generate?'), '#default_value' => $this->getSetting('price_max'), '#min' => 0);
     $currency_repository = new CurrencyRepository();
     $options = $currency_repository->getList();
     $form['amount']['currency'] = array('#type' => 'select', '#title' => $this->t('Set currency'), '#options' => $options);
     // We always need a language.
     $options = array();
     $languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
     foreach ($languages as $langcode => $language) {
         $options[$langcode] = $language->getName();
     }
     $form['add_language'] = array('#type' => 'select', '#title' => $this->t('Set language on products'), '#multiple' => TRUE, '#description' => $this->t('Requires locale.module'), '#options' => $options, '#default_value' => array($this->languageManager->getDefaultLanguage()->getId()));
     $form['#redirect'] = FALSE;
     return $form;
 }
Exemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function execute($entity = NULL)
 {
     if (empty($this->configuration['node'])) {
         $this->configuration['node'] = $entity;
     }
     $recipient = PlainTextOutput::renderFromHtml($this->token->replace($this->configuration['recipient'], $this->configuration));
     // If the recipient is a registered user with a language preference, use
     // the recipient's preferred language. Otherwise, use the system default
     // language.
     $recipient_accounts = $this->storage->loadByProperties(array('mail' => $recipient));
     $recipient_account = reset($recipient_accounts);
     if ($recipient_account) {
         $langcode = $recipient_account->getPreferredLangcode();
     } else {
         $langcode = $this->languageManager->getDefaultLanguage()->getId();
     }
     $params = array('context' => $this->configuration);
     if ($this->mailManager->mail('system', 'action_send_email', $recipient, $langcode, $params)) {
         $this->logger->notice('Sent email to %recipient', array('%recipient' => $recipient));
     } else {
         $this->logger->error('Unable to send email to %recipient', array('%recipient' => $recipient));
     }
 }
Exemplo n.º 15
0
 /**
  * {@inheritdoc}
  */
 public function save(array $form, array &$form_state)
 {
     $user = $this->currentUser();
     $language_interface = $this->languageManager->getCurrentLanguage();
     $message = $this->entity;
     $sender = clone $this->entityManager->getStorage('user')->load($user->id());
     if ($user->isAnonymous()) {
         // At this point, $sender contains an anonymous user, so we need to take
         // over the submitted form values.
         $sender->name = $message->getSenderName();
         $sender->mail = $message->getSenderMail();
         // Save the anonymous user information to a cookie for reuse.
         // @todo remove when https://www.drupal.org/node/749748 is in.
         user_cookie_save(array('name' => $message->getSenderName(), 'mail' => $message->getSenderMail()));
         // For the email message, clarify that the sender name is not verified; it
         // could potentially clash with a username on this site.
         $sender->name = $this->t('!name (not verified)', array('!name' => $message->getSenderName()));
     }
     // Build email parameters.
     $params['contact_message'] = $message;
     $params['sender'] = $sender;
     if (!$message->isPersonal()) {
         // Send to the category recipient(s), using the site's default language.
         $category = $message->getCategory();
         $params['contact_category'] = $category;
         $to = implode(', ', $category->recipients);
         $recipient_langcode = $this->languageManager->getDefaultLanguage()->getId();
     } elseif ($recipient = $message->getPersonalRecipient()) {
         // Send to the user in the user's preferred language.
         $to = $recipient->getEmail();
         $recipient_langcode = $recipient->getPreferredLangcode();
         $params['recipient'] = $recipient;
     } else {
         throw new \RuntimeException($this->t('Unable to determine message recipient.'));
     }
     // Send email to the recipient(s).
     $key_prefix = $message->isPersonal() ? 'user' : 'page';
     drupal_mail('contact', $key_prefix . '_mail', $to, $recipient_langcode, $params, $sender->getEmail());
     // If requested, send a copy to the user, using the current language.
     if ($message->copySender()) {
         drupal_mail('contact', $key_prefix . '_copy', $sender->getEmail(), $language_interface->id, $params, $sender->getEmail());
     }
     // If configured, send an auto-reply, using the current language.
     if (!$message->isPersonal() && $category->reply) {
         // User contact forms do not support an auto-reply message, so this
         // message always originates from the site.
         drupal_mail('contact', 'page_autoreply', $sender->getEmail(), $language_interface->id, $params);
     }
     $this->flood->register('contact', $this->config('contact.settings')->get('flood.interval'));
     if (!$message->isPersonal()) {
         watchdog('contact', '%sender-name (@sender-from) sent an email regarding %category.', array('%sender-name' => $sender->getUsername(), '@sender-from' => $sender->getEmail(), '%category' => $category->label()));
     } else {
         watchdog('contact', '%sender-name (@sender-from) sent %recipient-name an email.', array('%sender-name' => $sender->getUsername(), '@sender-from' => $sender->getEmail(), '%recipient-name' => $message->getPersonalRecipient()->getUsername()));
     }
     drupal_set_message($this->t('Your message has been sent.'));
     // To avoid false error messages caused by flood control, redirect away from
     // the contact form; either to the contacted user account or the front page.
     if ($message->isPersonal() && $user->hasPermission('access user profiles')) {
         $form_state['redirect_route'] = $message->getPersonalRecipient()->urlInfo();
     } else {
         $form_state['redirect_route']['route_name'] = '<front>';
     }
     // Save the message. In core this is a no-op but should contrib wish to
     // implement message storage, this will make the task of swapping in a real
     // storage controller straight-forward.
     $message->save();
 }
Exemplo n.º 16
0
 /**
  * Constructs a TranslationManager object.
  *
  * @param \Drupal\Core\Language\LanguageManagerInterface
  *   The language manager.
  */
 public function __construct(LanguageManagerInterface $language_manager)
 {
     $this->languageManager = $language_manager;
     $this->defaultLangcode = $language_manager->getDefaultLanguage()->getId();
 }
Exemplo n.º 17
0
 /**
  * Constructs a TranslationManager object.
  *
  * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
  *   The language manager.
  * @param \Drupal\Core\State\StateInterface $state
  *   (optional) The state service.
  */
 public function __construct(LanguageManagerInterface $language_manager, StateInterface $state = NULL)
 {
     $this->languageManager = $language_manager;
     $this->defaultLangcode = $language_manager->getDefaultLanguage()->getId();
     $this->state = $state;
 }