/** * {@inheritdoc} */ function setUp() { parent::setUp(); $this->installSchema('system', array('url_alias', 'router')); $this->installEntitySchema('user'); $this->installEntitySchema('entity_test'); $this->installConfig(array('field', 'language')); // Add English as a language. $english = new Language(array('id' => 'en', 'name' => 'English')); language_save($english); // Add German as a language. $german = new Language(array('id' => 'de', 'name' => 'Deutsch', 'weight' => -1)); language_save($german); // Create the test text field. entity_create('field_storage_config', array('name' => 'field_test_text', 'entity_type' => 'entity_test', 'type' => 'text'))->save(); entity_create('field_instance_config', array('entity_type' => 'entity_test', 'field_name' => 'field_test_text', 'bundle' => 'entity_test', 'translatable' => FALSE))->save(); // Create the test translatable field. entity_create('field_storage_config', array('name' => 'field_test_translatable_text', 'entity_type' => 'entity_test', 'type' => 'text'))->save(); entity_create('field_instance_config', array('entity_type' => 'entity_test', 'field_name' => 'field_test_translatable_text', 'bundle' => 'entity_test', 'translatable' => TRUE))->save(); // Create the test entity reference field. entity_create('field_storage_config', array('name' => 'field_test_entity_reference', 'entity_type' => 'entity_test', 'type' => 'entity_reference', 'settings' => array('target_type' => 'entity_test')))->save(); entity_create('field_instance_config', array('entity_type' => 'entity_test', 'field_name' => 'field_test_entity_reference', 'bundle' => 'entity_test', 'translatable' => TRUE))->save(); $entity_manager = \Drupal::entityManager(); $link_manager = new LinkManager(new TypeLinkManager(new MemoryBackend('default')), new RelationLinkManager(new MemoryBackend('default'), $entity_manager)); $chain_resolver = new ChainEntityResolver(array(new UuidResolver($entity_manager), new TargetIdResolver())); // Set up the mock serializer. $normalizers = array(new ContentEntityNormalizer($link_manager, $entity_manager, \Drupal::moduleHandler()), new EntityReferenceItemNormalizer($link_manager, $chain_resolver), new FieldItemNormalizer(), new FieldNormalizer()); $encoders = array(new JsonEncoder()); $this->serializer = new Serializer($normalizers, $encoders); }
/** * Get the module handler. * * @return \Drupal\Core\Extension\ModuleHandlerInterface * The module handler. */ protected function getModuleHandler() { if (!isset($this->moduleHandler)) { $this->moduleHandler = \Drupal::moduleHandler(); } return $this->moduleHandler; }
/** * Inserts a form element with a list of available tokens. * * @param $form * The form array to append the token list to. * @param array $types * An array of token types to use. */ public function insertTokenList(&$form, array $types = array()) { if (\Drupal::moduleHandler()->moduleExists('token')) { // Add the token tree UI. $form['token_tree'] = array( '#theme' => 'token_tree', '#token_types' => $types, '#dialog' => TRUE, '#weight' => -90, ); } else { $token_items = array(); foreach ($this->getAvailableTokens($types) as $type => $tokens) { foreach ($tokens as $name => $info) { $token_description = !empty($info['description']) ? $info['description'] : ''; $token_items[$type . ':' . $name] = "[$type:$name]" . ' - ' . $info['name'] . ': ' . $token_description; } } if (count($token_items)) { $form['tokens'] = array( '#type' => 'details', '#title' => t('Available tokens'), '#weight' => -90, ); $form['tokens']['list'] = array( '#theme' => 'item_list', '#items' => $token_items, ); } } }
/** * Tests the views_ui_autocomplete_tag function. */ public function testViewsUiAutocompleteTag() { \Drupal::moduleHandler()->loadInclude('views_ui', 'inc', 'admin'); // Save 15 views with a tag. $tags = array(); for ($i = 0; $i < 16; $i++) { $suffix = $i % 2 ? 'odd' : 'even'; $tag = 'autocomplete_tag_test_' . $suffix . $this->randomMachineName(); $tags[] = $tag; entity_create('view', array('tag' => $tag, 'id' => $this->randomMachineName()))->save(); } // Make sure just ten results are returns. $controller = ViewsUIController::create($this->container); $request = $this->container->get('request_stack')->getCurrentRequest(); $request->query->set('q', 'autocomplete_tag_test'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 10, 'Make sure the maximum amount of tag results is 10.'); // Make sure that matching by a certain prefix works. $request->query->set('q', 'autocomplete_tag_test_even'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 8, 'Make sure that only a subset is returned.'); foreach ($matches as $tag) { $this->assertTrue(array_search($tag, $tags) !== FALSE, format_string('Make sure the returned tag @tag actually exists.', array('@tag' => $tag))); } // Make sure an invalid result doesn't return anything. $request->query->set('q', $this->randomMachineName()); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 0, "Make sure an invalid tag doesn't return anything."); }
/** * Tests entity info cache after enabling a module with a dependency on an entity providing module. * * @see entity_cache_test_modules_enabled() */ function testEntityInfoCacheModulesEnabled() { \Drupal::moduleHandler()->install(array('entity_cache_test')); $entity_type = \Drupal::state()->get('entity_cache_test'); $this->assertEqual($entity_type->getLabel(), 'Entity Cache Test', 'Entity info label is correct.'); $this->assertEqual($entity_type->getStorageClass(), 'Drupal\\Core\\Entity\\EntityDatabaseStorage', 'Entity controller class info is correct.'); }
/** * Create test views from config. * * @param string $class * The name of the test class. Installs the listed test views *in order*. * @param array $modules * The module directories to look in for test views. */ public static function createTestViews($class, array $modules) { $views = array(); while ($class) { if (property_exists($class, 'testViews')) { $views = array_merge($views, $class::$testViews); } $class = get_parent_class($class); } if (!empty($views)) { $storage = \Drupal::entityManager()->getStorage('view'); $module_handler = \Drupal::moduleHandler(); foreach ($modules as $module) { $config_dir = drupal_get_path('module', $module) . '/test_views'; if (!is_dir($config_dir) || !$module_handler->moduleExists($module)) { continue; } $file_storage = new FileStorage($config_dir); $available_views = $file_storage->listAll('views.view.'); foreach ($views as $id) { $config_name = 'views.view.' . $id; if (in_array($config_name, $available_views)) { $storage->create($file_storage->read($config_name))->save(); } } } } // Rebuild the router once. \Drupal::service('router.builder')->rebuild(); }
public function query() { // This can only work if we're authenticated in. if (!\Drupal::currentUser()->isAuthenticated()) { return; } // Don't filter if we're exposed and the checkbox isn't selected. if (!empty($this->options['exposed']) && empty($this->value)) { return; } // Hey, Drupal kills old history, so nodes that haven't been updated // since HISTORY_READ_LIMIT are bzzzzzzzt outta here! $limit = REQUEST_TIME - HISTORY_READ_LIMIT; $this->ensureMyTable(); $field = "{$this->tableAlias}.{$this->realField}"; $node = $this->query->ensureTable('node_field_data', $this->relationship); $clause = ''; $clause2 = ''; if (\Drupal::moduleHandler()->moduleExists('comment')) { $ces = $this->query->ensureTable('comment_entity_statistics', $this->relationship); $clause = "OR {$ces}.last_comment_timestamp > (***CURRENT_TIME*** - {$limit})"; $clause2 = "OR {$field} < {$ces}.last_comment_timestamp"; } // NULL means a history record doesn't exist. That's clearly new content. // Unless it's very very old content. Everything in the query is already // type safe cause none of it is coming from outside here. $this->query->addWhereExpression($this->options['group'], "({$field} IS NULL AND ({$node}.changed > (***CURRENT_TIME*** - {$limit}) {$clause})) OR {$field} < {$node}.changed {$clause2}"); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $enabled_link = Link::fromTextAndUrl(t('enabled'), Url::fromRoute('system.modules_list')); $form['#attached']['library'][] = 'system/drupal.system'; $form['exclude_node_title_search'] = ['#type' => 'checkbox', '#title' => $this->t('Remove node title from search pages'), '#description' => $this->t('Select if you wish to remove title from search pages. You need to have Search module @link.', ['@link' => $enabled_link]), '#default_value' => $this->excludeNodeTitleManager->isSearchExcluded(), '#disabled' => !\Drupal::moduleHandler()->moduleExists('search')]; $form['content_type'] = ['#type' => 'fieldset', '#title' => $this->t('Exclude title by content types'), '#description' => $this->t('Define title excluding settings for each content type.'), '#collapsible' => TRUE, '#collapsed' => FALSE, '#tree' => TRUE]; foreach ($this->bundleInfo->getBundleInfo('node') as $node_type => $node_type_info) { $form['#attached']['drupalSettings']['exclude_node_title']['content_types'][$node_type] = $node_type_info['label']; $form['content_type'][$node_type]['content_type_value'] = ['#type' => 'select', '#title' => $node_type_info['label'], '#default_value' => $this->excludeNodeTitleManager->getBundleExcludeMode($node_type), '#options' => ['none' => $this->t('None'), 'all' => $this->t('All nodes...'), 'user' => $this->t('User defined nodes...')]]; $entity_view_modes = $this->entityDisplayRepository->getViewModes('node'); $modes = []; foreach ($entity_view_modes as $view_mode_name => $view_mode_info) { $modes[$view_mode_name] = $view_mode_info['label']; } $modes += ['nodeform' => $this->t('Node form')]; switch ($form['content_type'][$node_type]['content_type_value']['#default_value']) { case 'all': $title = $this->t('Exclude title from all nodes in the following view modes:'); break; case 'user defined': $title = $this->t('Exclude title from user defined nodes in the following view modes:'); break; default: $title = $this->t('Exclude from:'); } $form['content_type'][$node_type]['content_type_modes'] = ['#type' => 'checkboxes', '#title' => $title, '#default_value' => $this->excludeNodeTitleManager->getExcludedViewModes($node_type), '#options' => $modes, '#states' => ['invisible' => ['select[name="content_type[' . $node_type . '][content_type_value]"]' => ['value' => 'none']]]]; } $form['#attached']['library'][] = 'exclude_node_title/drupal.exclude_node_title.admin'; return parent::buildForm($form, $form_state); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // Invoke hook_uc_order($op = 'submit') to test to make sure the order can // be completed... used for auto payment in uc_credit.module. $order = $form_state->get('uc_order'); $error = FALSE; // Invoke it on a per-module basis instead of all at once. $module_handler = \Drupal::moduleHandler(); foreach ($module_handler->getImplementations('uc_order') as $module) { $function = $module . '_uc_order'; if (function_exists($function)) { // $order must be passed by reference. $result = $function('submit', $order, NULL); $msg_type = 'status'; if ($result[0]['pass'] === FALSE) { $error = TRUE; $msg_type = 'error'; } if (!empty($result[0]['message'])) { drupal_set_message($result[0]['message'], $msg_type); } // Stop invoking the hooks if there was an error. if ($error) { break; } } } if ($error) { $form_state->setRedirect('uc_cart.checkout_review'); } else { unset($_SESSION['uc_checkout'][$order->id()]['do_review']); $_SESSION['uc_checkout'][$order->id()]['do_complete'] = TRUE; $form_state->setRedirect('uc_cart.checkout_complete'); } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('uc_product.settings'); $form['product-settings'] = array('#type' => 'vertical_tabs'); $form['product'] = array('#type' => 'details', '#title' => $this->t('Product settings'), '#group' => 'product-settings', '#weight' => -10); $form['product']['empty'] = array('#markup' => t('There are currently no settings choices for your products. When enabled, the Cart module and other modules that provide product features (such as Role assignment and File downloads) will add settings choices here.')); $form['#submit'][] = array($this, 'submitForm'); if (\Drupal::moduleHandler()->moduleExists('uc_cart')) { unset($form['product']['empty']); $form['product']['uc_product_add_to_cart_qty'] = array('#type' => 'checkbox', '#title' => $this->t('Display an optional quantity field in the <em>Add to Cart</em> form.'), '#default_value' => $config->get('add_to_cart_qty')); $form['product']['uc_product_update_node_view'] = array('#type' => 'checkbox', '#title' => $this->t('Update product display based on customer selections'), '#default_value' => $config->get('update_node_view'), '#description' => $this->t('Check this box to dynamically update the display of product information such as display-price or weight based on customer input on the add-to-cart form (e.g. selecting a particular attribute option).')); } foreach (\Drupal::moduleHandler()->invokeAll('uc_product_feature') as $feature) { unset($form['product']['empty']); if (isset($feature['settings']) && function_exists($feature['settings'])) { $form[$feature['id']] = array('#type' => 'details', '#title' => $this->t('@feature settings', ['@feature' => $feature['title']]), '#group' => 'product-settings'); $form[$feature['id']] += $feature['settings']([], $form_state); if (function_exists($feature['settings'] . '_validate')) { $form['#validate'][] = $feature['settings'] . '_validate'; } if (function_exists($feature['settings'] . '_submit')) { $form['#submit'][] = $feature['settings'] . '_submit'; } } } return parent::buildForm($form, $form_state); }
/** * {@inheritdoc} */ public function alterForm(&$form) { $config = $this->getConfiguration(); // Add prefix $form['lb'] = array('#type' => 'textfield', '#title' => t('Label'), '#size' => '10', '#default_value' => $config['lb']); // Add prefix $form['prefix'] = array('#type' => 'textfield', '#title' => t('Prefix'), '#size' => '100', '#description' => t('You can enter any html in here.'), '#default_value' => isset($config['prefix']) ? $config['prefix'] : '', '#prefix' => '<div class="field-prefix">', '#suffix' => '</div>'); $wrappers = array('lbw' => array('title' => t('Label wrapper')), 'ow' => array('title' => t('Outer wrapper')), 'fis' => array('title' => t('Field items')), 'fi' => array('title' => t('Field item'))); foreach ($wrappers as $wrapper_key => $value) { $form[$wrapper_key] = array('#type' => 'checkbox', '#title' => $value['title'], '#prefix' => '<div class="ft-group ' . $wrapper_key . '">', '#default_value' => $config[$wrapper_key]); $form[$wrapper_key . '-el'] = array('#type' => 'textfield', '#title' => t('Element'), '#size' => '10', '#description' => t('E.g. div, span, h2 etc.'), '#default_value' => $config[$wrapper_key . '-el'], '#states' => array('visible' => array(':input[name$="[' . $wrapper_key . ']"]' => array('checked' => TRUE)))); $form[$wrapper_key . '-cl'] = array('#type' => 'textfield', '#title' => t('Classes'), '#size' => '10', '#default_value' => $config[$wrapper_key . '-cl'], '#description' => t('E.g.') . ' field-expert', '#states' => array('visible' => array(':input[name$="[' . $wrapper_key . ']"]' => array('checked' => TRUE)))); $form[$wrapper_key . '-at'] = array('#type' => 'textfield', '#title' => t('Attributes'), '#size' => '20', '#default_value' => $config[$wrapper_key . '-at'], '#description' => t('E.g. name="anchor"'), '#states' => array('visible' => array(':input[name$="[' . $wrapper_key . ']"]' => array('checked' => TRUE)))); // Hide colon. if ($wrapper_key == 'lbw') { $form['lb-col'] = array('#type' => 'checkbox', '#title' => t('Show label colon'), '#default_value' => $config['lb-col'], '#attributes' => array('class' => array('colon-checkbox')), '#states' => array('visible' => array(':input[name$="[' . $wrapper_key . ']"]' => array('checked' => TRUE)))); } if ($wrapper_key != 'lbw') { $form[$wrapper_key . '-def-at'] = array('#type' => 'checkbox', '#title' => t('Add default attributes'), '#default_value' => $config[$wrapper_key . '-def-at'], '#suffix' => $wrapper_key == 'ow' ? '' : '</div><div class="clearfix"></div>', '#states' => array('visible' => array(':input[name$="[' . $wrapper_key . ']"]' => array('checked' => TRUE)))); } else { $form['ft'][$wrapper_key . '-def-at'] = array('#markup' => '</div><div class="clearfix"></div>'); } // Default classes for outer wrapper. if ($wrapper_key == 'ow') { $form[$wrapper_key . '-def-cl'] = array('#type' => 'checkbox', '#title' => t('Add default classes'), '#default_value' => $config[$wrapper_key . '-def-cl'], '#suffix' => '</div><div class="clearfix"></div>', '#states' => array('visible' => array(':input[name$="[' . $wrapper_key . ']"]' => array('checked' => TRUE)))); } } // Add suffix $form['suffix'] = array('#type' => 'textfield', '#title' => t('Suffix'), '#size' => '100', '#description' => t('You can enter any html in here.'), '#default_value' => isset($config['suffix']) ? $config['suffix'] : '', '#prefix' => '<div class="field-suffix">', '#suffix' => '</div>'); // Token support. if (\Drupal::moduleHandler()->moduleExists('token')) { $form['tokens'] = array('#title' => t('Tokens'), '#type' => 'container', '#states' => array('invisible' => array('input[name="use_token"]' => array('checked' => FALSE)))); $form['tokens']['help'] = array('#theme' => 'token_tree', '#token_types' => 'all', '#global_types' => FALSE, '#dialog' => TRUE); } }
/** * {@inheritdoc} */ public function getOperations(EntityInterface $entity) { $operations = parent::getOperations($entity); $destination = drupal_get_destination(); $default = $entity->isDefault(); $id = $entity->id(); // Get CSRF token service. $token_generator = \Drupal::csrfToken(); // @TODO: permission checks. if ($entity->status() && !$default) { $operations['disable'] = array('title' => $this->t('Disable'), 'url' => Url::fromRoute('domain.inline_action', array('op' => 'disable', 'domain' => $id)), 'weight' => 50); } elseif (!$default) { $operations['enable'] = array('title' => $this->t('Enable'), 'url' => Url::fromRoute('domain.inline_action', array('op' => 'enable', 'domain' => $id)), 'weight' => 40); } if (!$default) { $operations['default'] = array('title' => $this->t('Make default'), 'url' => Url::fromRoute('domain.inline_action', array('op' => 'default', 'domain' => $id)), 'weight' => 30); $operations['delete'] = array('title' => $this->t('Delete'), 'url' => Url::fromRoute('entity.domain.delete_form', array('domain' => $id)), 'weight' => 20); } // @TODO: inject this service? $operations += \Drupal::moduleHandler()->invokeAll('domain_operations', array($entity)); foreach ($operations as $key => $value) { if (isset($value['query']['token'])) { $operations[$key]['query'] += $destination; } } $default = \Drupal::service('domain.loader')->loadDefaultDomain(); // Deleting the site default domain is not allowed. if ($id == $default->id()) { unset($operations['delete']); } return $operations; }
function testFieldPermissions() { $fields = array( 'fields[body][region]' => 'right', 'fields[test_field][region]' => 'left', ); $this->config('ds_extras.settings')->set('field_permissions', TRUE)->save(); \Drupal::moduleHandler()->resetImplementations(); $this->dsSelectLayout(); $this->dsConfigureUI($fields); // Create a node. $settings = array('type' => 'article'); $node = $this->drupalCreateNode($settings); $this->drupalGet('node/' . $node->id()); $this->assertRaw('group-right', 'Template found (region right)'); $this->assertNoText('Test code field on node ' . $node->id(), 'Test code field not found'); // Give permissions. $edit = array( 'authenticated[view node_author on node]' => 1, 'authenticated[view test_field on node]' => 1, ); $this->drupalPostForm('admin/people/permissions', $edit, t('Save permissions')); $this->drupalGet('node/' . $node->id()); $this->assertRaw('group-left', 'Template found (region left)'); $this->assertText('Test field plugin on node ' . $node->id(), 'Test field plugin found'); }
/** * {@inheritdoc} */ public function endpoint($hash) { $return = 0; if (!empty($_POST)) { $data = $_POST['data']; $type = $_POST['type']; switch ($type) { case 'unsubscribe': case 'profile': case 'cleaned': mailchimp_get_memberinfo($data['list_id'], $data['email'], TRUE); break; case 'upemail': mailchimp_cache_clear_member($data['list_id'], $data['old_email']); mailchimp_get_memberinfo($data['list_id'], $data['new_email'], TRUE); break; case 'campaign': mailchimp_cache_clear_list_activity($data['list_id']); mailchimp_cache_clear_campaign($data['id']); break; } // Allow other modules to act on a webhook. \Drupal::moduleHandler()->invokeAll('mailchimp_process_webhook', array($type, $data)); // Log event. \Drupal::logger('mailchimp')->info('Webhook type {type} has been processed.', array('type' => $type)); $return = 1; } // TODO: There should be a better way of doing this. // D8 routing doesn't seem to allow us to return a single character // or string from a controller. echo $return; exit; }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); /** @var \Drupal\commerce_product\Entity\ProductVariationTypeInterface $variation_type */ $variation_type = $this->entity; $form['label'] = ['#type' => 'textfield', '#title' => $this->t('Label'), '#maxlength' => 255, '#default_value' => $variation_type->label(), '#required' => TRUE]; $form['id'] = ['#type' => 'machine_name', '#default_value' => $variation_type->id(), '#machine_name' => ['exists' => '\\Drupal\\commerce_product\\Entity\\ProductVariationType::load'], '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH]; $form['generateTitle'] = ['#type' => 'checkbox', '#title' => t('Generate variation titles based on attribute values.'), '#default_value' => $variation_type->shouldGenerateTitle()]; if (\Drupal::moduleHandler()->moduleExists('commerce_order')) { // Prepare a list of line item types used to purchase product variations. $line_item_type_storage = $this->entityTypeManager->getStorage('commerce_line_item_type'); $line_item_types = $line_item_type_storage->loadMultiple(); $line_item_types = array_filter($line_item_types, function ($line_item_type) { return $line_item_type->getPurchasableEntityTypeId() == 'commerce_product_variation'; }); $line_item_types = array_map(function ($line_item_type) { return $line_item_type->label(); }, $line_item_types); $form['lineItemType'] = ['#type' => 'select', '#title' => $this->t('Line item type'), '#default_value' => $variation_type->getLineItemTypeId(), '#options' => $line_item_types, '#empty_value' => '', '#required' => TRUE]; } if ($this->moduleHandler->moduleExists('language')) { $form['language'] = ['#type' => 'details', '#title' => $this->t('Language settings'), '#group' => 'additional_settings']; $form['language']['language_configuration'] = ['#type' => 'language_configuration', '#entity_information' => ['entity_type' => 'commerce_product_variation', 'bundle' => $variation_type->id()], '#default_value' => ContentLanguageSettings::loadByEntityTypeBundle('commerce_product_variation', $variation_type->id())]; $form['#submit'][] = 'language_configuration_element_submit'; } return $this->protectBundleIdElement($form); }
public function __construct($node, $submission) { $this->submission = $submission; $this->node = $node; $this->webform = new Webform($node); $this->submitted = $submission->submitted; $this->remote_addr = $submission->remote_addr; $this->data = array(); if (!isset($submission->tracking)) { $submission->tracking = (object) array(); if (\Drupal::moduleHandler()->moduleExists('webform_tracking') && isset($submission->sid)) { webform_tracking_load($submission); } } // Some components like checkboxes and fieldsets may have no values // We want to return NULL in that case instead of throwing a notice. $webform4 = Webform::is_webform4(); foreach (array_keys($this->node->webform['components']) as $cid) { if (isset($this->submission->data[$cid])) { $this->data[$cid] = $webform4 ? $this->submission->data[$cid] : $this->submission->data[$cid]['value']; } else { $this->data[$cid] = array(NULL); } } }
/** * Tests field item attributes. */ public function testFieldItemAttributes() { // Make sure the test field will be rendered. entity_get_display('entity_test', 'entity_test', 'default')->setComponent('field_test_text', array('type' => 'text_default'))->save(); // Create an entity and save test value in field_test_text. $test_value = $this->randomMachineName(); $entity = entity_create('entity_test'); $entity->field_test_text = $test_value; $entity->save(); // Browse to the entity and verify that the attribute is rendered in the // field item HTML markup. $this->drupalGet('entity_test/' . $entity->id()); $xpath = $this->xpath('//div[@data-field-item-attr="foobar" and text()=:value]', array(':value' => $test_value)); $this->assertTrue($xpath, 'The field item attribute has been found in the rendered output of the field.'); // Enable the RDF module to ensure that two modules can add attributes to // the same field item. \Drupal::moduleHandler()->install(array('rdf')); $this->resetAll(); // Set an RDF mapping for the field_test_text field. This RDF mapping will // be turned into RDFa attributes in the field item output. $mapping = rdf_get_mapping('entity_test', 'entity_test'); $mapping->setFieldMapping('field_test_text', array('properties' => array('schema:text')))->save(); // Browse to the entity and verify that the attributes from both modules // are rendered in the field item HTML markup. $this->drupalGet('entity_test/' . $entity->id()); $xpath = $this->xpath('//div[@data-field-item-attr="foobar" and @property="schema:text" and text()=:value]', array(':value' => $test_value)); $this->assertTrue($xpath, 'The field item attributes from both modules have been found in the rendered output of the field.'); }
/** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { /* Settings form after "manage form display" page, valid for one content type */ $field_settings = $this->getFieldSettings(); $settings = $this->getSettings(); $values = array(); foreach ($settings as $vkey => $vval) { $values[$vkey] = $vval; if (isset($field_settings[$vkey]) && is_string($vval) && (empty($vval) && 0 !== strcmp('0', $vval))) { $values[$vkey] = $field_settings[$vkey]; } } $element['width'] = array('#type' => 'textfield', '#title' => t('width of an iframe'), '#default_value' => $values['width'], '#description' => t('iframes need fix width and height, only numbers are allowed.'), '#maxlength' => 4, '#size' => 4, '#required' => TRUE); $element['height'] = array('#type' => 'textfield', '#title' => t('height of an iframe'), '#default_value' => $values['height'], '#description' => t('iframes need fix width and height, only numbers are allowed.'), '#maxlength' => 4, '#size' => 4, '#required' => TRUE); $element['class'] = array('#type' => 'textfield', '#title' => t('Additional CSS Class'), '#default_value' => $values['class'], '#description' => t('When output, this iframe will have this class attribute. Multiple classes should be separated by spaces.')); $element['expose_class'] = array('#type' => 'checkbox', '#title' => t('Expose Additional CSS Class'), '#default_value' => $values['expose_class'], '#description' => t('Allow author to specify an additional class attribute for this iframe.')); $element['frameborder'] = array('#type' => 'select', '#title' => t('Frameborder'), '#options' => array('0' => t('no frameborder'), '1' => t('show frameborder')), '#default_value' => $values['frameborder'], '#description' => t('Frameborder is the border arround the iframe. Mostly people want it silent, so the default value for frameborder is 0 = no.')); $element['scrolling'] = array('#type' => 'select', '#title' => t('Scrolling'), '#options' => array('auto' => t('Scrolling automatic'), 'no' => t('Scrolling disabled'), 'yes' => t('Scrolling enabled')), '#default_value' => $values['scrolling'], '#description' => t('Scrollbars help the user to reach all iframe content despite the real height of the iframe content. Please disable it only if You know what You are doing.')); $element['transparency'] = array('#type' => 'select', '#title' => t('Transparency'), '#options' => array('0' => t('no transparency'), '1' => t('allow transparency')), '#default_value' => $values['transparency'], '#description' => t('Allow transparency per CSS in the outer iframe tag. You have to set background-color:transparent in Your IFrame too for the body tag!')); $element['tokensupport'] = array('#type' => 'select', '#title' => t('Token Support'), '#options' => array('0' => t('no tokens allowed'), '1' => t('tokens only in title field'), '2' => t('tokens for title and url field')), '#default_value' => $values['tokensupport'], '#description' => t('Are tokens allowed for users to use in title or url field?')); if (!\Drupal::moduleHandler()->moduleExists('token')) { $element['tokensupport']['#description'] .= ' ' . t('Attention: token module is not enabled currently!'); } return $element; }
/** * {@inheritdoc} */ public function getProcess() { if (!$this->init) { $this->init = TRUE; $definition['source'] = ['entity_type' => 'user', 'ignore_map' => TRUE] + $this->source; $definition['destination']['plugin'] = 'null'; if (\Drupal::moduleHandler()->moduleExists('field')) { $definition['source']['plugin'] = 'd7_field_instance'; $field_migration = new Migration([], uniqid(), $definition); foreach ($field_migration->getSourcePlugin() as $row) { $field_name = $row->getSourceProperty('field_name'); $this->process[$field_name] = $field_name; } } try { $definition['source']['plugin'] = 'profile_field'; $profile_migration = new Migration([], uniqid(), $definition); // Ensure that Profile is enabled in the source DB. $profile_migration->checkRequirements(); foreach ($profile_migration->getSourcePlugin() as $row) { $name = $row->getSourceProperty('name'); $this->process[$name] = $name; } } catch (RequirementsException $e) { // The checkRequirements() call will fail when the profile module does // not exist on the source site. } } return parent::getProcess(); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, OrderInterface $order) { $paypal_config = $this->config('uc_paypal.settings'); if (\Drupal::moduleHandler()->moduleExists('uc_quote') && $paypal_config->get('ec_review_shipping') && $order->isShippable()) { uc_checkout_pane_quotes('prepare', $order, NULL); $order->line_items = $order->getLineItems(); $order->save(); $result = uc_checkout_pane_quotes('view', $order, NULL); $form['panes']['quotes'] = array('#type' => 'fieldset', '#title' => $this->t('Shipping cost')); $form['panes']['quotes'] += $result['contents']; unset($form['panes']['quotes']['quote_button']); $form['shippable'] = array('#type' => 'value', '#value' => 'true'); } if ($paypal_config->get('ec_review_company')) { $form['delivery_company'] = array('#type' => 'textfield', '#title' => $this->t('Company'), '#description' => $order->isShippable() ? $this->t('Leave blank if shipping to a residence.') : '', '#default_value' => $order->delivery_company); } if ($paypal_config->get('ec_review_phone')) { $form['delivery_phone'] = array('#type' => 'textfield', '#title' => $this->t('Contact phone number'), '#default_value' => $order->delivery_phone, '#size' => 24); } if ($paypal_config->get('ec_review_comment')) { $form['order_comments'] = array('#type' => 'textarea', '#title' => $this->t('Order comments'), '#description' => $this->t('Special instructions or notes regarding your order.')); } if (empty($form)) { $this->redirect('uc_cart.ec_submit'); } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Continue checkout')); return $form; }
private function configImport($io, StorageComparer $storage_comparer) { $config_importer = new ConfigImporter($storage_comparer, \Drupal::service('event_dispatcher'), \Drupal::service('config.manager'), \Drupal::lock(), \Drupal::service('config.typed'), \Drupal::moduleHandler(), \Drupal::service('module_installer'), \Drupal::service('theme_handler'), \Drupal::service('string_translation')); if ($config_importer->alreadyImporting()) { $io->success($this->trans('commands.config.import.messages.already-imported')); } else { try { if ($config_importer->validate()) { $sync_steps = $config_importer->initialize(); foreach ($sync_steps as $step) { $context = array(); do { $config_importer->doSyncStep($step, $context); } while ($context['finished'] < 1); } } } catch (ConfigImporterException $e) { $message = 'The import failed due for the following reasons:' . "\n"; $message .= implode("\n", $config_importer->getErrors()); $io->error(sprintf($this->trans('commands.site.import.local.messages.error-writing'), $message)); } catch (\Exception $e) { $io->error(sprintf($this->trans('commands.site.import.local.messages.error-writing'), $e->getMessage())); } } }
/** * @todo . */ public function messageHandler() { if (!isset($_POST['serviceKey']) || !nodejs_is_valid_service_key($_POST['serviceKey'])) { return new JsonResponse(array('error' => 'Invalid service key.')); } if (!isset($_POST['messageJson'])) { return new JsonResponse(array('error' => 'No message.')); } $message = Json::decode($_POST['messageJson']); $response = array(); switch ($message['messageType']) { case 'authenticate': $response = nodejs_auth_check($message); break; case 'userOffline': nodejs_user_set_offline($message['uid']); break; default: $handlers = array(); foreach (module_implements('nodejs_message_callback') as $module) { $function = $module . '_nodejs_message_callback'; $handlers += $function($message['messageType']); } foreach ($handlers as $callback) { $callback($message, $response); } } \Drupal::moduleHandler()->alter('nodejs_message_response', $response, $message); return new JsonResponse($response ? $response : array('error' => 'Not implemented')); }
/** * Overrides Mollom::__construct(). * * This class accounts for multiple scenarios: * - Straight low-level requests against the testing API from a custom script, * caring for API keys on its own. * - Whenever the testing mode is enabled (either through the module's * settings page or by changing the testing_mode system variable), * the client requires valid testing API keys to perform any calls. Testing * API keys are different to production API keys, need to be created first, * and may vanish at any time (whenever the testing API server is * redeployed). Since they are different, the class stores them in different * system variables. Since they can vanish at any time, the class verifies * the keys upon every instantiation, and automatically creates new testing * API keys if necessary. * - Some automated unit tests attempt to verify that authentication errors * are handled correctly by the class' error handling. The automatic * creation and recovery of testing API keys would break those assertions, * so said tests can disable the behavior by preemptively setting * $createKeys or the 'mollom.testing_create_keys' state variable to FALSE, * and manually create testing API keys (once). * * Constructor. * @param ConfigFactory $config_factory * @param ClientInterface $http_client * * @see Mollom::__construct(). */ public function __construct(ConfigFactory $config_factory, ClientInterface $http_client) { $this->config = $config_factory->get('mollom.settings'); // Some tests are verifying the production behavior of e.g. setting up API // keys, in which testing mode is NOT enabled and the test creates fake // "production" API keys on the local fake server on its own. This special // override must only be possible when executing tests. // @todo Add global test_info as condition? $testing_mode = $this->config->get('test_mode.enabled'); $module_exists = \Drupal::moduleHandler()->moduleExists('mollom_test_server'); if ($module_exists && !$testing_mode) { // Disable authentication error auto-recovery. $this->createKeys = FALSE; } else { // Do not destroy production variables when testing mode is enabled. $this->configuration_map['publicKey'] = 'test_mode.keys.public'; $this->configuration_map['privateKey'] = 'test_mode.keys.private'; $this->configuration_map['server'] = 'test_mode.api_endpoint'; } // Load and set publicKey and privateKey configuration values. parent::__construct($config_factory, $http_client); // Unless pre-set, determine whether API keys should be auto-created. if (!isset($this->createKeys)) { $this->createKeys = \Drupal::state()->get('mollom.testing_create_keys') ?: TRUE; } // Testing can require additional time. $this->requestTimeout = $this->config->get('connection_timeout_seconds', 3) + 10; }
/** * Get subscription status from the Acquia Network, and store the result. * * This check also sends a heartbeat to the Acquia Network unless * $params['no_heartbeat'] == 1. * * @param array $params * * @return FALSE, integer (error number), or subscription data. */ static function update($params = array()) { $config = \Drupal::configFactory()->getEditable('acquia_connector.settings'); $current_subscription = $config->get('subscription_data'); $subscription = FALSE; if (!self::hasCredentials()) { // If there is not an identifier or key, delete any old subscription data. $config->clear('subscription_data')->set('subscription_data', ['active' => FALSE])->save(); } else { // Get our subscription data try { $subscription = \Drupal::service('acquia_connector.client')->getSubscription($config->get('identifier'), $config->get('key'), $params); } catch (ConnectorException $e) { switch ($e->getCustomMessage('code')) { case static::NOT_FOUND: case static::EXPIRED: // Fall through since these values are stored and used by // acquia_search_acquia_subscription_status() $subscription = $e->getCustomMessage('code'); break; default: // Likely server error (503) or connection timeout (-110) so leave // current subscription in place. _acquia_agent_request() logged an // error message. return $current_subscription; } } if ($subscription) { \Drupal::moduleHandler()->invokeAll('acquia_subscription_status', [$subscription]); $config->set('subscription_data', $subscription)->save(); } } return $subscription; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $field_key = '') { $form = parent::buildForm($form, $form_state, $field_key); $field = $this->field; $form['content'] = array( '#type' => 'text_format', '#title' => t('Field content'), '#default_value' => isset($field['properties']['content']['value']) ? $field['properties']['content']['value'] : '', '#format' => isset($field['properties']['content']['format']) ? $field['properties']['content']['format'] : 'plain_text', '#base_type' => 'textarea', '#required' => TRUE, ); // Token support. if (\Drupal::moduleHandler()->moduleExists('token')) { $form['tokens'] = array( '#title' => t('Tokens'), '#type' => 'container', '#states' => array( 'invisible' => array( 'input[name="use_token"]' => array('checked' => FALSE), ), ), ); $form['tokens']['help'] = array( '#theme' => 'token_tree', '#token_types' => 'all', '#global_types' => FALSE, '#dialog' => TRUE, ); } return $form; }
/** * Returns the module handler. * * @return \Drupal\Core\Extension\ModuleHandlerInterface * The module handler. */ protected function moduleHandler() { if (!$this->moduleHandler) { $this->moduleHandler = \Drupal::moduleHandler(); } return $this->moduleHandler; }
/** * @param ConsoleCommandEvent $event */ public function validateDependencies(ConsoleCommandEvent $event) { /** * @var \Drupal\AppConsole\Command\Command $command */ $command = $event->getCommand(); $output = $event->getOutput(); $application = $command->getApplication(); $messageHelper = $application->getHelperSet()->get('message'); /** * @var TranslatorHelper */ $translatorHelper = $application->getHelperSet()->get('translator'); if (!$command instanceof Command) { return; } $dependencies = $command->getDependencies(); if ($dependencies) { foreach ($dependencies as $dependency) { if (\Drupal::moduleHandler()->moduleExists($dependency) === false) { $errorMessage = sprintf($translatorHelper->trans('commands.common.errors.module-dependency'), $dependency); $messageHelper->showMessage($output, $errorMessage, 'error'); $event->disableCommand(); } } } }
/** * Tests Standard installation profile. */ function testStandard() { $this->drupalGet(''); $this->assertLink(t('Contact')); $this->clickLink(t('Contact')); $this->assertResponse(200); // Test anonymous user can access 'Main navigation' block. $admin = $this->drupalCreateUser(array('administer blocks', 'post comments', 'skip comment approval')); $this->drupalLogin($admin); // Configure the block. $this->drupalGet('admin/structure/block/add/system_menu_block:main/bartik'); $this->drupalPostForm(NULL, array('region' => 'sidebar_first', 'id' => 'main_navigation'), t('Save block')); // Verify admin user can see the block. $this->drupalGet(''); $this->assertText('Main navigation'); // Verify we have role = aria on system_powered_by and system_help_block // blocks. $this->drupalGet('admin/structure/block'); $elements = $this->xpath('//div[@role=:role and @id=:id]', array(':role' => 'complementary', ':id' => 'block-bartik-help')); $this->assertEqual(count($elements), 1, 'Found complementary role on help block.'); $this->drupalGet(''); $elements = $this->xpath('//div[@role=:role and @id=:id]', array(':role' => 'complementary', ':id' => 'block-bartik-powered')); $this->assertEqual(count($elements), 1, 'Found complementary role on powered by block.'); // Verify anonymous user can see the block. $this->drupalLogout(); $this->assertText('Main navigation'); // Ensure comments don't show in the front page RSS feed. // Create an article. $node = $this->drupalCreateNode(array('type' => 'article', 'title' => 'Foobar', 'promote' => 1, 'status' => 1)); // Add a comment. $this->drupalLogin($admin); $this->drupalGet('node/1'); $this->drupalPostForm(NULL, array('subject[0][value]' => 'Barfoo', 'comment_body[0][value]' => 'Then she picked out two somebodies, Sally and me'), t('Save')); // Fetch the feed. $this->drupalGet('rss.xml'); $this->assertText('Foobar'); $this->assertNoText('Then she picked out two somebodies, Sally and me'); // Now we have all configuration imported, test all of them for schema // conformance. Ensures all imported default configuration is valid when // standard profile modules are enabled. $names = $this->container->get('config.storage')->listAll(); $factory = $this->container->get('config.factory'); /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */ $typed_config = $this->container->get('config.typed'); foreach ($names as $name) { $config = $factory->get($name); $this->assertConfigSchema($typed_config, $name, $config->get()); } // Ensure that configuration from the Standard profile is not reused when // enabling a module again since it contains configuration that can not be // installed. For example, editor.editor.basic_html is editor configuration // that depends on the ckeditor module. The ckeditor module can not be // installed before the editor module since it depends on the editor module. // The installer does not have this limitation since it ensures that all of // the install profiles dependencies are installed before creating the // editor configuration. \Drupal::moduleHandler()->uninstall(array('editor', 'ckeditor')); $this->rebuildContainer(); \Drupal::moduleHandler()->install(array('editor')); }
/** * Test availability of main content: Drupal falls back to SimplePageVariant. */ function testMainContentFallback() { $edit = array(); // Uninstall the block module. $edit['uninstall[block]'] = 'block'; $this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall')); $this->drupalPostForm(NULL, NULL, t('Uninstall')); $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.'); $this->rebuildContainer(); $this->assertFalse(\Drupal::moduleHandler()->moduleExists('block'), 'Block module uninstall.'); // When Block module is not installed and BlockPageVariant is not available, // Drupal should fall back to SimplePageVariant. Both for the admin and the // front-end theme. $this->drupalGet('admin/config/system/site-information'); $this->assertField('site_name', 'Fallback to SimplePageVariant works for admin theme.'); $this->drupalGet('system-test/main-content-fallback'); $this->assertText(t('Content to test main content fallback'), 'Fallback to SimplePageVariant works for front-end theme.'); // Request a user* page and see if it is displayed. $this->drupalLogin($this->webUser); $this->drupalGet('user/' . $this->webUser->id() . '/edit'); $this->assertField('mail', 'User interface still available.'); // Enable the block module again. $this->drupalLogin($this->adminUser); $edit = array(); $edit['modules[Core][block][enable]'] = 'block'; $this->drupalPostForm('admin/modules', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.'); $this->rebuildContainer(); $this->assertTrue(\Drupal::moduleHandler()->moduleExists('block'), 'Block module re-enabled.'); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { module_load_include('inc', 'pathauto'); $config = $this->config('pathauto.settings'); $form = array(); $form['verbose'] = array('#type' => 'checkbox', '#title' => t('Verbose'), '#default_value' => $config->get('verbose'), '#description' => t('Display alias changes (except during bulk updates).')); $form['separator'] = array('#type' => 'textfield', '#title' => t('Separator'), '#size' => 1, '#maxlength' => 1, '#default_value' => $config->get('separator'), '#description' => t('Character used to separate words in titles. This will replace any spaces and punctuation characters. Using a space or + character can cause unexpected results.')); $form['case'] = array('#type' => 'radios', '#title' => t('Character case'), '#default_value' => $config->get('case'), '#options' => array(self::CASE_LEAVE_ASIS => t('Leave case the same as source token values.'), self::CASE_LOWER => t('Change to lower case'))); $max_length = \Drupal::service('pathauto.alias_storage_helper')->getAliasSchemaMaxlength(); $form['max_length'] = array('#type' => 'number', '#title' => t('Maximum alias length'), '#size' => 3, '#maxlength' => 3, '#default_value' => $config->get('max_length'), '#min' => 1, '#max' => $max_length, '#description' => t('Maximum length of aliases to generate. 100 is the recommended length. @max is the maximum possible length. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => $this->getUrlGenerator()->generateFromPath('admin/help/pathauto'), '@max' => $max_length))); $form['max_component_length'] = array('#type' => 'number', '#title' => t('Maximum component length'), '#size' => 3, '#maxlength' => 3, '#default_value' => $config->get('max_component_length'), '#min' => 1, '#max' => $max_length, '#description' => t('Maximum text length of any component in the alias (e.g., [title]). 100 is the recommended length. @max is the maximum possible length. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => $this->getUrlGenerator()->generateFromPath('admin/help/pathauto'), '@max' => $max_length))); $description = t('What should Pathauto do when updating an existing content item which already has an alias?'); if (\Drupal::moduleHandler()->moduleExists('redirect')) { $description .= ' ' . t('The <a href="!url">Redirect module settings</a> affect whether a redirect is created when an alias is deleted.', array('!url' => \Drupal::url('redirect.settings'))); } else { $description .= ' ' . t('Considering installing the <a href="!url">Redirect module</a> to get redirects when your aliases change.', array('!url' => 'http://drupal.org/project/redirect')); } $form['update_action'] = array('#type' => 'radios', '#title' => t('Update action'), '#default_value' => $config->get('update_action'), '#options' => array(PathautoManagerInterface::UPDATE_ACTION_NO_NEW => t('Do nothing. Leave the old alias intact.'), PathautoManagerInterface::UPDATE_ACTION_LEAVE => t('Create a new alias. Leave the existing alias functioning.'), PathautoManagerInterface::UPDATE_ACTION_DELETE => t('Create a new alias. Delete the old alias.')), '#description' => $description); $form['transliterate'] = array('#type' => 'checkbox', '#title' => t('Transliterate prior to creating alias'), '#default_value' => $config->get('transliterate'), '#description' => t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the US-ASCII alphabet? Transliteration is handled by the Transliteration module.')); $form['reduce_ascii'] = array('#type' => 'checkbox', '#title' => t('Reduce strings to letters and numbers'), '#default_value' => $config->get('reduce_ascii'), '#description' => t('Filters the new alias to only letters and numbers found in the ASCII-96 set.')); $form['ignore_words'] = array('#type' => 'textarea', '#title' => t('Strings to Remove'), '#default_value' => $config->get('ignore_words'), '#description' => t('Words to strip out of the URL alias, separated by commas. Do not use this to remove punctuation.'), '#wysiwyg' => FALSE); $form['punctuation'] = array('#type' => 'fieldset', '#title' => t('Punctuation'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#tree' => TRUE); $punctuation = \Drupal::service('pathauto.manager')->getPunctuationCharacters(); foreach ($punctuation as $name => $details) { $details['default'] = PathautoManagerInterface::PUNCTUATION_REMOVE; if ($details['value'] == $config->get('separator')) { $details['default'] = PathautoManagerInterface::PUNCTUATION_REPLACE; } $form['punctuation']['punctuation' . $name] = array('#type' => 'select', '#title' => $details['name'] . ' (<code>' . SafeMarkup::checkPlain($details['value']) . '</code>)', '#default_value' => $details['default'], '#options' => array(PathautoManagerInterface::PUNCTUATION_REMOVE => t('Remove'), PathautoManagerInterface::PUNCTUATION_REPLACE => t('Replace by separator'), PathautoManagerInterface::PUNCTUATION_DO_NOTHING => t('No action (do not replace)'))); } return parent::buildForm($form, $form_state); }