/** * Tests CRUD operations for text formats and filters. */ function testTextFormatCrud() { // Add a text format with minimum data only. $format = FilterFormat::create(array('format' => 'empty_format', 'name' => 'Empty format')); $format->save(); $this->verifyTextFormat($format); // Add another text format specifying all possible properties. $format = FilterFormat::create(array('format' => 'custom_format', 'name' => 'Custom format')); $format->setFilterConfig('filter_url', array('status' => 1, 'settings' => array('filter_url_length' => 30))); $format->save(); $this->verifyTextFormat($format); // Alter some text format properties and save again. $format->set('name', 'Altered format'); $format->setFilterConfig('filter_url', array('status' => 0)); $format->setFilterConfig('filter_autop', array('status' => 1)); $format->save(); $this->verifyTextFormat($format); // Add a filter_test_replace filter and save again. $format->setFilterConfig('filter_test_replace', array('status' => 1)); $format->save(); $this->verifyTextFormat($format); // Disable the text format. $format->disable()->save(); $formats = filter_formats(); $this->assertTrue(!isset($formats[$format->id()]), 'filter_formats: Disabled text format no longer exists.'); }
protected function setUp() { parent::setUp(); // Enable user signatures. \Drupal::config('user.settings')->set('signatures', 1)->save(); // Create Basic page node type. $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); // Add a comment field with commenting enabled by default. $this->container->get('comment.manager')->addDefaultField('node', 'page'); // Prefetch and create text formats. $this->filtered_html_format = entity_create('filter_format', array('format' => 'filtered_html_format', 'name' => 'Filtered HTML', 'weight' => -1, 'filters' => array('filter_html' => array('module' => 'filter', 'status' => TRUE, 'settings' => array('allowed_html' => '<a> <em> <strong>'))))); $this->filtered_html_format->save(); $this->full_html_format = entity_create('filter_format', array('format' => 'full_html', 'name' => 'Full HTML')); $this->full_html_format->save(); user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array($this->filtered_html_format->getPermissionName())); // Create regular and administrative users. $this->web_user = $this->drupalCreateUser(array('post comments')); $admin_permissions = array('post comments', 'administer comments', 'administer user form display', 'administer account settings'); foreach (filter_formats() as $format) { if ($permission = $format->getPermissionName()) { $admin_permissions[] = $permission; } } $this->admin_user = $this->drupalCreateUser($admin_permissions); }
/** * {@inheritdoc} */ public function getSettableOptions(AccountInterface $account = NULL) { // @todo: Avoid calling functions but move to injected dependencies. return array_map(function ($format) { return $format->label(); }, filter_formats($account)); }
/** * Returns a new term with random properties in vocabulary $vid. * * @param \Drupal\taxonomy\Entity\Vocabulary $vocabulary * The vocabulary object. * @param array $values * (optional) An array of values to set, keyed by property name. If the * entity type has bundles, the bundle key has to be specified. * * @return \Drupal\taxonomy\Entity\Term * The new taxonomy term object. */ function createTerm(Vocabulary $vocabulary, $values = array()) { $filter_formats = filter_formats(); $format = array_pop($filter_formats); $term = Term::create($values + ['name' => $this->randomMachineName(), 'description' => ['value' => $this->randomMachineName(), 'format' => $format->id()], 'vid' => $vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]); $term->save(); return $term; }
/** * Get a text format object given its machine name. * * @param string $format_name * Text format machine name. * @param bool $reset * TRUE to reset filter formats cache. * * @return object|bool * Text format object or FALSE. */ public function getFormat($format_name, $reset = FALSE) { if ($reset) { filter_formats_reset(); } $formats = filter_formats(); return isset($formats[$format_name]) ? (object) $formats[$format_name] : FALSE; }
/** * Returns a new term with random properties in vocabulary $vid. * * @return \Drupal\taxonomy\Term * The created taxonomy term. */ protected function createTerm() { $filter_formats = filter_formats(); $format = array_pop($filter_formats); $term = entity_create('taxonomy_term', array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'format' => $format->format, 'vid' => $this->vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); $term->save(); return $term; }
public function buildConfigurationForm(array &$form, array &$form_state) { global $user; $options = array(); foreach (filter_formats($user) as $id => $format) { $options[$id] = $format->label(); } $form['format'] = array('#type' => 'select', '#title' => $this->t('Description format'), '#options' => $options, '#default_value' => $this->configuration['format']); }
/** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $options = []; foreach (filter_formats($this->user) as $id => $format) { $options[$id] = $format->label(); } $form['format'] = ['#type' => 'select', '#title' => $this->t('Filter format'), '#options' => $options, '#default_value' => $this->configuration['format']]; return $form; }
/** * Overrides Drupal\configuration\Config\Configuration::findDependencies(). */ public function findDependencies() { $format = $this->getIdentifier(); $formats = filter_formats(); if (isset($formats[$format])) { $filter_format = ConfigurationManagement::createConfigurationInstance('text_format.' . $format); $this->addToDependencies($filter_format); } parent::findDependencies(); }
/** * Implements QuickEditInPlaceEditorInterface::getAttachments(). * * @see Drupal 8's \Drupal\editor\Plugin\quickedit\editor\Editor::getAttachments(). */ public function getAttachments() { global $user; // Get a list of formats to which the current user has access. $formats = filter_formats($user); // Get filter configuration information for the available formats. $settings = editor_get_attached($formats); // Also include editor.module's formatted text editor. $settings['library'][] = array('editor', 'quickedit.inPlaceEditor.formattedText'); $settings['js'][] = array('type' => 'setting', 'data' => array('quickedit' => array('ckeditor' => array('basePath' => base_path() . drupal_get_path('module', 'editor_ckeditor') . '/lib/ckeditor/')))); return $settings; }
/** * Overrides theme_filter_tips(). */ function bootstrap_subtheme_filter_tips($variables) { global $user; drupal_set_title(''); // Create a place holder for the tabs. $build['tabs'] = array('#theme' => 'item_list', '#items' => array(), '#attributes' => array('class' => array('nav', 'nav-tabs'), 'role' => 'tablist')); // Create a placeholder for the panes. $build['panes'] = array('#theme_wrappers' => array('container'), '#attributes' => array('class' => array('tab-content'))); $format_id = arg(2); $current_path = current_path(); $formats = filter_formats($user); $filter_info = filter_get_filters(); foreach ($formats as $format) { $tab = array('data' => array('#type' => 'link', '#title' => check_plain($format->name), '#href' => $current_path, '#attributes' => array('role' => 'tab', 'data-toggle' => 'tab'), '#options' => array('fragment' => $format->format))); if (!$format_id || $format_id === $format->format) { $tab['class'][] = 'active'; $format_id = $format->format; } $build['tabs']['#items'][] = $tab; // Retrieve each filter in the format. $tips = array(); $filters = filter_list_format($format->format); foreach ($filters as $name => $filter) { if ($filter->status && isset($filter_info[$name]['tips callback']) && is_callable($filter_info[$name]['tips callback'])) { $tip = $filter_info[$name]['tips callback']($filter, $format, TRUE); if (isset($tip)) { $tips[] = $tip; } } } // Construct the pane. $pane = array('#theme_wrappers' => array('container'), '#attributes' => array('class' => array('tab-pane', 'fade'), 'id' => $format->format)); if (count($tips) === 1) { $pane['list'] = array('#markup' => $tips[0]); } else { $pane['list'] = array('#theme' => 'item_list', '#items' => $tips); } if ($format_id === $format->format) { $pane['#attributes']['class'][] = 'active'; $pane['#attributes']['class'][] = 'in'; $format_id = $format->format; } $build['panes'][] = $pane; } return drupal_render($build); }
/** * Helper function for mass adding of terms. * * @param $input * The textual input with terms. Each line contains a single term. Child term * can be prefixed with a dash '-' (one dash for each level). Term names * starting with a dash and should not become a child term need to be wrapped * in quotes. * @param $vid * The vocabulary id. * @param int $parents * An array of parent term ids for the new inserted terms. Can be 0. * @param $term_names_too_long * Return value that is used to indicate that some term names were too long * and truncated to 255 characters. * * @return An array of the newly inserted term objects */ public static function mass_add_terms($input, $vid, $parents, &$term_names_too_long = array()) { $new_terms = array(); $terms = explode("\n", str_replace("\r", '', $input)); $parents = count($parents) ? $parents : 0; // Stores the current lineage of newly inserted terms. $last_parents = array(); foreach ($terms as $name) { if (empty($name)) { continue; } $matches = array(); // Child term prefixed with one or more dashes if (preg_match('/^(-){1,}/', $name, $matches)) { $depth = strlen($matches[0]); $name = substr($name, $depth); $current_parents = isset($last_parents[$depth - 1]) ? array($last_parents[$depth - 1]->id()) : 0; } elseif (preg_match('/^\\"(-){1,}.*\\"/', $name, $matches)) { $name = substr($name, 1, -1); $depth = 0; $current_parents = $parents; } else { $depth = 0; $current_parents = $parents; } // Truncate long string names that will cause database exceptions. if (strlen($name) > 255) { $term_names_too_long[] = $name; $name = substr($name, 0, 255); } $filter_formats = filter_formats(); $format = array_pop($filter_formats); $values = ['name' => $name, 'format' => $format->id(), 'vid' => $vid, 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]; if (!empty($current_parents)) { foreach ($current_parents as $p) { $values['parent'][] = array('target_id' => $p); } } $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($values); $term->save(); $new_terms[] = $term; $last_parents[$depth] = $term; } return $new_terms; }
/** * Creates and saves a new term with in vocabulary $vid. * * @param \Drupal\taxonomy\Entity\Vocabulary $vocabulary * The vocabulary object. * @param array $values * (optional) An array of values to set, keyed by property name. If the * entity type has bundles, the bundle key has to be specified. * * @return \Drupal\taxonomy\Entity\Term * The new taxonomy term object. */ private function createTerm(Vocabulary $vocabulary, $values = array()) { $filter_formats = filter_formats(); $format = array_pop($filter_formats); $termStorage = \Drupal::entityTypeManager()->getStorage('taxonomy_term'); $term = $termStorage->create($values + array( 'name' => $this->randomMachineName(), 'description' => array( 'value' => $this->randomMachineName(), // Use the first available text format. 'format' => $format->id(), ), 'vid' => $vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, )); $term->save(); return $term; }
/** * @param $contentTypes * @param $limit * @param $titleWords * @param $timeRange * * @return array */ public function createTerm($vocabularies, $limit, $nameWords) { $terms = []; $values = []; for ($i = 0; $i < $limit; $i++) { $vocabulary = Vocabulary::load($vocabularies[array_rand($vocabularies)]); $filter_formats = filter_formats(); $format = array_pop($filter_formats); $term = entity_create('taxonomy_term', $values + array('name' => $this->getRandom()->sentences(mt_rand(1, $nameWords), true), 'description' => array('value' => $this->getRandom()->sentences(), 'format' => $format->id()), 'vid' => $vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); try { $term->save(); $terms['success'][] = ['tid' => $term->id(), 'vocabulary' => $vocabulary->get('name'), 'name' => $term->getName()]; } catch (\Exception $error) { $terms['error'][] = ['vocabulary' => $vocabularies[$vocabulary], 'name' => $term->getName(), 'error' => $error->getMessage()]; } } return $terms; }
/** * Overrides Drupal\configuration\Config\Configuration::alterDependencies(). */ public static function alterDependencies(Configuration $config) { if ($config->getComponent() == 'permission') { // Generate permissions for each text format. Warn the administrator that any // of them are potentially unsafe. foreach (filter_formats() as $format) { $permission = filter_permission_name($format); if (!empty($permission)) { $data = $config->getData(); if ($permission == $data['permission']) { $text_format = ConfigurationManagement::createConfigurationInstance('text_format.' . $format->format); $config->addToDependencies($text_format); break; } } } } }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $medium_editor = $this->getEntity(); // Check duplication if ($this->getOperation() === 'duplicate') { $medium_editor = $medium_editor->createDuplicate(); $medium_editor->set('label', $this->t('Duplicate of !label', array('!label' => $medium_editor->label()))); $this->setEntity($medium_editor); } // Label $form['label'] = array('#type' => 'textfield', '#title' => $this->t('Name'), '#default_value' => $medium_editor->label(), '#maxlength' => 64, '#required' => TRUE); // Id $form['id'] = array('#type' => 'machine_name', '#machine_name' => array('exists' => array(get_class($medium_editor), 'load'), 'source' => array('label')), '#default_value' => $medium_editor->id(), '#maxlength' => 32, '#required' => TRUE); // Description $form['description'] = array('#type' => 'textfield', '#title' => $this->t('Description'), '#default_value' => $medium_editor->get('description')); // Delay $form['delay'] = array('#type' => 'textfield', '#title' => $this->t('Delay'), '#default_value' => $medium_editor->get('delay')); // Diffleft $form['diffleft'] = array('#type' => 'textfield', '#title' => $this->t('Diffleft'), '#default_value' => $medium_editor->get('diffleft')); // Diffright $form['difftop'] = array('#type' => 'textfield', '#title' => $this->t('Difftop'), '#default_value' => $medium_editor->get('difftop')); // Settings $form['settings'] = array('#tree' => TRUE); $widget_libraries = $widget['libraries']; unset($widget['libraries']); $form['settings']['toolbar_config'] = array('#type' => 'fieldset', '#title' => $this->t('Toolbar configuration'), '#attached' => array('library' => $widget_libraries, 'drupalSettings' => array('medium' => array('twSettings' => $widget)))); $form['settings']['toolbar_config']['toolbar'] = array('#type' => 'textfield', '#title' => $this->t('Active toolbar'), '#default_value' => implode(', ', $medium_editor->getToolbar()), '#attributes' => array('class' => array('medium-toolbar-input')), '#maxlength' => NULL, '#parents' => array('settings', 'toolbar')); // Add demo if (!$medium_editor->isNew()) { $formats = array(); foreach (filter_formats(\Drupal::currentUser()) as $format) { $formats[] = '<option value="' . String::checkPlain($format->id()) . '">' . String::checkPlain($format->label()) . '</option>'; } $form['demo']['#markup'] = '<div class="form-item form-type-textarea medium-demo"><label>' . $this->t('Demo') . '</label><textarea class="form-textarea" cols="40" rows="5"></textarea><div class="form-item form-type-select filter-wrapper"><span class="label">' . $this->t('Text format') . '</span> <select class="filter-list form-select">' . implode('', $formats) . '</select></div></div>'; $form['demo']['#weight'] = 1000; $form['demo']['#attached']['library'] = $medium_editor->getLibraries(); $form['demo']['#attached']['drupalSettings']['medium']['demoSettings'] = $medium_editor->getJSSettings(); } // Add admin library $form['#attached']['library'][] = 'medium/drupal.medium.admin'; // Allow plugins to add their elements \Drupal::service('plugin.manager.medium.plugin')->alterEditorForm($form, $form_state, $medium_editor); return parent::form($form, $form_state); }
/** * {@inheritdoc} */ public function preprocessVariables(Variables $variables, $hook, array $info) { /** @var \Drupal\filter\FilterFormatInterface $current_format */ $current_format = \Drupal::routeMatch()->getParameter('filter_format'); $current_format_id = $current_format ? $current_format->id() : FALSE; // Create a place holder for the tabs. $build['tabs'] = ['#theme' => 'item_list__filter_tips__tabs', '#items' => [], '#attributes' => ['class' => ['nav', 'nav-tabs', 'filter-formats'], 'role' => 'tablist']]; // Create a placeholder for the panes. $build['panes'] = ['#theme_wrappers' => ['container__filter_tips__panes'], '#attributes' => ['class' => ['tab-content']]]; foreach (filter_formats(\Drupal::currentUser()) as $format_id => $format) { // Set the current format ID to the first format. if (!$current_format_id) { $current_format_id = $format_id; } $tab = ['#type' => 'link', '#title' => $format->label(), '#url' => Url::fromRoute('filter.tips', ['filter_format' => $format_id]), '#attributes' => ['role' => 'tab', 'data-toggle' => 'tab', 'data-target' => "#{$format_id}"]]; if ($current_format_id === $format_id) { $tab['#wrapper_attributes']['class'][] = 'active'; } $build['tabs']['#items'][] = $tab; $tips = []; // Iterate over each format's enabled filters. /** @var \Drupal\filter\Plugin\FilterBase $filter */ foreach ($format->filters() as $name => $filter) { // Ignore filters that are not enabled. if (!$filter->status) { continue; } $tip = $filter->tips(TRUE); if (isset($tip)) { $tips[] = ['#markup' => $tip]; } } // Construct the pane. $pane = ['#theme_wrappers' => ['container__filter_tips'], '#attributes' => ['class' => ['tab-pane', 'fade'], 'id' => $format_id], 'list' => ['#theme' => 'item_list', '#items' => $tips]]; if ($current_format_id === $format_id) { $pane['#attributes']['class'][] = 'active'; $pane['#attributes']['class'][] = 'in'; } $build['panes'][] = $pane; } $variables['tips'] = $build; }
/** * {@inheritdoc} */ public function getAttachments() { $user = \Drupal::currentUser(); $user_format_ids = array_keys(filter_formats($user)); $manager = \Drupal::service('plugin.manager.editor'); $definitions = $manager->getDefinitions(); // Filter the current user's formats to those that support inline editing. $formats = array(); foreach ($user_format_ids as $format_id) { if ($editor = editor_load($format_id)) { $editor_id = $editor->getEditor(); if (isset($definitions[$editor_id]['supports_inline_editing']) && $definitions[$editor_id]['supports_inline_editing'] === TRUE) { $formats[] = $format_id; } } } // Get the attachments for all text editors that the user might use. $attachments = $manager->getAttachments($formats); // Also include editor.module's formatted text editor. $attachments['library'][] = 'editor/quickedit.inPlaceEditor.formattedText'; return $attachments; }
public function generateValues($object, $instance, $plugin_definition, $form_display_options) { $object_field = array(); $settings = $instance->getSettings(); if (!empty($settings['text_processing'])) { $formats = filter_formats(); $format = array_rand($formats); } else { $format = filter_fallback_format(); } if (empty($settings['max_length'])) { // Textarea handling $object_field['value'] = DevelGenerateBase::createContent($format); if ($form_display_options['type'] == 'text_textarea_with_summary' && !empty($settings['display_summary'])) { $object_field['summary'] = DevelGenerateBase::createContent($format); } } else { // Textfield handling. $object_field['value'] = substr(DevelGenerateBase::createGreeking(mt_rand(1, $settings['max_length'] / 6), FALSE), 0, $settings['max_length']); } $object_field['format'] = $format; return $object_field; }
/** * Creates a taxonomy term with specified name and other properties. * * @param array $properties * Array of properties and field values to set. * * @return \Drupal\taxonomy\TermInterface * The created taxonomy term. */ protected function createTermWithProperties($properties) { // Use the first available text format. $filter_formats = filter_formats(); $format = array_pop($filter_formats); $properties += array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'field_foo' => $this->randomMachineName()); $term = Term::create(['name' => $properties['name'], 'description' => $properties['description'], 'format' => $format->id(), 'vid' => $this->vocabulary->id(), 'langcode' => $properties['langcode']]); $term->field_foo->value = $properties['field_foo']; $term->save(); return $term; }
/** * Helper function for testTextfieldWidgetsFormatted(). */ function _testTextfieldWidgetsFormatted($field_type, $widget_type) { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = $this->container->get('renderer'); // Create a field. $field_name = Unicode::strtolower($this->randomMachineName()); $field_storage = entity_create('field_storage_config', array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => $field_type)); $field_storage->save(); entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => 'entity_test', 'label' => $this->randomMachineName() . '_label'))->save(); entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => $widget_type))->save(); entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name)->save(); // Disable all text formats besides the plain text fallback format. $this->drupalLogin($this->adminUser); foreach (filter_formats() as $format) { if (!$format->isFallbackFormat()) { $this->drupalPostForm('admin/config/content/formats/manage/' . $format->id() . '/disable', array(), t('Disable')); } } $this->drupalLogin($this->webUser); // Display the creation form. Since the user only has access to one format, // no format selector will be displayed. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed'); $this->assertNoFieldByName("{$field_name}[0][format]", '', 'Format selector is not displayed'); // Submit with data that should be filtered. $value = '<em>' . $this->randomMachineName() . '</em>'; $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created'); // Display the entity. $entity = entity_load('entity_test', $id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent($renderer->renderRoot($content)); $this->assertNoRaw($value, 'HTML tags are not displayed.'); $this->assertEscaped($value, 'Escaped HTML is displayed correctly.'); // Create a new text format that does not escape HTML, and grant the user // access to it. $this->drupalLogin($this->adminUser); $edit = array('format' => Unicode::strtolower($this->randomMachineName()), 'name' => $this->randomMachineName()); $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration')); filter_formats_reset(); $format = entity_load('filter_format', $edit['format']); $format_id = $format->id(); $permission = $format->getPermissionName(); $roles = $this->webUser->getRoles(); $rid = $roles[0]; user_role_grant_permissions($rid, array($permission)); $this->drupalLogin($this->webUser); // Display edition form. // We should now have a 'text format' selector. $this->drupalGet('entity_test/manage/' . $id . '/edit'); $this->assertFieldByName("{$field_name}[0][value]", NULL, 'Widget is displayed'); $this->assertFieldByName("{$field_name}[0][format]", NULL, 'Format selector is displayed'); // Edit and change the text format to the new one that was created. $edit = array("{$field_name}[0][format]" => $format_id); $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated'); // Display the entity. $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id)); $entity = entity_load('entity_test', $id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent($renderer->renderRoot($content)); $this->assertRaw($value, 'Value is displayed unfiltered'); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('mimemail.settings'); $form = array(); $form['mimemail']['name'] = array('#type' => 'textfield', '#title' => t('Sender name'), '#default_value' => $config->get('name') ? $config->get('name') : \Drupal::config('system.site')->get('name'), '#size' => 60, '#maxlength' => 128, '#description' => t('The name that all site emails will be from when using default engine.')); $form['mimemail']['mail'] = array('#type' => 'textfield', '#title' => t('Sender e-mail address'), '#default_value' => $config->get('mail') ? $config->get('mail') : \Drupal::config('system.site')->get('mail'), '#size' => 60, '#maxlength' => 128, '#description' => t('The email address that all site e-mails will be from when using default engine.')); // Get a list of all formats. $formats = filter_formats(); $format_options = array(); foreach ($formats as $format) { $format_options[$format->get('format')] = $format->get('name'); } $form['mimemail']['format'] = array('#type' => 'select', '#title' => t('E-mail format'), '#default_value' => $this->config('mimemail.settings')->get('format'), '#options' => $format_options, '#access' => count($formats) > 1, '#attributes' => array('class' => array('filter-list'))); // Check for the existence of a mail.css file in the default theme folder. /*$theme = variable_get('theme_default', NULL); $mailstyle = drupal_get_path('theme', $theme) . '/mail.css'; // Disable site style sheets including option if found. if (is_file($mailstyle)) { variable_set('mimemail_sitestyle', 0); $disable_sitestyle = TRUE; } else { $disable_sitestyle = FALSE; } $form = array(); $form['mimemail']['mimemail_name'] = array( '#type' => 'textfield', '#title' => t('Sender name'), '#default_value' => variable_get('mimemail_name', variable_get('site_name', 'Drupal')), '#size' => 60, '#maxlength' => 128, '#description' => t('The name that all site emails will be from when using default engine.'), ); $form['mimemail']['mimemail_mail'] = array( '#type' => 'textfield', '#title' => t('Sender e-mail address'), '#default_value' => variable_get('mimemail_mail', variable_get('site_mail', ini_get('sendmail_from'))), '#size' => 60, '#maxlength' => 128, '#description' => t('The email address that all site e-mails will be from when using default engine.'), ); $form['mimemail']['mimemail_simple_address'] = array( '#type' => 'checkbox', '#title' => t('Use simple address format'), '#default_value' => variable_get('mimemail_simple_address', FALSE), '#description' => t('Use the simple format of user@example.com for all recipient email addresses.'), ); $form['mimemail']['mimemail_sitestyle'] = array( '#type' => 'checkbox', '#title' => t('Include site style sheets'), '#default_value' => variable_get('mimemail_sitestyle', TRUE), '#description' => t('Gather all style sheets when no mail.css found in the default theme directory.'), '#disabled' => $disable_sitestyle, ); $form['mimemail']['mimemail_textonly'] = array( '#type' => 'checkbox', '#title' => t('Send plain text email only'), '#default_value' => variable_get('mimemail_textonly', FALSE), '#description' => t('This option disables the use of email messages with graphics and styles. All messages will be converted to plain text.'), ); $form['mimemail']['mimemail_linkonly'] = array( '#type' => 'checkbox', '#title' => t('Link images only'), '#default_value' => variable_get('mimemail_linkonly', 0), '#description' => t('This option disables the embedding of images. All image will be available as external content. This can make email messages much smaller.'), ); if (module_exists('mimemail_compress')) { $form['mimemail']['mimemail_preserve_class'] = array( '#type' => 'checkbox', '#title' => t('Preserve class attributes'), '#default_value' => variable_get('mimemail_preserve_class', 0), '#description' => t('This option disables the removing of class attributes from the message source. Useful for debugging the style of the message.'), ); } // Get a list of all formats. $formats = filter_formats(); foreach ($formats as $format) { $format_options[$format->format] = $format->name; } $form['mimemail']['mimemail_format'] = array( '#type' => 'select', '#title' => t('E-mail format'), '#options' => $format_options, '#default_value' => variable_get('mimemail_format', filter_fallback_format()), '#access' => count($formats) > 1, '#attributes' => array('class' => array('filter-list')), ); $form['mimemail']['advanced'] = array( '#type' => 'fieldset', '#title' => t('Advanced settings'), '#collapsible' => TRUE, '#collapsed' => TRUE, ); $form['mimemail']['advanced']['mimemail_incoming'] = array( '#type' => 'checkbox', '#title' => t('Process incoming messages posted to this site'), '#default_value' => variable_get('mimemail_incoming', FALSE), '#description' => t('This is an advanced setting that should not be enabled unless you know what you are doing.'), ); $form['mimemail']['advanced']['mimemail_key'] = array( '#type' => 'textfield', '#title' => t('Message validation string'), '#default_value' => variable_get('mimemail_key', drupal_random_key()), '#required' => TRUE, '#description' => t('This string will be used to validate incoming messages. It can be anything, but must be used on both sides of the transfer.'), ); // Get the available mail engines. $engines = mimemail_get_engines(); foreach ($engines as $module => $engine) { $engine_options[$module] = $engine['name'] . ': ' . $engine['description']; } // Hide the settings if only 1 engine is available. if (count($engines) == 1) { reset($engines); variable_set('mimemail_engine', key($engines)); $form['mimemail']['mimemail_engine'] = array( '#type' => 'hidden', '#value' => variable_get('mimemail_engine', 'mimemail'), ); } else { $form['mimemail']['mimemail_engine'] = array( '#type' => 'select', '#title' => t('E-mail engine'), '#default_value' => variable_get('mimemail_engine', 'mimemail'), '#options' => $engine_options, '#description' => t('Choose an engine for sending mails from your site.'), ); } if (variable_get('mimemail_engine', 'mail')) { $settings = module_invoke(variable_get('mimemail_engine', 'mimemail'), 'mailengine', 'settings'); if ($settings) { $form['mimemail']['engine_settings'] = array( '#type' => 'fieldset', '#title' => t('Engine specific settings'), ); foreach ($settings as $name => $value) { $form['mimemail']['engine_settings'][$name] = $value; } } } else { drupal_set_message(t('Please choose a mail engine.'), 'error'); }*/ return parent::buildForm($form, $form_state); }
/** * Loads the format declared in the config file */ function loadFormat() { global $mniblogpub_props; $format = null; if ($mniblogpub_props["mniblogpub.php"]["format.name"]) { $formats = filter_formats(); foreach ($formats as $f) { if ($f->name == $mniblogpub_props["mniblogpub.php"]["format.name"]) { $format = $f->format; break; } } } return $format; }
/** * Tests editing a page using a disallowed text format. * * Verifies that regular users and administrators are able to edit a page, but * not allowed to change the fields which use an inaccessible text format. * Also verifies that fields which use a text format that does not exist can * be edited by administrators only, but that the administrator is forced to * choose a new format before saving the page. */ function testFormatWidgetPermissions() { $body_value_key = 'body[0][value]'; $body_format_key = 'body[0][format]'; // Create node to edit. $this->drupalLogin($this->adminUser); $edit = array(); $edit['title[0][value]'] = $this->randomMachineName(8); $edit[$body_value_key] = $this->randomMachineName(16); $edit[$body_format_key] = $this->disallowedFormat->id(); $this->drupalPostForm('node/add/page', $edit, t('Save')); $node = $this->drupalGetNodeByTitle($edit['title[0][value]']); // Try to edit with a less privileged user. $this->drupalLogin($this->webUser); $this->drupalGet('node/' . $node->id()); $this->clickLink(t('Edit')); // Verify that body field is read-only and contains replacement value. $this->assertFieldByXPath("//textarea[@name='{$body_value_key}' and @disabled='disabled']", t('This field has been disabled because you do not have sufficient permissions to edit it.'), 'Text format access denied message found.'); // Verify that title can be changed, but preview displays original body. $new_edit = array(); $new_edit['title[0][value]'] = $this->randomMachineName(8); $this->drupalPostForm(NULL, $new_edit, t('Preview')); $this->assertText($edit[$body_value_key], 'Old body found in preview.'); // Save and verify that only the title was changed. $this->drupalPostForm('node/' . $node->id() . '/edit', $new_edit, t('Save')); $this->assertNoText($edit['title[0][value]'], 'Old title not found.'); $this->assertText($new_edit['title[0][value]'], 'New title found.'); $this->assertText($edit[$body_value_key], 'Old body found.'); // Check that even an administrator with "administer filters" permission // cannot edit the body field if they do not have specific permission to // use its stored format. (This must be disallowed so that the // administrator is never forced to switch the text format to something // else.) $this->drupalLogin($this->filterAdminUser); $this->drupalGet('node/' . $node->id() . '/edit'); $this->assertFieldByXPath("//textarea[@name='{$body_value_key}' and @disabled='disabled']", t('This field has been disabled because you do not have sufficient permissions to edit it.'), 'Text format access denied message found.'); // Disable the text format used above. $this->disallowedFormat->disable()->save(); $this->resetFilterCaches(); // Log back in as the less privileged user and verify that the body field // is still disabled, since the less privileged user should not be able to // edit content that does not have an assigned format. $this->drupalLogin($this->webUser); $this->drupalGet('node/' . $node->id() . '/edit'); $this->assertFieldByXPath("//textarea[@name='{$body_value_key}' and @disabled='disabled']", t('This field has been disabled because you do not have sufficient permissions to edit it.'), 'Text format access denied message found.'); // Log back in as the filter administrator and verify that the body field // can be edited. $this->drupalLogin($this->filterAdminUser); $this->drupalGet('node/' . $node->id() . '/edit'); $this->assertNoFieldByXPath("//textarea[@name='{$body_value_key}' and @disabled='disabled']", NULL, 'Text format access denied message not found.'); $this->assertFieldByXPath("//select[@name='{$body_format_key}']", NULL, 'Text format selector found.'); // Verify that trying to save the node without selecting a new text format // produces an error message, and does not result in the node being saved. $old_title = $new_edit['title[0][value]']; $new_title = $this->randomMachineName(8); $edit = array(); $edit['title[0][value]'] = $new_title; $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save')); $this->assertText(t('@name field is required.', array('@name' => t('Text format'))), 'Error message is displayed.'); $this->drupalGet('node/' . $node->id()); $this->assertText($old_title, 'Old title found.'); $this->assertNoText($new_title, 'New title not found.'); // Now select a new text format and make sure the node can be saved. $edit[$body_format_key] = filter_fallback_format(); $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save')); $this->assertUrl('node/' . $node->id()); $this->assertText($new_title, 'New title found.'); $this->assertNoText($old_title, 'Old title not found.'); // Switch the text format to a new one, then disable that format and all // other formats on the site (leaving only the fallback format). $this->drupalLogin($this->adminUser); $edit = array($body_format_key => $this->allowedFormat->id()); $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save')); $this->assertUrl('node/' . $node->id()); foreach (filter_formats() as $format) { if (!$format->isFallbackFormat()) { $format->disable()->save(); } } // Since there is now only one available text format, the widget for // selecting a text format would normally not display when the content is // edited. However, we need to verify that the filter administrator still // is forced to make a conscious choice to reassign the text to a different // format. $this->drupalLogin($this->filterAdminUser); $old_title = $new_title; $new_title = $this->randomMachineName(8); $edit = array(); $edit['title[0][value]'] = $new_title; $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save')); $this->assertText(t('@name field is required.', array('@name' => t('Text format'))), 'Error message is displayed.'); $this->drupalGet('node/' . $node->id()); $this->assertText($old_title, 'Old title found.'); $this->assertNoText($new_title, 'New title not found.'); $edit[$body_format_key] = filter_fallback_format(); $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save')); $this->assertUrl('node/' . $node->id()); $this->assertText($new_title, 'New title found.'); $this->assertNoText($old_title, 'Old title not found.'); }
/** * Tests breadcrumbs on node and administrative paths. */ function testBreadCrumbs() { // Prepare common base breadcrumb elements. $home = array('' => 'Home'); $admin = $home + array('admin' => t('Administration')); $config = $admin + array('admin/config' => t('Configuration')); $type = 'article'; // Verify Taxonomy administration breadcrumbs. $trail = $admin + array('admin/structure' => t('Structure')); $this->assertBreadcrumb('admin/structure/taxonomy', $trail); $trail += array('admin/structure/taxonomy' => t('Taxonomy')); $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags', $trail); $trail += array('admin/structure/taxonomy/manage/tags' => t('Tags')); $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags/overview', $trail); $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags/add', $trail); // Verify Menu administration breadcrumbs. $trail = $admin + array('admin/structure' => t('Structure')); $this->assertBreadcrumb('admin/structure/menu', $trail); $trail += array('admin/structure/menu' => t('Menus')); $this->assertBreadcrumb('admin/structure/menu/manage/tools', $trail); $trail += array('admin/structure/menu/manage/tools' => t('Tools')); $this->assertBreadcrumb("admin/structure/menu/link/node.add_page/edit", $trail); $this->assertBreadcrumb('admin/structure/menu/manage/tools/add', $trail); // Verify Node administration breadcrumbs. $trail = $admin + array('admin/structure' => t('Structure'), 'admin/structure/types' => t('Content types')); $this->assertBreadcrumb('admin/structure/types/add', $trail); $this->assertBreadcrumb("admin/structure/types/manage/{$type}", $trail); $trail += array("admin/structure/types/manage/{$type}" => t('Article')); $this->assertBreadcrumb("admin/structure/types/manage/{$type}/fields", $trail); $this->assertBreadcrumb("admin/structure/types/manage/{$type}/display", $trail); $trail_teaser = $trail + array("admin/structure/types/manage/{$type}/display" => t('Manage display')); $this->assertBreadcrumb("admin/structure/types/manage/{$type}/display/teaser", $trail_teaser); $this->assertBreadcrumb("admin/structure/types/manage/{$type}/delete", $trail); $trail += array("admin/structure/types/manage/{$type}/fields" => t('Manage fields')); $this->assertBreadcrumb("admin/structure/types/manage/{$type}/fields/node.{$type}.body", $trail); // Verify Filter text format administration breadcrumbs. $filter_formats = filter_formats(); $format = reset($filter_formats); $format_id = $format->id(); $trail = $config + array('admin/config/content' => t('Content authoring')); $this->assertBreadcrumb('admin/config/content/formats', $trail); $trail += array('admin/config/content/formats' => t('Text formats and editors')); $this->assertBreadcrumb('admin/config/content/formats/add', $trail); $this->assertBreadcrumb("admin/config/content/formats/manage/{$format_id}", $trail); // @todo Remove this part once we have a _title_callback, see // https://www.drupal.org/node/2076085. $trail += array("admin/config/content/formats/manage/{$format_id}" => $format->label()); $this->assertBreadcrumb("admin/config/content/formats/manage/{$format_id}/disable", $trail); // Verify node breadcrumbs (without menu link). $node1 = $this->drupalCreateNode(); $nid1 = $node1->id(); $trail = $home; $this->assertBreadcrumb("node/{$nid1}", $trail); // Also verify that the node does not appear elsewhere (e.g., menu trees). $this->assertNoLink($node1->getTitle()); // Also verify that the node does not appear elsewhere (e.g., menu trees). $this->assertNoLink($node1->getTitle()); $trail += array("node/{$nid1}" => $node1->getTitle()); $this->assertBreadcrumb("node/{$nid1}/edit", $trail); // Verify that breadcrumb on node listing page contains "Home" only. $trail = array(); $this->assertBreadcrumb('node', $trail); // Verify node breadcrumbs (in menu). // Do this separately for Main menu and Tools menu, since only the // latter is a preferred menu by default. // @todo Also test all themes? Manually testing led to the suspicion that // breadcrumbs may differ, possibly due to theme overrides. $menus = array('main', 'tools'); // Alter node type menu settings. $node_type = NodeType::load($type); $node_type->setThirdPartySetting('menu_ui', 'available_menus', $menus); $node_type->setThirdPartySetting('menu_ui', 'parent', 'tools:'); $node_type->save(); foreach ($menus as $menu) { // Create a parent node in the current menu. $title = $this->randomMachineName(); $node2 = $this->drupalCreateNode(array('type' => $type, 'title' => $title, 'menu' => array('enabled' => 1, 'title' => 'Parent ' . $title, 'description' => '', 'menu_name' => $menu, 'parent' => ''))); if ($menu == 'tools') { $parent = $node2; } } // Create a Tools menu link for 'node', move the last parent node menu // link below it, and verify a full breadcrumb for the last child node. $menu = 'tools'; $edit = array('title[0][value]' => 'Root', 'link[0][uri]' => '/node'); $this->drupalPostForm("admin/structure/menu/manage/{$menu}/add", $edit, t('Save')); $menu_links = entity_load_multiple_by_properties('menu_link_content', array('title' => 'Root')); $link = reset($menu_links); $edit = array('menu[menu_parent]' => $link->getMenuName() . ':' . $link->getPluginId()); $this->drupalPostForm('node/' . $parent->id() . '/edit', $edit, t('Save and keep published')); $expected = array("node" => $link->getTitle()); $trail = $home + $expected; $tree = $expected + array('node/' . $parent->id() => $parent->menu['title']); $trail += array('node/' . $parent->id() => $parent->menu['title']); // Add a taxonomy term/tag to last node, and add a link for that term to the // Tools menu. $tags = array('Drupal' => array(), 'Breadcrumbs' => array()); $edit = array('field_tags[target_id]' => implode(',', array_keys($tags))); $this->drupalPostForm('node/' . $parent->id() . '/edit', $edit, t('Save and keep published')); // Put both terms into a hierarchy Drupal ยป Breadcrumbs. Required for both // the menu links and the terms itself, since taxonomy_term_page() resets // the breadcrumb based on taxonomy term hierarchy. $parent_tid = 0; foreach ($tags as $name => $null) { $terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $name)); $term = reset($terms); $tags[$name]['term'] = $term; if ($parent_tid) { $edit = array('parent[]' => array($parent_tid)); $this->drupalPostForm("taxonomy/term/{$term->id()}/edit", $edit, t('Save')); } $parent_tid = $term->id(); } $parent_mlid = ''; foreach ($tags as $name => $data) { $term = $data['term']; $edit = array('title[0][value]' => "{$name} link", 'link[0][uri]' => "/taxonomy/term/{$term->id()}", 'menu_parent' => "{$menu}:{$parent_mlid}", 'enabled[value]' => 1); $this->drupalPostForm("admin/structure/menu/manage/{$menu}/add", $edit, t('Save')); $menu_links = entity_load_multiple_by_properties('menu_link_content', array('title' => $edit['title[0][value]'], 'link.uri' => 'internal:/taxonomy/term/' . $term->id())); $tags[$name]['link'] = reset($menu_links); $parent_mlid = $tags[$name]['link']->getPluginId(); } // Verify expected breadcrumbs for menu links. $trail = $home; $tree = array(); // Logout the user because we want to check the active class as well, which // is just rendered as anonymous user. $this->drupalLogout(); foreach ($tags as $name => $data) { $term = $data['term']; /** @var \Drupal\menu_link_content\MenuLinkContentInterface $link */ $link = $data['link']; $link_path = $link->getUrlObject()->getInternalPath(); $tree += array($link_path => $link->getTitle()); $this->assertBreadcrumb($link_path, $trail, $term->getName(), $tree); $this->assertEscaped($parent->getTitle(), 'Tagged node found.'); // Additionally make sure that this link appears only once; i.e., the // untranslated menu links automatically generated from menu router items // ('taxonomy/term/%') should never be translated and appear in any menu // other than the breadcrumb trail. $elements = $this->xpath('//nav[@id=:menu]/descendant::a[@href=:href]', array(':menu' => 'block-bartik-tools', ':href' => Url::fromUri('base:' . $link_path)->toString())); $this->assertTrue(count($elements) == 1, "Link to {$link_path} appears only once."); // Next iteration should expect this tag as parent link. // Note: Term name, not link name, due to taxonomy_term_page(). $trail += array($link_path => $term->getName()); } // Verify breadcrumbs on user and user/%. // We need to log back in and out below, and cannot simply grant the // 'administer users' permission, since user_page() makes your head explode. user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access user profiles')); // Verify breadcrumb on front page. $this->assertBreadcrumb('<front>', array()); // Verify breadcrumb on user pages (without menu link) for anonymous user. $trail = $home; $this->assertBreadcrumb('user', $trail, t('Log in')); $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername()); // Verify breadcrumb on user pages (without menu link) for registered users. $this->drupalLogin($this->adminUser); $trail = $home; $this->assertBreadcrumb('user', $trail, $this->adminUser->getUsername()); $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername()); $trail += array('user/' . $this->adminUser->id() => $this->adminUser->getUsername()); $this->assertBreadcrumb('user/' . $this->adminUser->id() . '/edit', $trail, $this->adminUser->getUsername()); // Create a second user to verify breadcrumb on user pages again. $this->webUser = $this->drupalCreateUser(array('administer users', 'access user profiles')); $this->drupalLogin($this->webUser); // Verify correct breadcrumb and page title on another user's account pages. $trail = $home; $this->assertBreadcrumb('user/' . $this->adminUser->id(), $trail, $this->adminUser->getUsername()); $trail += array('user/' . $this->adminUser->id() => $this->adminUser->getUsername()); $this->assertBreadcrumb('user/' . $this->adminUser->id() . '/edit', $trail, $this->adminUser->getUsername()); // Verify correct breadcrumb and page title when viewing own user account. $trail = $home; $this->assertBreadcrumb('user/' . $this->webUser->id(), $trail, $this->webUser->getUsername()); $trail += array('user/' . $this->webUser->id() => $this->webUser->getUsername()); $this->assertBreadcrumb('user/' . $this->webUser->id() . '/edit', $trail, $this->webUser->getUsername()); // Create an only slightly privileged user being able to access site reports // but not administration pages. $this->webUser = $this->drupalCreateUser(array('access site reports')); $this->drupalLogin($this->webUser); // Verify that we can access recent log entries, there is a corresponding // page title, and that the breadcrumb is just the Home link (because the // user is not able to access "Administer". $trail = $home; $this->assertBreadcrumb('admin', $trail, t('Access denied')); $this->assertResponse(403); // Since the 'admin' path is not accessible, we still expect only the Home // link. $this->assertBreadcrumb('admin/reports', $trail, t('Reports')); $this->assertNoResponse(403); // Since the Reports page is accessible, that will show. $trail += array('admin/reports' => t('Reports')); $this->assertBreadcrumb('admin/reports/dblog', $trail, t('Recent log messages')); $this->assertNoResponse(403); // Ensure that the breadcrumb is safe against XSS. $this->drupalGet('menu-test/breadcrumb1/breadcrumb2/breadcrumb3'); $this->assertRaw('<script>alert(12);</script>'); $this->assertEscaped('<script>alert(123);</script>'); }
/** * Define custom prepare_translation behavior for this module's field types. * * @param $entity_type * The type of $entity. * @param $entity * The entity for the operation. * @param $field * The field structure for the operation. * @param $instance * The instance structure for $field on $entity's bundle. * @param $langcode * The language associated to $items. * @param $items * $entity->{$field['field_name']}[$langcode], or an empty array if unset. * @param $source_entity * The source entity from which field values are being copied. * @param $source_langcode * The source language from which field values are being copied. */ function hook_field_prepare_translation($entity_type, $entity, $field, $instance, $langcode, &$items, $source_entity, $source_langcode) { // If the translating user is not permitted to use the assigned text format, // we must not expose the source values. $field_name = $field['field_name']; $formats = filter_formats(); $format_id = $source_entity->{$field_name}[$source_langcode][0]['format']; if (!filter_access($formats[$format_id])) { $items = array(); } }
/** * Creates and returns a taxonomy term. * * @param array $settings * (optional) An array of values to override the following default * properties of the term: * - name: A random string. * - description: A random string. * - format: First available text format. * - vid: Vocabulary ID of self::$vocabulary object. * - langcode: LANGCODE_NOT_SPECIFIED. * Defaults to an empty array. * * @return \Drupal\taxonomy\Entity\Term * The created taxonomy term. */ protected function createTerm(array $settings = []) { $filter_formats = filter_formats(); $format = array_pop($filter_formats); $settings += ['name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'format' => $format->id(), 'vid' => $this->vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]; $term = Term::create($settings); $term->save(); return $term; }
/** * Expands an element into a base element with text format selector attached. * * The form element will be expanded into two separate form elements, one * holding the original element, and the other holding the text format * selector: * - value: Holds the original element, having its #type changed to the value * of #base_type or 'textarea' by default. * - format: Holds the text format details and the text format selection, * using the text format ID specified in #format or the user's default * format by default, if NULL. * * The resulting value for the element will be an array holding the value and * the format. For example, the value for the body element will be: * @code * $values = $form_state->getValue('body'); * $values['value'] = 'foo'; * $values['format'] = 'foo'; * @endcode * * @param array $element * The form element to process. See main class documentation for properties. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * @param array $complete_form * The complete form structure. * * @return array * The form element. */ public static function processFormat(&$element, FormStateInterface $form_state, &$complete_form) { $user = static::currentUser(); // Ensure that children appear as subkeys of this element. $element['#tree'] = TRUE; $blacklist = array('#parents', '#id', '#name', '#process', '#pre_render', '#description', '#weight', '#prefix', '#suffix', '#attached', '#processed', '#theme_wrappers'); // Move this element into sub-element 'value'. unset($element['value']); foreach (Element::properties($element) as $key) { if (!in_array($key, $blacklist)) { $element['value'][$key] = $element[$key]; } } $element['value']['#type'] = $element['#base_type']; $element['value'] += static::elementInfo()->getInfo($element['#base_type']); // Make sure the #default_value key is set, so we can use it below. $element['value'] += array('#default_value' => ''); // Turn original element into a text format wrapper. $element['#attached']['library'][] = 'filter/drupal.filter'; // Setup child container for the text format widget. $element['format'] = array('#type' => 'container', '#attributes' => array('class' => array('filter-wrapper'))); // Get a list of formats that the current user has access to. $formats = filter_formats($user); // Allow the list of formats to be restricted. if (isset($element['#allowed_formats'])) { // We do not add the fallback format here to allow the use-case of forcing // certain text formats to be used for certain text areas. In case the // fallback format is supposed to be allowed as well, it must be added to // $element['#allowed_formats'] explicitly. $formats = array_intersect_key($formats, array_flip($element['#allowed_formats'])); } if (!isset($element['#format']) && !empty($formats)) { // If no text format was selected, use the allowed format with the highest // weight. This is equivalent to calling filter_default_format(). $element['#format'] = reset($formats)->id(); } // If #allowed_formats is set, the list of formats must not be modified in // any way. Otherwise, however, if all of the following conditions are true, // remove the fallback format from the list of formats: // 1. The 'always_show_fallback_choice' filter setting has not been activated. // 2. Multiple text formats are available. // 3. The fallback format is not the default format. // The 'always_show_fallback_choice' filter setting is a hidden setting that // has no UI. It defaults to FALSE. $config = static::configFactory()->get('filter.settings'); if (!isset($element['#allowed_formats']) && !$config->get('always_show_fallback_choice')) { $fallback_format = $config->get('fallback_format'); if ($element['#format'] !== $fallback_format && count($formats) > 1) { unset($formats[$fallback_format]); } } // Prepare text format guidelines. $element['format']['guidelines'] = array('#type' => 'container', '#attributes' => array('class' => array('filter-guidelines')), '#weight' => 20); $options = array(); foreach ($formats as $format) { $options[$format->id()] = $format->label(); $element['format']['guidelines'][$format->id()] = array('#theme' => 'filter_guidelines', '#format' => $format); } $element['format']['format'] = array('#type' => 'select', '#title' => t('Text format'), '#options' => $options, '#default_value' => $element['#format'], '#access' => count($formats) > 1, '#weight' => 10, '#attributes' => array('class' => array('filter-list')), '#parents' => array_merge($element['#parents'], array('format'))); $element['format']['help'] = ['#type' => 'container', 'about' => ['#type' => 'link', '#title' => t('About text formats'), '#url' => new Url('filter.tips_all'), '#attributes' => ['target' => '_blank']], '#attributes' => ['class' => ['filter-help']], '#weight' => 0]; $all_formats = filter_formats(); $format_exists = isset($all_formats[$element['#format']]); $format_allowed = !isset($element['#allowed_formats']) || in_array($element['#format'], $element['#allowed_formats']); $user_has_access = isset($formats[$element['#format']]); $user_is_admin = $user->hasPermission('administer filters'); // If the stored format does not exist or if it is not among the allowed // formats for this textarea, administrators have to assign a new format. if ((!$format_exists || !$format_allowed) && $user_is_admin) { $element['format']['format']['#required'] = TRUE; $element['format']['format']['#default_value'] = NULL; // Force access to the format selector (it may have been denied above if // the user only has access to a single format). $element['format']['format']['#access'] = TRUE; } elseif (!$user_has_access || !$format_exists) { // Overload default values into #value to make them unalterable. $element['value']['#value'] = $element['value']['#default_value']; $element['format']['format']['#value'] = $element['format']['format']['#default_value']; // Prepend #pre_render callback to replace field value with user notice // prior to rendering. $element['value'] += array('#pre_render' => array()); array_unshift($element['value']['#pre_render'], 'filter_form_access_denied'); // Cosmetic adjustments. if (isset($element['value']['#rows'])) { $element['value']['#rows'] = 3; } $element['value']['#disabled'] = TRUE; $element['value']['#resizable'] = 'none'; // Hide the text format selector and any other child element (such as text // field's summary). foreach (Element::children($element) as $key) { if ($key != 'value') { $element[$key]['#access'] = FALSE; } } } return $element; }
/** * Returns a string or an array of randomly generated textfield values. * * @param int $num * Number of values to return. * @param bool $generate_format * Whether to generate the format of the textfield. * @param int $max_length * Maximum length of the text field. * * @return string|array * A string if only one value was to be returned, an array of strings * otherwise. */ protected static function generateValues($num, $generate_format = FALSE, $generate_summary = FALSE, $max_length = 100, $newline = TRUE) { $filter_formats = array(); if ($generate_format) { global $user; $filter_formats = array_keys(filter_formats($user)); } $values = array(); for ($i = 0; $i < $num; $i++) { $values[$i]['value'] = Utils::getRandomText($max_length); if (!$newline) { $values[$i]['value'] = str_replace(PHP_EOL, " ", $values[$i]['value']); } if ($generate_format) { $values[$i]['format'] = $filter_formats[array_rand($filter_formats)]; } if ($generate_summary) { $values[$i]['summary'] = Utils::getRandomText($max_length); } } return Utils::normalize($values); }
/** * Function to build the form * * @return void * @access public */ public function buildQuickForm() { $wysiwyg_options = array('' => ts('Textarea')) + CRM_Core_OptionGroup::values('wysiwyg_editor'); $config = CRM_Core_Config::singleton(); $extra = array(); //if not using Joomla, remove Joomla default editor option if ($config->userFramework != 'Joomla') { unset($wysiwyg_options[3]); } $drupal_wysiwyg = FALSE; if (!$config->userSystem->is_drupal || !module_exists("wysiwyg")) { unset($wysiwyg_options[4]); } else { $extra['onchange'] = ' if (this.value==4) { cj("#crm-preferences-display-form-block-wysiwyg_input_format").show(); } else { cj("#crm-preferences-display-form-block-wysiwyg_input_format").hide() }'; $formats = filter_formats(); $format_options = array(); foreach ($formats as $id => $format) { $format_options[$id] = $format->name; } $drupal_wysiwyg = TRUE; } $this->addElement('select', 'editor_id', ts('WYSIWYG Editor'), $wysiwyg_options, $extra); if ($drupal_wysiwyg) { $this->addElement('select', 'wysiwyg_input_format', ts('Input Format'), $format_options, NULL); } $editOptions = CRM_Core_OptionGroup::values('contact_edit_options', FALSE, FALSE, FALSE, 'AND v.filter = 0'); $this->assign('editOptions', $editOptions); $contactBlocks = CRM_Core_OptionGroup::values('contact_edit_options', FALSE, FALSE, FALSE, 'AND v.filter = 1'); $this->assign('contactBlocks', $contactBlocks); $nameFields = CRM_Core_OptionGroup::values('contact_edit_options', FALSE, FALSE, FALSE, 'AND v.filter = 2'); $this->assign('nameFields', $nameFields); $this->addElement('hidden', 'contact_edit_preferences', NULL, array('id' => 'contact_edit_preferences')); parent::buildQuickForm(); }