本文整理汇总了PHP中Drupal\Component\Utility\SafeMarkup::set方法的典型用法代码示例。如果您正苦于以下问题:PHP SafeMarkup::set方法的具体用法?PHP SafeMarkup::set怎么用?PHP SafeMarkup::set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Component\Utility\SafeMarkup
的用法示例。
在下文中一共展示了SafeMarkup::set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL)
{
$current_path = $request->attributes->get('_system_path');
$current_url = Url::createFromRequest($request);
$devel_config = $this->config('devel.settings');
$form['queries'] = array('#type' => 'fieldset', '#title' => t('Query log'));
$description = t('Display a log of the database queries needed to generate the current page, and the execution time for each. Also, queries which are repeated during a single page view are summed in the # column, and printed in red since they are candidates for caching.');
$form['queries']['query_display'] = array('#type' => 'checkbox', '#title' => t('Display query log'), '#default_value' => $devel_config->get('query_display'), '#description' => $description);
$form['queries']['settings'] = array('#type' => 'container', '#states' => array('invisible' => array('input[name="query_display"]' => array('checked' => FALSE))));
$form['queries']['settings']['query_sort'] = array('#type' => 'radios', '#title' => t('Sort query log'), '#default_value' => $devel_config->get('query_sort'), '#options' => array(t('by source'), t('by duration')), '#description' => t('The query table can be sorted in the order that the queries were executed or by descending duration.'));
$form['queries']['settings']['execution'] = array('#type' => 'textfield', '#title' => t('Slow query highlighting'), '#default_value' => $devel_config->get('execution'), '#size' => 4, '#maxlength' => 4, '#description' => t('Enter an integer in milliseconds. Any query which takes longer than this many milliseconds will be highlighted in the query log. This indicates a possibly inefficient query, or a candidate for caching.'));
$form['api_url'] = array('#type' => 'textfield', '#title' => t('API Site'), '#default_value' => $devel_config->get('api_url'), '#description' => t('The base URL for your developer documentation links. You might change this if you run <a href="!url">api.module</a> locally.', array('!url' => Url::fromUri('http://drupal.org/project/api')->toString())));
$form['timer'] = array('#type' => 'checkbox', '#title' => t('Display page timer'), '#default_value' => $devel_config->get('timer'), '#description' => t('Display page execution time in the query log box.'));
$form['memory'] = array('#type' => 'checkbox', '#title' => t('Display memory usage'), '#default_value' => $devel_config->get('memory'), '#description' => t('Display how much memory is used to generate the current page. This will show memory usage when devel_init() is called and when devel_exit() is called.'));
$form['redirect_page'] = array('#type' => 'checkbox', '#title' => t('Display redirection page'), '#default_value' => $devel_config->get('redirect_page'), '#description' => t('When a module executes drupal_goto(), the query log and other developer information is lost. Enabling this setting presents an intermediate page to developers so that the log can be examined before continuing to the destination page.'));
$form['page_alter'] = array('#type' => 'checkbox', '#title' => t('Display $page array'), '#default_value' => $devel_config->get('page_alter'), '#description' => t('Display $page array from <a href="http://api.drupal.org/api/function/hook_page_alter/7">hook_page_alter()</a> in the messages area of each page.'));
$form['raw_names'] = array('#type' => 'checkbox', '#title' => t('Display machine names of permissions and modules'), '#default_value' => $devel_config->get('raw_names'), '#description' => t('Display the language-independent machine names of the permissions in mouse-over hints on the !Permissions page and the module base file names on the @Permissions and !Modules pages.', array('!Permissions' => $this->l(t('Permissions'), Url::fromRoute('user.admin_permissions')), '@Permissions' => t('Permissions'), '!Modules' => $this->l(t('Modules'), Url::fromRoute('system.modules_list')))));
$error_handlers = devel_get_handlers();
$form['error_handlers'] = array('#type' => 'select', '#title' => t('Error handlers'), '#options' => array(DEVEL_ERROR_HANDLER_NONE => t('None'), DEVEL_ERROR_HANDLER_STANDARD => t('Standard Drupal'), DEVEL_ERROR_HANDLER_BACKTRACE_DPM => t('Krumo backtrace in the message area'), DEVEL_ERROR_HANDLER_BACKTRACE_KRUMO => t('Krumo backtrace above the rendered page')), '#multiple' => TRUE, '#default_value' => empty($error_handlers) ? DEVEL_ERROR_HANDLER_NONE : $error_handlers, '#description' => SafeMarkup::set(t('Select the error handler(s) to use, in case you <a href="@choose">choose to show errors on screen</a>.', array('@choose' => $this->url('system.logging_settings'))) . '<ul>' . '<li>' . t('<em>None</em> is a good option when stepping through the site in your debugger.') . '</li>' . '<li>' . t('<em>Standard Drupal</em> does not display all the information that is often needed to resolve an issue.') . '</li>' . '<li>' . t('<em>Krumo backtrace</em> displays nice debug information when any type of error is noticed, but only to users with the %perm permission.', array('%perm' => t('Access developer information'))) . '</li></ul>' . t('Depending on the situation, the theme, the size of the call stack and the arguments, etc., some handlers may not display their messages, or display them on the subsequent page. Select <em>Standard Drupal</em> <strong>and</strong> <em>Krumo backtrace above the rendered page</em> to maximize your chances of not missing any messages.') . '<br />' . t('Demonstrate the current error handler(s):') . ' ' . $this->l('notice', $current_url, array('query' => array('demo' => 'notice'))) . ', ' . $this->l('notice+warning', $current_url, array('query' => array('demo' => 'warning'))) . ', ' . $this->l('notice+warning+error', $current_url, array('query' => array('demo' => 'error'))) . ' ' . t('(The presentation of the @error is determined by PHP.)', array('@error' => 'error'))));
$form['error_handlers']['#size'] = count($form['error_handlers']['#options']);
if ($request->query->has('demo')) {
if ($request->getMethod() == 'GET') {
$this->demonstrateErrorHandlers($request->query->get('demo'));
}
$request->query->remove('demo');
}
$options = array('default', 'blue', 'green', 'orange', 'white', 'disabled');
$form['krumo_skin'] = array('#type' => 'radios', '#title' => t('Krumo display'), '#description' => t('Select a skin for your debug messages or select <em>disabled</em> to display object and array output in standard PHP format.'), '#options' => array_combine($options, $options), '#default_value' => $devel_config->get('krumo_skin'));
$form['rebuild_theme'] = array('#type' => 'checkbox', '#title' => t('Rebuild the theme information like the registry'), '#description' => t('While creating new templates, change the $theme.info.yml and theme_ overrides the theme information needs to be rebuilt.'), '#default_value' => $devel_config->get('rebuild_theme'));
$form['use_uncompressed_jquery'] = array('#type' => 'checkbox', '#title' => t('Use uncompressed jQuery'), '#default_value' => $devel_config->get('use_uncompressed_jquery'), '#description' => t("Use a human-readable version of jQuery instead of the minified version that ships with Drupal, to make JavaScript debugging easier."));
return parent::buildForm($form, $form_state);
}
示例2: testUserLoginBlock
/**
* Test the user login block.
*/
function testUserLoginBlock()
{
// Make sure the validation error is displayed when try to login with
// invalid username/password.
$edit['name'] = $this->randomMachineName();
$edit['pass'] = $this->randomMachineName();
$this->drupalPostForm('node', $edit, t('Log in'));
$this->assertRaw(\Drupal::translation()->formatPlural(1, '1 error has been found: !errors', '@count errors have been found: !errors', ['!errors' => SafeMarkup::set('<a href="#edit-name">Username</a>')]));
$this->assertText(t('Sorry, unrecognized username or password.'));
// Create a user with some permission that anonymous users lack.
$user = $this->drupalCreateUser(array('administer permissions'));
// Log in using the block.
$edit = array();
$edit['name'] = $user->getUsername();
$edit['pass'] = $user->pass_raw;
$this->drupalPostForm('admin/people/permissions', $edit, t('Log in'));
$this->assertNoText(t('User login'), 'Logged in.');
// Check that we are still on the same page.
$this->assertUrl(\Drupal::url('user.admin_permissions', [], ['absolute' => TRUE]), [], 'Still on the same page after login for access denied page');
// Now, log out and repeat with a non-403 page.
$this->drupalLogout();
$this->drupalPostForm('filter/tips', $edit, t('Log in'));
$this->assertNoText(t('User login'), 'Logged in.');
$this->assertPattern('!<title.*?' . t('Compose tips') . '.*?</title>!', 'Still on the same page after login for allowed page');
// Check that the user login block is not vulnerable to information
// disclosure to third party sites.
$this->drupalLogout();
$this->drupalPostForm('http://example.com/', $edit, t('Log in'), array('external' => FALSE));
// Check that we remain on the site after login.
$this->assertUrl($user->url('canonical', ['absolute' => TRUE]), [], 'Redirected to user profile page after login from the frontpage');
}
示例3: getHead
/**
* Implodes the meta and link elements for the template.
*
* @return string
* A string of meta and link tags.
*/
public function getHead()
{
// Each MetaElement or LinkElement is a subclass of
// \Drupal\Core\Page\HeadElement and generates safe output when __toString()
// is called on it. Thus, the whole concatenation is also safe.
return SafeMarkup::set(implode("\n", $this->getMetaElements()) . implode("\n", $this->getLinkElements()));
}
示例4: testIntegration
/**
* Tests the integration.
*/
public function testIntegration()
{
// Remove the watchdog entries added by the potential batch process.
$this->container->get('database')->truncate('watchdog')->execute();
$entries = array();
// Setup a watchdog entry without tokens.
$entries[] = array('message' => $this->randomMachineName(), 'variables' => array('link' => \Drupal::l('Link', new Url('<front>'))));
// Setup a watchdog entry with one token.
$entries[] = array('message' => '@token1', 'variables' => array('@token1' => $this->randomMachineName(), 'link' => \Drupal::l('Link', new Url('<front>'))));
// Setup a watchdog entry with two tokens.
$entries[] = array('message' => '@token1 !token2', 'variables' => array('@token1' => $this->randomMachineName(), '!token2' => $this->randomMachineName(), 'link' => \Drupal::l(SafeMarkup::set('<object>Link</object>'), new Url('<front>'))));
$logger_factory = $this->container->get('logger.factory');
foreach ($entries as $entry) {
$entry += array('type' => 'test-views', 'severity' => RfcLogLevel::NOTICE);
$logger_factory->get($entry['type'])->log($entry['severity'], $entry['message'], $entry['variables']);
}
$view = Views::getView('test_dblog');
$this->executeView($view);
$view->initStyle();
foreach ($entries as $index => $entry) {
$this->assertEqual($view->style_plugin->getField($index, 'message'), SafeMarkup::format($entry['message'], $entry['variables']));
$this->assertEqual($view->style_plugin->getField($index, 'link'), Xss::filterAdmin($entry['variables']['link']));
}
// 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->assertEqual($view->style_plugin->getField($index, 'message'), $entry['message']);
}
}
示例5: preRenderHtmlTag
/**
* Pre-render callback: Renders a generic HTML tag with attributes into #markup.
*
* Note: It is the caller's responsibility to sanitize any input parameters.
* This callback does not perform sanitization.
*
* @param array $element
* An associative array containing:
* - #tag: The tag name to output. Typical tags added to the HTML HEAD:
* - meta: To provide meta information, such as a page refresh.
* - link: To refer to stylesheets and other contextual information.
* - script: To load JavaScript.
* The value of #tag is not escaped or sanitized, so do not pass in user
* input.
* - #attributes: (optional) An array of HTML attributes to apply to the
* tag.
* - #value: (optional) A string containing tag content, such as inline
* CSS.
* - #value_prefix: (optional) A string to prepend to #value, e.g. a CDATA
* wrapper prefix.
* - #value_suffix: (optional) A string to append to #value, e.g. a CDATA
* wrapper suffix.
*
* @return array
*/
public static function preRenderHtmlTag($element)
{
$attributes = isset($element['#attributes']) ? new Attribute($element['#attributes']) : '';
if (!isset($element['#value'])) {
// This function is intended for internal use, so we assume that no unsafe
// values are passed in #tag. The attributes are already safe because
// Attribute output is already automatically sanitized.
// @todo Escape this properly instead? https://www.drupal.org/node/2296101
$markup = SafeMarkup::set('<' . $element['#tag'] . $attributes . " />\n");
} else {
$markup = '<' . $element['#tag'] . $attributes . '>';
if (isset($element['#value_prefix'])) {
$markup .= $element['#value_prefix'];
}
$markup .= $element['#value'];
if (isset($element['#value_suffix'])) {
$markup .= $element['#value_suffix'];
}
$markup .= '</' . $element['#tag'] . ">\n";
// @todo We cannot actually guarantee this markup is safe. Consider a fix
// in: https://www.drupal.org/node/2296101
$markup = SafeMarkup::set($markup);
}
if (!empty($element['#noscript'])) {
$element['#markup'] = '<noscript>' . $markup . '</noscript>';
} else {
$element['#markup'] = $markup;
}
return $element;
}
示例6: get
/**
* {@inheritdoc}
*/
public function get(array $elements)
{
// Form submissions rely on the form being built during the POST request,
// and render caching of forms prevents this from happening.
// @todo remove the isMethodSafe() check when
// https://www.drupal.org/node/2367555 lands.
if (!$this->requestStack->getCurrentRequest()->isMethodSafe() || !($cid = $this->createCacheID($elements))) {
return FALSE;
}
$bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'render';
if (!empty($cid) && ($cache_bin = $this->cacheFactory->get($bin)) && ($cache = $cache_bin->get($cid))) {
$cached_element = $cache->data;
// Two-tier caching: redirect to actual (post-bubbling) cache item.
// @see \Drupal\Core\Render\RendererInterface::render()
// @see ::set()
if (isset($cached_element['#cache_redirect'])) {
return $this->get($cached_element);
}
// Ensure that any safe properties are marked safe.
foreach ($cached_element['#safe_cache_properties'] as $cache_property) {
SafeMarkup::set($cached_element[$cache_property]);
}
unset($cached_element['#safe_cache_properties']);
// Return the cached element.
return $cached_element;
}
return FALSE;
}
示例7: execute
/**
* Execute the search.
*
* This is a dummy search, so when search "executes", we just return a dummy
* result containing the keywords and a list of conditions.
*
* @return array
* A structured list of search results
*/
public function execute()
{
$results = array();
if (!$this->isSearchExecutable()) {
return $results;
}
return array(array('link' => url('node'), 'type' => 'Dummy result type', 'title' => 'Dummy title', 'snippet' => SafeMarkup::set("Dummy search snippet to display. Keywords: {$this->keywords}\n\nConditions: " . print_r($this->searchParameters, TRUE))));
}
示例8: buildRow
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $view)
{
$row = parent::buildRow($view);
$display_paths = '';
$separator = '';
foreach ($this->getDisplayPaths($view) as $display_path) {
$display_paths .= $separator . SafeMarkup::escape($display_path);
$separator = ', ';
}
return array('data' => array('view_name' => array('data' => array('#theme' => 'views_ui_view_info', '#view' => $view, '#displays' => $this->getDisplaysList($view))), 'description' => array('data' => array('#markup' => String::checkPlain($view->get('description'))), 'class' => array('views-table-filter-text-source')), 'tag' => $view->get('tag'), 'path' => SafeMarkup::set($display_paths), 'operations' => $row['operations']), 'title' => $this->t('Machine name: @name', array('@name' => $view->id())), 'class' => array($view->status() ? 'views-ui-list-enabled' : 'views-ui-list-disabled'));
}
示例9: __toString
/**
* Renders this object to an HTML element string.
*
* @return string
*/
public function __toString()
{
// Render the attributes via the attribute template class.
// @todo Should HeadElement just extend the Attribute classes?
$attributes = new Attribute($this->attributes);
$rendered = (string) $attributes;
$string = "<{$this->element}{$rendered} />";
if ($this->noScript) {
$string = "<noscript>{$string}</noscript>";
}
return SafeMarkup::set($string);
}
示例10: buildForm
/**
* {@inheritdoc}
*
* @param \Drupal\filter\Entity\FilterFormat $filter_format
* The filter format for which this dialog corresponds.
*/
public function buildForm(array $form, array &$form_state, FilterFormat $filter_format = NULL)
{
// The default values are set directly from \Drupal::request()->request,
// provided by the editor plugin opening the dialog.
if (!isset($form_state['image_element'])) {
$form_state['image_element'] = isset($form_state['input']['editor_object']) ? $form_state['input']['editor_object'] : array();
}
$image_element = $form_state['image_element'];
$form['#tree'] = TRUE;
$form['#attached']['library'][] = 'editor/drupal.editor.dialog';
$form['#prefix'] = '<div id="editor-image-dialog-form">';
$form['#suffix'] = '</div>';
$editor = editor_load($filter_format->format);
// Construct strings to use in the upload validators.
$image_upload = $editor->getImageUploadSettings();
if (!empty($image_upload['dimensions'])) {
$max_dimensions = $image_upload['dimensions']['max_width'] . 'x' . $image_upload['dimensions']['max_height'];
} else {
$max_dimensions = 0;
}
$max_filesize = min(Bytes::toInt($image_upload['max_size']), file_upload_max_size());
$existing_file = isset($image_element['data-editor-file-uuid']) ? entity_load_by_uuid('file', $image_element['data-editor-file-uuid']) : NULL;
$fid = $existing_file ? $existing_file->id() : NULL;
$form['fid'] = array('#title' => $this->t('Image'), '#type' => 'managed_file', '#upload_location' => $image_upload['scheme'] . '://' . $image_upload['directory'], '#default_value' => $fid ? array($fid) : NULL, '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg'), 'file_validate_size' => array($max_filesize), 'file_validate_image_resolution' => array($max_dimensions)), '#required' => TRUE);
$form['attributes']['src'] = array('#title' => $this->t('URL'), '#type' => 'textfield', '#default_value' => isset($image_element['src']) ? $image_element['src'] : '', '#maxlength' => 2048, '#required' => TRUE);
// If the editor has image uploads enabled, show a managed_file form item,
// otherwise show a (file URL) text form item.
if ($image_upload['status']) {
$form['attributes']['src']['#access'] = FALSE;
$form['attributes']['src']['#required'] = FALSE;
} else {
$form['fid']['#access'] = FALSE;
$form['fid']['#required'] = FALSE;
}
$form['attributes']['alt'] = array('#title' => $this->t('Alternative text'), '#type' => 'textfield', '#required' => TRUE, '#default_value' => isset($image_element['alt']) ? $image_element['alt'] : '', '#maxlength' => 2048);
$form['dimensions'] = array('#type' => 'item', '#title' => $this->t('Image size'), '#field_prefix' => SafeMarkup::set('<div class="container-inline">'), '#field_suffix' => SafeMarkup::set('</div>'));
$form['dimensions']['width'] = array('#title' => $this->t('Width'), '#title_display' => 'invisible', '#type' => 'number', '#default_value' => isset($image_element['width']) ? $image_element['width'] : '', '#size' => 8, '#maxlength' => 8, '#min' => 1, '#max' => 99999, '#placeholder' => $this->t('width'), '#field_suffix' => ' x ', '#parents' => array('attributes', 'width'));
$form['dimensions']['height'] = array('#title' => $this->t('Height'), '#title_display' => 'invisible', '#type' => 'number', '#default_value' => isset($image_element['height']) ? $image_element['height'] : '', '#size' => 8, '#maxlength' => 8, '#min' => 1, '#max' => 99999, '#placeholder' => $this->t('height'), '#field_suffix' => $this->t('pixels'), '#parents' => array('attributes', 'height'));
// When Drupal core's filter_caption is being used, the text editor may
// offer the ability to change the alignment.
if (isset($image_element['data-align'])) {
$form['align'] = array('#title' => $this->t('Align'), '#type' => 'radios', '#options' => array('none' => $this->t('None'), 'left' => $this->t('Left'), 'center' => $this->t('Center'), 'right' => $this->t('Right')), '#default_value' => $image_element['data-align'] === '' ? 'none' : $image_element['data-align'], '#wrapper_attributes' => array('class' => array('container-inline')), '#attributes' => array('class' => array('container-inline')), '#parents' => array('attributes', 'data-align'));
}
// When Drupal core's filter_caption is being used, the text editor may
// offer the ability to in-place edit the image's caption: show a toggle.
if (isset($image_element['hasCaption'])) {
$form['caption'] = array('#title' => $this->t('Caption'), '#type' => 'checkbox', '#default_value' => $image_element['hasCaption'] === 'true', '#parents' => array('attributes', 'hasCaption'));
}
$form['actions'] = array('#type' => 'actions');
$form['actions']['save_modal'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#submit' => array(), '#ajax' => array('callback' => array($this, 'submitForm'), 'event' => 'click'));
return $form;
}
示例11: _flushLine
protected function _flushLine($new_tag)
{
$this->_flushGroup($new_tag);
if ($this->line != '') {
// @todo This is probably not the right place to do this. To be
// addressed in https://drupal.org/node/2280963
array_push($this->lines, SafeMarkup::set($this->line));
} else {
// make empty lines visible by inserting an NBSP
array_push($this->lines, $this::NBSP);
}
$this->line = '';
}
示例12: fieldFilterXss
/**
* Filters an HTML string to prevent XSS vulnerabilities.
*
* Like \Drupal\Component\Utility\Xss::filterAdmin(), but with a shorter list
* of allowed tags.
*
* Used for items entered by administrators, like field descriptions, allowed
* values, where some (mainly inline) mark-up may be desired (so
* \Drupal\Component\Utility\SafeMarkup::checkPlain() is not acceptable).
*
* @param string $string
* The string with raw HTML in it.
*
* @return \Drupal\Component\Utility\SafeMarkup
* An XSS safe version of $string, or an empty string if $string is not
* valid UTF-8.
*/
public function fieldFilterXss($string)
{
// All known XSS vectors are filtered out by
// \Drupal\Component\Utility\Xss::filter(), all tags in the markup are
// allowed intentionally by the trait, and no danger is added in by
// \Drupal\Component\Utility\HTML::normalize(). Since the normalized value
// is essentially the same markup, designate this string as safe as well.
// This method is an internal part of field sanitization, so the resultant,
// sanitized string should be printable as is.
//
// @todo Free this memory in https://www.drupal.org/node/2505963.
return SafeMarkup::set(Html::normalize(Xss::filter($string, $this->allowedTags())));
}
示例13: renderExceptionSafe
/**
* Renders an exception error message without further exceptions.
*
* @param \Exception $exception
* The exception object that was thrown.
*
* @return string
* An error message.
*/
public static function renderExceptionSafe(\Exception $exception)
{
$decode = static::decodeException($exception);
$backtrace = $decode['backtrace'];
unset($decode['backtrace']);
// Remove 'main()'.
array_shift($backtrace);
$output = String::format('%type: !message in %function (line %line of %file).', $decode);
// Even though it is possible that this method is called on a public-facing
// site, it is only called when the exception handler itself threw an
// exception, which normally means that a code change caused the system to
// no longer function correctly (as opposed to a user-triggered error), so
// we assume that it is safe to include a verbose backtrace.
$output .= '<pre>' . static::formatBacktrace($backtrace) . '</pre>';
return SafeMarkup::set($output);
}
示例14: getValue
/**
* Implements \Drupal\Core\TypedData\TypedDataInterface::getValue().
*/
public function getValue($langcode = NULL)
{
if ($this->processed !== NULL) {
return $this->processed;
}
$item = $this->getParent();
$text = $item->{$this->definition->getSetting('text source')};
// Avoid running check_markup() or
// \Drupal\Component\Utility\String::checkPlain() on empty strings.
if (!isset($text) || $text === '') {
$this->processed = '';
} elseif ($item->getFieldDefinition()->getSetting('text_processing')) {
$this->processed = check_markup($text, $item->format, $item->getLangcode());
} else {
// Escape all HTML and retain newlines.
// @see \Drupal\Core\Field\Plugin\Field\FieldFormatter\StringFormatter
$this->processed = SafeMarkup::set(nl2br(String::checkPlain($text)));
}
return $this->processed;
}
示例15: format
/**
* Formats a message composed by drupal_mail().
*
* @see http://api.drupal.org/api/drupal/includes--mail.inc/interface/MailSystemInterface/7
*
* @param array $message
* A message array holding all relevant details for the message.
*
* @return string
* The message as it should be sent.
*/
public function format(array $message)
{
// Get default mail line endings and merge all lines in the e-mail body
// separated by the mail line endings.
$line_endings = Settings::get('mail_line_endings', PHP_EOL);
$message['body'] = SafeMarkup::set(implode($line_endings, $message['body']));
// Get applicable format.
$applicable_format = $this->getApplicableFormat($message);
// Theme message if format is set to be HTML.
if ($applicable_format == SWIFTMAILER_FORMAT_HTML) {
$render = array('#theme' => isset($message['params']['theme']) ? $message['params']['theme'] : 'swiftmailer', '#message' => $message);
$message['body'] = $this->renderer->renderRoot($render);
if ($this->config['message']['convert_mode'] || !empty($message['params']['convert'])) {
$converter = new Html2Text($message['body']);
$message['plain'] = $converter->get_text();
}
}
// Process any images specified by 'image:' which are to be added later
// in the process. All we do here is to alter the message so that image
// paths are replaced with cid's. Each image gets added to the array
// which keeps track of which images to embed in the e-mail.
$embeddable_images = array();
preg_match_all('/"image:([^"]+)"/', $message['body'], $embeddable_images);
for ($i = 0; $i < count($embeddable_images[0]); $i++) {
$image_id = $embeddable_images[0][$i];
$image_path = trim($embeddable_images[1][$i]);
$image_name = basename($image_path);
if (Unicode::substr($image_path, 0, 1) == '/') {
$image_path = Unicode::substr($image_path, 1);
}
$image = new stdClass();
$image->uri = $image_path;
$image->filename = $image_name;
$image->filemime = file_get_mimetype($image_path);
$image->cid = rand(0, 9999999999.0);
$message['params']['images'][] = $image;
$message['body'] = preg_replace($image_id, 'cid:' . $image->cid, $message['body']);
}
return $message;
}