/**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $bdd_ivw_settings = $this->config('bdd_ivw.settings');
     $form['current_code'] = array('#markup' => 'Current Default Code: ' . $this->token->replace($bdd_ivw_settings->get('code_template'), array(), array('sanitize' => FALSE)));
     $form['settings'] = array('#type' => 'vertical_tabs', '#default_tab' => 'site_settings');
     $form['site_settings'] = array('#type' => 'details', '#title' => t('Site settings'), '#collapsible' => FALSE, '#collapsed' => FALSE, '#group' => 'ivw_settings');
     $form['default_values'] = array('#type' => 'details', '#title' => t('Default values'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#group' => 'ivw_settings');
     $form['site_settings']['site'] = array('#type' => 'textfield', '#title' => t('IVW Site name'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('site'), '#description' => t('Site name as given by IVW, this is used as default for the "st" parameter in the iam_data object'));
     $form['site_settings']['code_template'] = array('#type' => 'textfield', '#title' => t('Code template'), '#required' => TRUE, '#maxlength' => 256, '#size' => 128, '#default_value' => $bdd_ivw_settings->get('code_template'), '#description' => t('Code template, for creating the actual ivw code.'));
     $form['site_settings']['code_template_token_tree'] = array('#theme' => 'token_tree', '#token_types' => ['ivw']);
     $form['site_settings']['responsive'] = array('#type' => 'checkbox', '#title' => t('Site is responsive'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('responsive'), '#description' => t('Responsive sites must handle mobile code in javascript, this is activated here.'));
     $form['site_settings']['mobile_width'] = array('#type' => 'textfield', '#states' => array('invisible' => array(':input[name="ivw_responsive"]' => array('checked' => FALSE))), '#title' => t('Mobile width'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('mobile_width'), '#description' => t('On a responsive site, this value tells the javascript up to which screen width, the device should be treated as mobile.'));
     $form['default_values']['offering_default'] = array('#type' => 'textfield', '#title' => t('Fallback offering code'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('offering_default'), '#description' => t('A single ivw site can have multiple offerings, they can be differentiated by different numbers.'), '#min' => 1);
     $form['default_values']['offering_overridable'] = array('#type' => 'checkbox', '#title' => t('Offering code is overrideable'), '#default_value' => $bdd_ivw_settings->get('offering_overridable'));
     $form['default_values']['language_default'] = array('#type' => 'select', '#options' => array(1 => 'Deutsch', 2 => 'Andere Sprache, Inhalt prüfbar', 3 => 'Andere Sprache, Inhalt nicht prüfbar'), '#title' => t('Fallback language'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('language_default'));
     $form['default_values']['language_overridable'] = array('#type' => 'checkbox', '#title' => t('Language code is overrideable'), '#default_value' => $bdd_ivw_settings->get('language_overridable'));
     $form['default_values']['format_default'] = array('#type' => 'select', '#options' => array(1 => 'Bild/Text', 2 => 'Audio', 3 => 'Video', 4 => 'Andere dynamische Formate'), '#title' => t('Fallback format'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('format_default'));
     $form['default_values']['format_overridable'] = array('#type' => 'checkbox', '#title' => t('Format code is overrideable'), '#default_value' => $bdd_ivw_settings->get('format_overridable'));
     $form['default_values']['creator_default'] = array('#type' => 'select', '#options' => array(1 => 'Redaktion', 2 => 'User', 3 => 'Unbekannt'), '#title' => t('Fallback creator'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('creator_default'));
     $form['default_values']['creator_overridable'] = array('#type' => 'checkbox', '#title' => t('Creator code is overrideable'), '#default_value' => $bdd_ivw_settings->get('creator_overridable'));
     $form['default_values']['homepage_default'] = array('#type' => 'select', '#options' => array(1 => 'Homepage des Angebots', 2 => 'Keine Homepage', 3 => 'Hompage der Fremddomains bei Multi-Angeboten'), '#title' => t('Fallback homepage flag'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('homepage_default'));
     $form['default_values']['homepage_overridable'] = array('#type' => 'checkbox', '#title' => t('Homepage flag is overridable'), '#default_value' => $bdd_ivw_settings->get('homepage_overridable'));
     $form['default_values']['delivery_default'] = array('#type' => 'select', '#options' => array(1 => 'Online', 2 => 'Mobile', 3 => 'Connected TV'), '#title' => t('Fallback delivery'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('delivery_default'));
     $form['default_values']['delivery_overridable'] = array('#type' => 'checkbox', '#title' => t('Delivery flag is overridable'), '#default_value' => $bdd_ivw_settings->get('delivery_overridable'));
     $form['default_values']['app_default'] = array('#type' => 'select', '#options' => array(1 => 'App', 2 => 'Keine App'), '#title' => t('Fallback app flag'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('app_default'));
     $form['default_values']['app_overridable'] = array('#type' => 'checkbox', '#title' => t('App flag is overridable'), '#default_value' => $bdd_ivw_settings->get('app_overridable'));
     $form['default_values']['paid_default'] = array('#type' => 'select', '#options' => array(1 => 'Paid', 2 => 'Nicht zugeordnet'), '#title' => t('Fallback paid flag'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('paid_default'));
     $form['default_values']['paid_overridable'] = array('#type' => 'checkbox', '#title' => t('Paid flag is overridable'), '#default_value' => $bdd_ivw_settings->get('paid_overridable'));
     $form['default_values']['content_default'] = array('#type' => 'select', '#options' => array('01' => 'Nachrichten', '02' => 'Sport', '03' => 'Entertainment/Boulevard/Stars/Film/Musik', '04' => 'Fashion/Beauty', '05' => 'Familie/Kinder/Lebenshilfe', '06' => 'Liebe/Psychologie/Beziehungen', '07' => 'Fahrzeuge/Verkehr/Mobilität', '08' => 'Reise/Touristik', '09' => 'Computer', '10' => 'Consumer Electronics', '11' => 'Telekommunikation/Internetdienste', '12' => 'Spiele', '13' => 'Wohnen/Immobilien/Garten/Haushalt', '14' => 'Wirtschaft/Finanzen/Job/Karriere', '15' => 'Gesundheit', '16' => 'Essen/Trinken', '17' => 'Kunst/Kultur/Literatur', '18' => 'Erotik', '19' => 'Wissenschaft/Bildung/Natur/Umwelt', '20' => 'Angebotsinformation', '21' => 'Vermischtes (multithematisch)', '22' => 'Sonstiges (monothematisch)', '23' => 'Übersichtsseite zu Spiele', '24' => 'Casual Games', '25' => 'Core Games', '26' => 'Sonstiges (Bereich Spiele)', '27' => 'Social Networking - Privat', '28' => 'Social Networking - Business', '29' => 'Partnersuche/Dating', '30' => 'Newsletter', '31' => 'E-Mail/SMS/E-Cards', '32' => 'Messenger/Chat', '33' => 'Sonstiges (Bereich Networking/Kommunikation', '34' => 'Suchmaschinen', '35' => 'Verzeichnisse/Auskunftsdienste', '36' => 'Sonstiges (Bereich Suchmaschinen/Verzeichnisse)', '37' => 'Onlineshops/Shopping Mall/Auktionen/B2bMarktplätze', '38' => 'Immobilien Rubrikenmärkte/Kleinanzeigen', '39' => 'Jobs Rubrikenmärkte/Kleinanzeigen', '40' => 'Fahrzeuge Rubrikenmärkte/Kleinanzeigen', '41' => 'Sonstiges Rubrikenmärkte/Kleinanzeigen', '42' => 'Sonstiges (Bereich E-Commerce)'), '#title' => t('Fallback content category'), '#required' => TRUE, '#default_value' => $bdd_ivw_settings->get('content_default'));
     $form['default_values']['content_overridable'] = array('#type' => 'checkbox', '#title' => t('Content category is overridable'), '#default_value' => $bdd_ivw_settings->get('content_overridable'));
     return parent::buildForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  */
 public function execute($entity = NULL)
 {
     if (empty($this->configuration['node'])) {
         $this->configuration['node'] = $entity;
     }
     $message = $this->token->replace(Xss::filterAdmin($this->configuration['message']), $this->configuration);
     drupal_set_message($message);
 }
 /**
  * Wrapper for the Token module's string parsing.
  *
  * @param $string
  * @param $data
  * @param array $options
  *
  * @return mixed|string $string
  */
 public function replace($string, $data, $options = array())
 {
     $options['clear'] = TRUE;
     $replaced = $this->token->replace($string, $data, $options);
     // Ensure that there are no double-slash sequences due to empty token
     // values.
     $replaced = preg_replace('/(?<!:)\\/+\\//', '/', $replaced);
     return $replaced;
 }
Exemple #4
0
 /**
  * {@inheritdoc}
  */
 public function execute($entity = NULL)
 {
     if (empty($this->configuration['node'])) {
         $this->configuration['node'] = $entity;
     }
     $message = $this->token->replace($this->configuration['message'], $this->configuration);
     $build = ['#markup' => $message];
     // @todo Fix in https://www.drupal.org/node/2577827
     drupal_set_message($this->renderer->renderPlain($build));
 }
Exemple #5
0
 /**
  * Replace tokens with their values using the core token service.
  *
  * @param $string
  * @param $data
  * @param array $settings
  * @return mixed|string
  */
 private function coreReplace($string, $data, $settings = array())
 {
     // @TODO: Remove this temp code.
     // This is just here as a way to see all available tokens in debugger.
     $tokens = $this->coreToken->getInfo();
     $options = array('clear' => TRUE);
     // Replace tokens with core Token service.
     $replaced = $this->coreToken->replace($string, $data, $options);
     // Ensure that there are no double-slash sequences due to empty token values.
     $replaced = preg_replace('/(?<!:)\\/+\\//', '/', $replaced);
     return $replaced;
 }
 public function setUp()
 {
     $this->account = $this->prophesize(AccountInterface::class);
     $this->contextHandler = $this->prophesize(ContextHandlerInterface::class);
     $this->uuidGenerator = $this->prophesize(UuidInterface::class);
     $this->token = $this->prophesize(Token::class);
     $this->builderManager = $this->prophesize(DisplayBuilderManagerInterface::class);
     $this->layoutManager = $this->prophesize(LayoutPluginManagerInterface::class);
     $this->layout = $this->prophesize(LayoutInterface::class);
     $this->layoutManager->createInstance(Argument::type('string'), Argument::type('array'))->willReturn($this->layout->reveal());
     $this->variant = new PanelsDisplayVariant([], '', [], $this->contextHandler->reveal(), $this->account->reveal(), $this->uuidGenerator->reveal(), $this->token->reveal(), $this->builderManager->reveal(), $this->layoutManager->reveal());
 }
  /**
   * Controller callback for API overview.
   */
  public function summary() {
    $route_names = $this->config->get('routes');
    if (empty($route_names)) {
      $return = array(
        '#markup' => $this->t('No REST API endpoints configured or available.'),
      );
      if ($this->currentUser()->hasPermission('administer rest_api_doc')) {
        $return['#markup'] .= ' ' . $this->t('Please !link routes used for REST API documentation.', array(
          '!link' => $this->l($this->t('configure'), Url::fromRoute('rest_api_doc.settings')),
        ));;
      }
      return $return;
    }
    $overview = $this->token->replace(Xss::filterAdmin($this->config->get('overview')));
    $return['overview'] = array(
      '#markup' => $overview,
    );

    $links = array();
    $routes = $this->routeProvider->getRoutesByNames($route_names);
    foreach ($routes as $route_name => $route) {
      $path = $route->getPath();
      $links[$path] = $this->l($path, Url::fromRoute('rest_api_doc.documentation_detail', array(
        'path' => str_replace('/', '::', $path),
      )));
    }

    $return['toc'] = array(
      '#title' => $this->t('Available end-points'),
      '#theme' => 'item_list',
      '#items' => $links,
    );
    return $return;
  }
 /**
  * {@inheritdoc}
  */
 public function getChangesList(SubscriberInterface $subscriber, $changes = NULL, $langcode = NULL)
 {
     if (empty($langcode)) {
         $language = $this->languageManager->getCurrentLanguage();
         $langcode = $language->getId();
     }
     if (empty($changes)) {
         $changes = $subscriber->getChanges();
     }
     $changes_list = array();
     foreach ($changes as $newsletter_id => $action) {
         $subscribed = $subscriber->isSubscribed($newsletter_id);
         // Get text for each possible combination.
         if ($action == 'subscribe' && !$subscribed) {
             $line = $this->config->get('subscription.confirm_combined_line_subscribe_unsubscribed');
         } elseif ($action == 'subscribe' && $subscribed) {
             $line = $this->config->get('subscription.confirm_combined_line_subscribe_subscribed');
         } elseif ($action == 'unsubscribe' && !$subscribed) {
             $line = $this->config->get('subscription.confirm_combined_line_unsubscribe_unsubscribed');
         } elseif ($action == 'unsubscribe' && $subscribed) {
             $line = $this->config->get('subscription.confirm_combined_line_unsubscribe_subscribed');
         }
         $newsletter_context = array('simplenews_subscriber' => $subscriber, 'newsletter' => simplenews_newsletter_load($newsletter_id));
         $changes_list[$newsletter_id] = $this->token->replace($line, $newsletter_context, array('sanitize' => FALSE));
     }
     return $changes_list;
 }
Exemple #9
0
 /**
  * {@inheritdoc}
  */
 public function createAlias($module, $op, $source, $data, $type = NULL, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED)
 {
     $config = $this->configFactory->get('pathauto.settings');
     // Retrieve and apply the pattern for this content type.
     $pattern = $this->getPatternByEntity($module, $type, $langcode);
     // Allow other modules to alter the pattern.
     $context = array('module' => $module, 'op' => $op, 'source' => $source, 'data' => $data, 'type' => $type, 'language' => &$langcode);
     $this->moduleHandler->alter('pathauto_pattern', $pattern, $context);
     if (empty($pattern)) {
         // No pattern? Do nothing (otherwise we may blow away existing aliases...)
         return NULL;
     }
     // Special handling when updating an item which is already aliased.
     $existing_alias = NULL;
     if ($op == 'update' || $op == 'bulkupdate') {
         if ($existing_alias = $this->aliasStorageHelper->loadBySource($source, $langcode)) {
             switch ($config->get('update_action')) {
                 case PathautoManagerInterface::UPDATE_ACTION_NO_NEW:
                     // If an alias already exists,
                     // and the update action is set to do nothing,
                     // then gosh-darn it, do nothing.
                     return NULL;
             }
         }
     }
     // Replace any tokens in the pattern.
     // Uses callback option to clean replacements. No sanitization.
     $alias = $this->token->replace($pattern, $data, array('sanitize' => FALSE, 'clear' => TRUE, 'callback' => array($this, 'cleanTokenValues'), 'langcode' => $langcode, 'pathauto' => TRUE));
     // Check if the token replacement has not actually replaced any values. If
     // that is the case, then stop because we should not generate an alias.
     // @see token_scan()
     $pattern_tokens_removed = preg_replace('/\\[[^\\s\\]:]*:[^\\s\\]]*\\]/', '', $pattern);
     if ($alias === $pattern_tokens_removed) {
         return NULL;
     }
     $alias = $this->aliasCleaner->cleanAlias($alias);
     // Allow other modules to alter the alias.
     $context['source'] =& $source;
     $context['pattern'] = $pattern;
     $this->moduleHandler->alter('pathauto_alias', $alias, $context);
     // If we have arrived at an empty string, discontinue.
     if (!Unicode::strlen($alias)) {
         return NULL;
     }
     // If the alias already exists, generate a new, hopefully unique, variant.
     $original_alias = $alias;
     $this->aliasUniquifier->uniquify($alias, $source, $langcode);
     if ($original_alias != $alias) {
         // Alert the user why this happened.
         $this->messenger->addMessage($this->t('The automatically generated alias %original_alias conflicted with an existing alias. Alias changed to %alias.', array('%original_alias' => $original_alias, '%alias' => $alias)), $op);
     }
     // Return the generated alias if requested.
     if ($op == 'return') {
         return $alias;
     }
     // Build the new path alias array and send it off to be created.
     $path = array('source' => $source, 'alias' => $alias, 'language' => $langcode);
     return $this->aliasStorageHelper->save($path, $existing_alias, $op);
 }
Exemple #10
0
 /**
  * @covers ::replace
  * @dataProvider providerTestReplaceEscaping
  */
 public function testReplaceEscaping($string, array $tokens, $expected)
 {
     $this->moduleHandler->expects($this->any())->method('invokeAll')->willReturnCallback(function ($type, $args) {
         return $args[2]['tokens'];
     });
     $result = $this->token->replace($string, ['tokens' => $tokens]);
     $this->assertInternalType('string', $result);
     $this->assertEquals($expected, $result);
 }
 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state)
 {
     $message_text = $this->token->replace($this->getMessageText(), array('payment' => $this->getPayment()), array('clear' => TRUE));
     if ($this->moduleHandler->moduleExists('filter')) {
         $elements['message'] = array('#type' => 'processed_text', '#text' => $message_text, '#format' => $this->getMessageTextFormat());
     } else {
         $elements['message'] = array('#type' => 'markup', '#markup' => $message_text);
     }
     return $elements;
 }
Exemple #12
0
 /**
  * @covers ::getInfo
  */
 public function testGetInfo()
 {
     $token_info = array('types' => array('foo' => array('name' => $this->randomMachineName())));
     $language = $this->getMock('\\Drupal\\Core\\Language\\Language');
     $language->id = $this->randomMachineName();
     $this->languageManager->expects($this->once())->method('getCurrentLanguage')->with(LanguageInterface::TYPE_CONTENT)->will($this->returnValue($language));
     // The persistent cache must only be hit once, after which the info is
     // cached statically.
     $this->cache->expects($this->once())->method('get');
     $this->cache->expects($this->once())->method('set')->with('token_info:' . $language->id, $token_info);
     $this->moduleHandler->expects($this->once())->method('invokeAll')->with('token_info')->will($this->returnValue($token_info));
     $this->moduleHandler->expects($this->once())->method('alter')->with('token_info', $token_info);
     // Get the information for the first time. The cache should be checked, the
     // hooks invoked, and the info should be set to the cache should.
     $this->token->getInfo();
     // Get the information for the second time. The data must be returned from
     // the static cache, so the persistent cache must not be accessed and the
     // hooks must not be invoked.
     $this->token->getInfo();
 }
  /**
   * {@inheritdoc}
   */
  public function replace($original, array $entities) {
    // Whichever entity matches the token last wins.
    $replaced_string = $original;

    foreach ($entities as $entity_type => $entity_objects) {
      // Our rule is "last value wins." So use the last entities's values first.
      $seititne = array_reverse($entity_objects); // Get it?

      foreach ($seititne as $entity_id => $entity) {
        $replaced_string = $this->token->replace($replaced_string, [
          $entity_type => $entity,
        ]);
      }
    }

    // The entities might not have had values for all the tokens in the pattern.
    // Ensure that any remaining tokens are cleared from the string so they
    // don't get sent to the PDF.
    $clean_replaced_string = $this->token->replace($replaced_string, [], ['clear' => TRUE]);
    return $clean_replaced_string;
  }
 /**
  * {@inheritdoc}
  */
 public function process($value, RulesStateInterface $rules_state)
 {
     $replacements = [];
     // The Token API requires this metadata object, but it is useless for us
     // here so we just always pass the same instance and ignore it.
     $bubbleable_metdata = new BubbleableMetadata();
     // We only use the token service to scan for tokens in the text. The
     // replacements are done by using the data selector logic.
     foreach ($this->tokenService->scan($value) as $var_name => $tokens) {
         foreach ($tokens as $token) {
             // Remove the opening and closing bracket to form a data selector.
             $data_selector = substr($token, 1, -1);
             try {
                 $replacement_data = $rules_state->applyDataSelector($data_selector);
                 $replacements[$token] = $replacement_data->getString();
             } catch (RulesEvaluationException $exception) {
                 // Data selector is invalid, so try to resolve the token with the
                 // token service.
                 if ($rules_state->hasVariable($var_name)) {
                     $variable = $rules_state->getVariable($var_name);
                     $token_type = $variable->getContextDefinition()->getDataType();
                     // The Token system does not know about "enity:" data type prefixes,
                     // so we have to remove them.
                     $token_type = str_replace('entity:', '', $token_type);
                     $data = [$token_type => $variable->getContextValue()];
                     $replacements += $this->tokenService->generate($token_type, $tokens, $data, ['sanitize' => FALSE], $bubbleable_metdata);
                 } else {
                     $replacements += $this->tokenService->generate($var_name, $tokens, [], ['sanitize' => FALSE], $bubbleable_metdata);
                 }
                 // Remove tokens if no replacement value is found.
                 $replacements += array_fill_keys($tokens, '');
             }
         }
     }
     // Apply the replacements now.
     $tokens = array_keys($replacements);
     $values = array_values($replacements);
     return str_replace($tokens, $values, $value);
 }
Exemple #15
0
 /**
  * {@inheritdoc}
  */
 public function execute($entity = NULL)
 {
     if (empty($this->configuration['node'])) {
         $this->configuration['node'] = $entity;
     }
     $recipient = $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 = language_default()->id;
     }
     $params = array('context' => $this->configuration);
     if (drupal_mail('system', 'action_send_email', $recipient, $langcode, $params)) {
         watchdog('action', 'Sent email to %recipient', array('%recipient' => $recipient));
     } else {
         watchdog('error', 'Unable to send email to %recipient', array('%recipient' => $recipient));
     }
 }
 /**
  * {@inheritdoc}
  */
 function buildUnsubscribeMail(&$message, $params)
 {
     $context = $params['context'];
     // Use formatted from address "name" <mail_address>
     $message['headers']['From'] = $params['from']['formatted'];
     $message['subject'] = $this->config->get('subscription.confirm_subscribe_subject');
     $message['subject'] = $this->token->replace($message['subject'], $context, array('sanitize' => FALSE));
     if ($context['simplenews_subscriber']->isSubscribed($context['newsletter']->id())) {
         $body = $this->config->get('subscription.confirm_unsubscribe_subscribed');
         $message['body'][] = $this->token->replace($body, $context, array('sanitize' => FALSE));
     } else {
         $body = $this->config->get('subscription.confirm_unsubscribe_unsubscribed');
         $message['body'][] = $this->token->replace($body, $context, array('sanitize' => FALSE));
     }
 }
  /**
   * @param string $destination_path
   * @param array $token_objects
   * @param string $scheme
   * @return string
   */
  protected function processDestinationPath($destination_path, $token_objects, $scheme = 'public') {
    $orig_path = $destination_path;
    $destination_path = trim($orig_path);
    // Replace any applicable tokens
    $types = [];
    if (isset($token_objects['node'])) {
      $types[] = 'node';
    }
    elseif (isset($token_objects['webform'])) {
      $types[] = 'webform';
    }
    // TODO: Do this kind of replacement with a common service instead, because I'm doing the same thing in like 3 places now.
    foreach ($types as $type) {
      $destination_path = $this->token->replace($destination_path, [$type => $token_objects[$type]], ['clear' => TRUE]);
    }

    // Slap on the files directory in front and return it
    $destination_path = FillPdf::buildFileUri($scheme, $destination_path);
    return $destination_path;
  }
 /**
  * {@inheritdoc}
  */
 public function saveFile($uri, $destination, $extensions, AccountProxyInterface $user, $validators = [])
 {
     // Create the file entity.
     $file = $this->fileEntityFromUri($uri, $user);
     // Replace tokens. As the tokens might contain HTML we convert it to plain
     // text.
     $destination = PlainTextOutput::renderFromHtml($this->token->replace($destination));
     // Handle potentialy dangerous extensions.
     $renamed = $this->renameExecutableExtensions($file);
     // The .txt extension may not be in the allowed list of extensions. We have
     // to add it here or else the file upload will fail.
     if ($renamed && !empty($extensions)) {
         $extensions .= ' txt';
         drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', ['%filename' => $file->getFilename()]));
     }
     // Validate the file.
     $errors = $this->validateFile($file, $extensions, $validators);
     if (!empty($errors)) {
         $message = ['error' => ['#markup' => t('The specified file %name could not be uploaded.', ['%name' => $file->getFilename()])], 'item_list' => ['#theme' => 'item_list', '#items' => $errors]];
         drupal_set_message($this->renderer->renderPlain($message), 'error');
         return FALSE;
     }
     // Prepare destination.
     if (!$this->prepareDestination($file, $destination)) {
         drupal_set_message(t('The file could not be uploaded because the destination %destination is invalid.', ['%destination' => $destination]), 'error');
         return FALSE;
     }
     // Move uploaded files from PHP's upload_tmp_dir to destination.
     $move_result = file_unmanaged_move($uri, $file->getFileUri());
     if (!$move_result) {
         drupal_set_message(t('File upload error. Could not move uploaded file.'), 'error');
         $this->logger->notice('Upload error. Could not move uploaded file %file to destination %destination.', ['%file' => $file->getFilename(), '%destination' => $file->getFileUri()]);
         return FALSE;
     }
     // Set the permissions on the new file.
     $this->fileSystem->chmod($file->getFileUri());
     // If we made it this far it's safe to record this file in the database.
     $file->save();
     return $file;
 }
Exemple #19
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));
     }
 }
Exemple #20
0
 /**
  * Provides a token replacement with a node as well as the current user.
  *
  * This controller is for testing the token service's fallback behavior of
  * applying collected metadata to the currently active render context when an
  * explicit bubbleable metadata object isn't passed in.
  *
  * @param \Drupal\node\NodeInterface $node
  *   The node.
  *
  * @return array
  *   The render array.
  */
 public function tokenReplaceWithoutPassedBubbleableMetadata(NodeInterface $node)
 {
     $build['#markup'] = $this->token->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], []);
     return $build;
 }
Exemple #21
0
 /**
  * {@inheritdoc}
  */
 public function getOutput()
 {
     $output = '<h2 class="tour-tip-label" id="tour-tip-' . $this->getAriaId() . '-label">' . Html::escape($this->getLabel()) . '</h2>';
     $output .= '<p class="tour-tip-body" id="tour-tip-' . $this->getAriaId() . '-contents">' . $this->token->replace($this->getBody()) . '</p>';
     return array('#markup' => $output);
 }
Exemple #22
0
 /**
  * {@inheritdoc}
  */
 public function resetInfo()
 {
     parent::resetInfo();
     $this->globalTokenTypes = NULL;
 }
 protected function getCp()
 {
     $settings = $this->configFactory->get('ivw_integration.settings');
     $code_template = $settings->get('code_template');
     return $this->token->replace($code_template, array(), array('sanitize' => FALSE));
 }
Exemple #24
0
 /**
  * @covers ::resetInfo
  */
 public function testResetInfo()
 {
     $this->cacheTagsInvalidator->expects($this->once())->method('invalidateTags')->with(['token_info']);
     $this->token->resetInfo();
 }
Exemple #25
0
 /**
  * Replaces all tokens in a given string with appropriate values.
  *
  * @param string $text
  *   An HTML string containing replaceable tokens.
  *
  * @return string
  *   The entered HTML text with tokens replaced.
  */
 public function tokenReplaceFilter($text)
 {
     return $this->token->replace($text);
 }
 /**
  * {@inheritdoc}
  */
 public function createEntityAlias(EntityInterface $entity, $op)
 {
     // Retrieve and apply the pattern for this content type.
     $pattern = $this->getPatternByEntity($entity);
     if (empty($pattern)) {
         // No pattern? Do nothing (otherwise we may blow away existing aliases...)
         return NULL;
     }
     $source = '/' . $entity->toUrl()->getInternalPath();
     $config = $this->configFactory->get('pathauto.settings');
     $langcode = $entity->language()->getId();
     // Core does not handle aliases with language Not Applicable.
     if ($langcode == LanguageInterface::LANGCODE_NOT_APPLICABLE) {
         $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
     }
     // Build token data.
     $data = [$this->tokenEntityMapper->getTokenTypeForEntityType($entity->getEntityTypeId()) => $entity];
     // Allow other modules to alter the pattern.
     $context = array('module' => $entity->getEntityType()->getProvider(), 'op' => $op, 'source' => $source, 'data' => $data, 'bundle' => $entity->bundle(), 'language' => &$langcode);
     // @todo Is still hook still useful?
     $this->moduleHandler->alter('pathauto_pattern', $pattern, $context);
     // Special handling when updating an item which is already aliased.
     $existing_alias = NULL;
     if ($op == 'update' || $op == 'bulkupdate') {
         if ($existing_alias = $this->aliasStorageHelper->loadBySource($source, $langcode)) {
             switch ($config->get('update_action')) {
                 case PathautoGeneratorInterface::UPDATE_ACTION_NO_NEW:
                     // If an alias already exists,
                     // and the update action is set to do nothing,
                     // then gosh-darn it, do nothing.
                     return NULL;
             }
         }
     }
     // Replace any tokens in the pattern.
     // Uses callback option to clean replacements. No sanitization.
     // Pass empty BubbleableMetadata object to explicitly ignore cacheablity,
     // as the result is never rendered.
     $alias = $this->token->replace($pattern->getPattern(), $data, array('clear' => TRUE, 'callback' => array($this->aliasCleaner, 'cleanTokenValues'), 'langcode' => $langcode, 'pathauto' => TRUE), new BubbleableMetadata());
     // Check if the token replacement has not actually replaced any values. If
     // that is the case, then stop because we should not generate an alias.
     // @see token_scan()
     $pattern_tokens_removed = preg_replace('/\\[[^\\s\\]:]*:[^\\s\\]]*\\]/', '', $pattern->getPattern());
     if ($alias === $pattern_tokens_removed) {
         return NULL;
     }
     $alias = $this->aliasCleaner->cleanAlias($alias);
     // Allow other modules to alter the alias.
     $context['source'] =& $source;
     $context['pattern'] = $pattern;
     $this->moduleHandler->alter('pathauto_alias', $alias, $context);
     // If we have arrived at an empty string, discontinue.
     if (!Unicode::strlen($alias)) {
         return NULL;
     }
     // If the alias already exists, generate a new, hopefully unique, variant.
     $original_alias = $alias;
     $this->aliasUniquifier->uniquify($alias, $source, $langcode);
     if ($original_alias != $alias) {
         // Alert the user why this happened.
         $this->messenger->addMessage($this->t('The automatically generated alias %original_alias conflicted with an existing alias. Alias changed to %alias.', array('%original_alias' => $original_alias, '%alias' => $alias)), $op);
     }
     // Return the generated alias if requested.
     if ($op == 'return') {
         return $alias;
     }
     // Build the new path alias array and send it off to be created.
     $path = array('source' => $source, 'alias' => $alias, 'language' => $langcode);
     return $this->aliasStorageHelper->save($path, $existing_alias, $op);
 }
 /**
  * Renders the page title and replaces tokens.
  *
  * @param string $page_title
  *   The page title that should be rendered.
  *
  * @return string
  *   The page title after replacing any tokens.
  */
 protected function renderPageTitle($page_title)
 {
     $data = $this->getContextAsTokenData();
     return $this->token->replace($page_title, $data);
 }
 /**
  * Implements \Drupal\tour\TipPluginInterface::getOutput().
  */
 public function getOutput()
 {
     $output = '<h2 class="tour-tip-label" id="tour-tip-' . $this->getAriaId() . '-label">' . String::checkPlain($this->getLabel()) . '</h2>';
     $output .= '<p class="tour-tip-body" id="tour-tip-' . $this->getAriaId() . '-contents">' . Xss::filterAdmin($this->token->replace($this->getBody())) . '</p>';
     return array('#markup' => $output);
 }