filterAdmin example



  /** * Render all items in this field together. * * When using advanced render, each possible item in the list is rendered * individually. Then the items are all pasted together. */
  public function renderItems($items) {
    if (!empty($items)) {
      if ($this->options['multi_type'] == 'separator' || !$this->options['group_rows']) {
        $separator = $this->options['multi_type'] == 'separator' ? Xss::filterAdmin($this->options['separator']) : '';
        $build = [
          '#type' => 'inline_template',
          '#template' => '{{ items | safe_join(separator) }}',
          '#context' => ['separator' => $separator, 'items' => $items],
        ];
      }
      else {
        $build = [
          '#theme' => 'item_list',
          '#items' => $items,
          '#title' => NULL,
          
$view->displayHandlers->get('page_1')->overrideOption('path', $path);
    $view->setDisplay('page_1');
    $this->assertEquals($path$view->getPath());
    // Test the override_path property override.     $override_path = $this->randomMachineName();
    $view->override_path = $override_path;
    $this->assertEquals($override_path$view->getPath());

    // Test the title methods.     $title = $this->randomString();
    $view->setTitle($title);
    $this->assertEquals(Xss::filterAdmin($title)$view->getTitle());
  }

  /** * Tests the deconstructor to be sure that necessary objects are removed. */
  public function testDestroy() {
    $view = Views::getView('test_destroy');

    $view->preview();
    $view->destroy();

    
/** * {@inheritdoc} */
  public function render(ResultRow $values) {
    $value = $this->getValue($values);
    if (!empty($this->options['not'])) {
      $value = !$value;
    }

    if ($this->options['type'] == 'custom') {
      $custom_value = $value ? $this->options['type_custom_true'] : $this->options['type_custom_false'];
      return ViewsRenderPipelineMarkup::create(UtilityXss::filterAdmin($custom_value));
    }
    elseif (isset($this->formats[$this->options['type']])) {
      return $value ? $this->formats[$this->options['type']][0] : $this->formats[$this->options['type']][1];
    }
    else {
      return $value ? $this->formats['yes-no'][0] : $this->formats['yes-no'][1];
    }
  }

}
if (!empty($alter['strip_tags'])) {
      $value = strip_tags($value$alter['preserve_tags']);
    }

    $more_link = '';
    if (!empty($alter['trim']) && !empty($alter['max_length'])) {
      $length = strlen($value);
      $value = $this->renderTrimText($alter$value);
      if ($this->options['alter']['more_link'] && strlen($value) < $length) {
        $tokens = $this->getRenderTokens($alter);
        $more_link_text = $this->options['alter']['more_link_text'] ? $this->options['alter']['more_link_text'] : $this->t('more');
        $more_link_text = strtr(Xss::filterAdmin($more_link_text)$tokens);
        $more_link_path = $this->options['alter']['more_link_path'];
        $more_link_path = strip_tags(Html::decodeEntities($this->viewsTokenReplace($more_link_path$tokens)));

        // Make sure that paths which were run through URL generation work as         // well.         $base_path = base_path();
        // Checks whether the path starts with the base_path.         if (str_starts_with($more_link_path$base_path)) {
          $more_link_path = mb_substr($more_link_pathmb_strlen($base_path));
        }

        
/** * Tests the generation of all system site information tokens. */
  public function testSystemSiteTokenReplacement() {
    $url_options = [
      'absolute' => TRUE,
      'language' => $this->interfaceLanguage,
    ];

    $slogan = '<blink>Slogan</blink>';
    $safe_slogan = Xss::filterAdmin($slogan);

    // Set a few site variables.     $config = $this->config('system.site');
    $config
      ->set('name', '<strong>Drupal<strong>')
      ->set('slogan', $slogan)
      ->set('mail', 'simpletest@example.com')
      ->save();

    // Generate and test tokens.     $tests = [];
    
// Row tokens might be empty, for example for node row style.       $tokens = $this->rowTokens[$row_index] ?? [];
      if (!empty($this->view->build_info['substitutions'])) {
        $tokens += $this->view->build_info['substitutions'];
      }

      $value = $this->viewsTokenReplace($value$tokens);
    }
    else {
      // ::viewsTokenReplace() will run Xss::filterAdmin on the       // resulting string. We do the same here for consistency.       $value = Xss::filterAdmin($value);
    }
    return $value;
  }

  /** * Determines if the style plugin is rendered even if the view is empty. */
  public function evenEmpty() {
    return !empty($this->definition['even empty']);
  }

  

  public function sanitizeValue($value$type = NULL) {
    if ($value === NULL) {
      return '';
    }
    switch ($type) {
      case 'xss':
        $value = Xss::filter($value);
        break;

      case 'xss_admin':
        $value = Xss::filterAdmin($value);
        break;

      case 'url':
        $value = Html::escape(UrlHelper::stripDangerousProtocols($value));
        break;

      default:
        $value = Html::escape($value);
        break;
    }
    return ViewsRenderPipelineMarkup::create($value);
  }

  public function formatMessage($row) {
    // Check for required properties.     if (isset($row->message, $row->variables)) {
      $variables = @unserialize($row->variables);
      // Messages without variables or user specified text.       if ($variables === NULL) {
        $message = Xss::filterAdmin($row->message);
      }
      elseif (!is_array($variables)) {
        $message = $this->t('Log data is corrupted and cannot be unserialized: @message', ['@message' => Xss::filterAdmin($row->message)]);
      }
      // Message to translate with injected variables.       else {
        // Ensure backtrace strings are properly formatted.         if (isset($variables['@backtrace_string'])) {
          $variables['@backtrace_string'] = new FormattableMarkup(
            '<pre class="backtrace">@backtrace_string</pre>', $variables
          );
        }
'<time datetime="1978-11-19T05:00:00Z">#DBD</time>',
        'Time with datetime attribute',
        ['time'],
      ],
    ];
  }

  /** * Checks that \Drupal\Component\Utility\Xss::filterAdmin() correctly strips unallowed tags. */
  public function testFilterXSSAdmin() {
    $value = Xss::filterAdmin('<style /><iframe /><frame /><frameset /><meta /><link /><embed /><applet /><param /><layer />');
    $this->assertEquals('', $value, 'Admin HTML filter -- should never allow some tags.');
  }

  /** * Tests the loose, admin HTML filter. * * @param string $value * The value to filter. * @param string $expected * The expected result. * @param string $message * The assertion message to display upon failure. * * @dataProvider providerTestFilterXssAdminNotNormalized */

    // Construct all other elements.     else {
      $open_tag .= '>';
      if ($element['#value'] === NULL) {
        $element['#markup'] = '';
      }
      elseif ($element['#value'] instanceof MarkupInterface) {
        $element['#markup'] = $element['#value'];
      }
      else {
        $element['#markup'] = Markup::create(Xss::filterAdmin($element['#value']));
      }
    }
    $prefix = isset($element['#prefix']) ? $element['#prefix'] . $open_tag : $open_tag;
    $suffix = isset($element['#suffix']) ? $close_tag . $element['#suffix'] : $close_tag;
    if (!empty($element['#noscript'])) {
      $prefix = '<noscript>' . $prefix;
      $suffix .= '</noscript>';
    }
    $element['#prefix'] = Markup::create($prefix);
    $element['#suffix'] = Markup::create($suffix);
    return $element;
  }

  protected function viewsTokenReplace($text$tokens) {
    if (!strlen($text)) {
      // No need to run filterAdmin on an empty string.       return '';
    }
    if (empty($tokens)) {
      return Xss::filterAdmin($text);
    }

    $twig_tokens = [];
    foreach ($tokens as $token => $replacement) {
      // Twig wants a token replacement array stripped of curly-brackets.       // Some Views tokens come with curly-braces, others do not.       // @todo: https://www.drupal.org/node/2544392       if (str_contains($token, '{{')) {
        // Twig wants a token replacement array stripped of curly-brackets.         $token = trim(str_replace(['{{', '}}'], '', $token));
      }

      

  protected function xssFilterAdminIfUnsafe($string) {
    if (!($string instanceof MarkupInterface)) {
      $string = Xss::filterAdmin($string);
    }
    return Markup::create($string);
  }

  /** * Escapes #plain_text or filters #markup as required. * * Drupal uses Twig's auto-escape feature to improve security. This feature * automatically escapes any HTML that is not known to be safe. Due to this * the render system needs to ensure that all markup it generates is marked * safe so that Twig does not do any additional escaping. * * By default all #markup is filtered to protect against XSS using the admin * tag list. Render arrays can alter the list of tags allowed by the filter * using the #allowed_tags property. This value should be an array of tags * that Xss::filter() would accept. Render arrays can escape text instead * of XSS filtering by setting the #plain_text property instead of #markup. If * #plain_text is used #allowed_tags is ignored. * * @param array $elements * A render array with #markup set. * * @return \Drupal\Component\Render\MarkupInterface|string * The escaped markup wrapped in a Markup object. If $elements['#markup'] * is an instance of \Drupal\Component\Render\MarkupInterface, it won't be * escaped or filtered again. * * @see \Drupal\Component\Utility\Html::escape() * @see \Drupal\Component\Utility\Xss::filter() * @see \Drupal\Component\Utility\Xss::filterAdmin() */
    // entity_reference_plugin_display.     $id_field_alias = $this->view->storage->get('base_field');

    // @todo We don't display grouping info for now. Could be useful for select     // widget, though.     $results = [];
    foreach ($sets as $records) {
      foreach ($records as $values) {
        $results[$values->{$id_field_alias}] = $this->view->rowPlugin->render($values);
        // Sanitize HTML, remove line breaks and extra whitespace.         $results[$values->{$id_field_alias}]['#post_render'][] = function D$html, array $elements) {
          return Xss::filterAdmin(preg_replace('/\s\s+/', ' ', str_replace("\n", '', $html)));
        };
      }
    }
    return $results;
  }

  /** * {@inheritdoc} */
  public function evenEmpty() {
    return TRUE;
  }
public static function trustedCallbacks() {
    $callbacks = parent::trustedCallbacks();
    $callbacks[] = 'preRenderCustomForm';
    return $callbacks;
  }

  /** * {@inheritdoc} */
  public function render(ResultRow $values) {
    // Return the text, so the code never thinks the value is empty.     return ViewsRenderPipelineMarkup::create(Xss::filterAdmin($this->options['alter']['text']));
  }

  /** * Prerender function to move the textarea to the top of a form. * * @param array $form * The form build array. * * @return array * The modified form build array. */
  
$message_vars = $entry['variables'];
      unset($message_vars['link']);
      $this->assertEquals(new FormattableMarkup($entry['message']$message_vars)$view->style_plugin->getField($index, 'message'));
      $link_field = $view->style_plugin->getField($index, 'link');
      // The 3rd entry contains some unsafe markup that needs to get filtered.       if ($index == 2) {
        // Make sure that unsafe link differs from the rendered link, so we know         // that some filtering actually happened. We use assertNotSame and cast         // values to strings since HTML tags are significant.         $this->assertNotSame((string) $entry['variables']['link'](string) $link_field);
      }
      $this->assertSame(Xss::filterAdmin($entry['variables']['link'])(string) $link_field);
    }

    // Disable replacing variables and check that the tokens aren't replaced.     $view->destroy();
    $view->storage->invalidateCaches();
    $view->initHandlers();
    $this->executeView($view);
    $view->initStyle();
    $view->field['message']->options['replace_variables'] = FALSE;
    foreach ($entries as $index => $entry) {
      $this->assertEquals($entry['message']$view->style_plugin->getField($index, 'message'));
    }
Home | Imprint | This part of the site doesn't use cookies.