Exemplo n.º 1
0
 /**
  * {@inheritdoc}
  */
 public function summaryTitle()
 {
     if ($this->options['vis']['manual_load']) {
         return \Drupal::translation()->formatPlural($this->options['items_per_page'], 'Click to load, @count item', 'Click to load, @count items', array('@count' => $this->options['items_per_page']));
     }
     return \Drupal::translation()->formatPlural($this->options['items_per_page'], 'Infinite scroll, @count item', 'Infinite scroll, @count items', array('@count' => $this->options['items_per_page']));
 }
Exemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 protected function generateElements(array $values)
 {
     $num = $values['num'];
     $kill = $values['kill'];
     $pass = $values['pass'];
     $age = $values['time_range'];
     $roles = $values['roles'];
     $url = parse_url($GLOBALS['base_url']);
     if ($kill) {
         $uids = db_select('users', 'u')->fields('u', array('uid'))->condition('uid', 1, '>')->execute()->fetchAllAssoc('uid');
         user_delete_multiple(array_keys($uids));
         $this->setMessage(\Drupal::translation()->formatPlural(count($uids), '1 user deleted', '@count users deleted.'));
     }
     if ($num > 0) {
         $names = array();
         while (count($names) < $num) {
             //@todo add suport for devel_generate_word(mt_rand(6, 12)) in a class method
             $name = $this->generateWord(mt_rand(6, 12));
             $names[$name] = '';
         }
         if (empty($roles)) {
             $roles = array(DRUPAL_AUTHENTICATED_RID);
         }
         foreach ($names as $name => $value) {
             $edit = array('uid' => NULL, 'name' => $name, 'pass' => $pass, 'mail' => $name . '@example.com', 'status' => 1, 'created' => REQUEST_TIME - mt_rand(0, $age), 'roles' => array_combine($roles, $roles), 'devel_generate' => TRUE);
             $account = entity_create('user', $edit);
             // Populate all fields with sample values.
             $this->populateFields($account);
             $account->save();
         }
     }
     $this->setMessage(t('!num_users created.', array('!num_users' => format_plural($num, '1 user', '@count users'))));
 }
Exemplo n.º 3
0
 /**
  * Processes fields targeted for purge as part of a configuration sync.
  *
  * This takes care of deleting the field if necessary, and purging the data on
  * the fly.
  *
  * @param array $context
  *   The batch context.
  * @param \Drupal\Core\Config\ConfigImporter $config_importer
  *   The config importer.
  */
 public static function process(array &$context, ConfigImporter $config_importer)
 {
     if (!isset($context['sandbox']['field'])) {
         static::initializeSandbox($context, $config_importer);
     }
     // Get the list of field storages to purge.
     $field_storages = static::getFieldStoragesToPurge($context['sandbox']['field']['extensions'], $config_importer->getUnprocessedConfiguration('delete'));
     // Get the first field storage to process.
     $field_storage = reset($field_storages);
     if (!isset($context['sandbox']['field']['current_storage_id']) || $context['sandbox']['field']['current_storage_id'] != $field_storage->id()) {
         $context['sandbox']['field']['current_storage_id'] = $field_storage->id();
         // If the storage has not been deleted yet we need to do that. This is the
         // case when the storage deletion is staged.
         if (!$field_storage->isDeleted()) {
             $field_storage->delete();
         }
     }
     field_purge_batch($context['sandbox']['field']['purge_batch_size'], $field_storage->uuid());
     $context['sandbox']['field']['current_progress']++;
     $fields_to_delete_count = count(static::getFieldStoragesToPurge($context['sandbox']['field']['extensions'], $config_importer->getUnprocessedConfiguration('delete')));
     if ($fields_to_delete_count == 0) {
         $context['finished'] = 1;
     } else {
         $context['finished'] = $context['sandbox']['field']['current_progress'] / $context['sandbox']['field']['steps_to_delete'];
         $context['message'] = \Drupal::translation()->translate('Purging field @field_label', array('@field_label' => $field_storage->label()));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildRow(Schedule $entity)
 {
     $row['label'] = $entity->label();
     $row['enabled'] = $entity->get('enabled') ? $this->t('Yes') : $this->t('No');
     $row['period'] = $entity->getPeriodFormatted();
     $row['last_run'] = $this->t('Never');
     if ($last_run = $entity->getLastRun()) {
         $row['last_run'] = \Drupal::service('date.formatter')->format($last_run, 'small');
         $row['last_run'] .= ' (' . $this->t('@time ago', array('@time' => \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $last_run))) . ')';
     }
     $row['next_run'] = $this->t('Not Scheduled');
     if ($next_run = $entity->getNextRun()) {
         $interval = \Drupal::service('date.formatter')->formatInterval(abs($next_run - REQUEST_TIME));
         if ($next_run > REQUEST_TIME) {
             $row['next_run'] = \Drupal::service('date.formatter')->format($next_run, 'small');
             $row['next_run'] .= ' (' . $this->t('in @time', array('@time' => $interval)) . ')';
         } else {
             $row['next_run'] = $this->t('Next cron run');
             if ($last_run) {
                 $row['next_run'] .= ' (' . $this->t('was due @time ago', array('@time' => $interval)) . ')';
             }
         }
     }
     $row['keep'] = \Drupal::translation()->formatPlural($entity->get('keep'), 'Last 1 backup', 'Last @count backups');
     return $row + parent::buildRow($entity);
 }
Exemplo n.º 5
0
 /**
  * Test the user login block.
  */
 function testUserLoginBlock()
 {
     // Make sure the validation error is displayed when try to login with
     // invalid username/password.
     $edit['name'] = $this->randomMachineName();
     $edit['pass'] = $this->randomMachineName();
     $this->drupalPostForm('node', $edit, t('Log in'));
     $this->assertRaw(\Drupal::translation()->formatPlural(1, '1 error has been found: !errors', '@count errors have been found: !errors', ['!errors' => SafeMarkup::set('<a href="#edit-name">Username</a>')]));
     $this->assertText(t('Sorry, unrecognized username or password.'));
     // Create a user with some permission that anonymous users lack.
     $user = $this->drupalCreateUser(array('administer permissions'));
     // Log in using the block.
     $edit = array();
     $edit['name'] = $user->getUsername();
     $edit['pass'] = $user->pass_raw;
     $this->drupalPostForm('admin/people/permissions', $edit, t('Log in'));
     $this->assertNoText(t('User login'), 'Logged in.');
     // Check that we are still on the same page.
     $this->assertUrl(\Drupal::url('user.admin_permissions', [], ['absolute' => TRUE]), [], 'Still on the same page after login for access denied page');
     // Now, log out and repeat with a non-403 page.
     $this->drupalLogout();
     $this->drupalPostForm('filter/tips', $edit, t('Log in'));
     $this->assertNoText(t('User login'), 'Logged in.');
     $this->assertPattern('!<title.*?' . t('Compose tips') . '.*?</title>!', 'Still on the same page after login for allowed page');
     // Check that the user login block is not vulnerable to information
     // disclosure to third party sites.
     $this->drupalLogout();
     $this->drupalPostForm('http://example.com/', $edit, t('Log in'), array('external' => FALSE));
     // Check that we remain on the site after login.
     $this->assertUrl($user->url('canonical', ['absolute' => TRUE]), [], 'Redirected to user profile page after login from the frontpage');
 }
 protected function doDisplay(array $context, array $blocks = array())
 {
     // line 12
     echo "<h3 class=\"views-ui-view-title views-table-filter-text-source\">";
     echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute(isset($context["view"]) ? $context["view"] : null, "label", array()), "html", null, true);
     echo "</h3>\n<div class=\"views-ui-view-displays\">\n  ";
     // line 14
     if (isset($context["displays"]) ? $context["displays"] : null) {
         // line 15
         echo "    ";
         echo \Drupal::translation()->formatPlural(abs(isset($context["displays"]) ? $context["displays"] : null), "Display", "Displays", array());
         // line 19
         echo ":\n    <em>";
         // line 20
         echo $this->env->getExtension('drupal_core')->renderVar($this->env->getExtension('drupal_core')->safeJoin($this->env, isset($context["displays"]) ? $context["displays"] : null, ", "));
         echo "</em>\n  ";
     } else {
         // line 22
         echo "    ";
         echo $this->env->getExtension('drupal_core')->renderVar(t("None"));
         echo "\n  ";
     }
     // line 24
     echo "</div>\n<div class=\"views-ui-view-machine-name\">\n  ";
     // line 26
     echo $this->env->getExtension('drupal_core')->renderVar(t("Machine name:"));
     echo "\n  <span class=\"views-table-filter-text-source\">";
     // line 27
     echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute(isset($context["view"]) ? $context["view"] : null, "id", array()), "html", null, true);
     echo "</span>\n</div>\n";
 }
 /**
  * Tests if the module cleans up the disk on uninstall.
  */
 public function testPiwikUninstall()
 {
     $cache_path = 'public://piwik';
     $site_id = '1';
     $this->config('piwik.settings')->set('site_id', $site_id)->save();
     $this->config('piwik.settings')->set('url_http', 'http://www.example.com/piwik/')->save();
     $this->config('piwik.settings')->set('url_https', 'https://www.example.com/piwik/')->save();
     // Enable local caching of piwik.js
     $this->config('piwik.settings')->set('cache', 1)->save();
     // Load front page to get the piwik.js downloaded into local cache. But
     // loading the piwik.js is not possible as "url_http" is a test dummy only.
     // Create a dummy file to complete the rest of the tests.
     file_prepare_directory($cache_path, FILE_CREATE_DIRECTORY);
     file_unmanaged_save_data($this->randomMachineName(16), $cache_path . '/piwik.js');
     // Test if the directory and piwik.js exists.
     $this->assertTrue(file_prepare_directory($cache_path), 'Cache directory "public://piwik" has been found.');
     $this->assertTrue(file_exists($cache_path . '/piwik.js'), 'Cached piwik.js tracking file has been found.');
     // Uninstall the module.
     $edit = [];
     $edit['uninstall[piwik]'] = TRUE;
     $this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall'));
     $this->assertNoText(\Drupal::translation()->translate('Configuration deletions'), 'No configuration deletions listed on the module install confirmation page.');
     $this->drupalPostForm(NULL, NULL, t('Uninstall'));
     $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
     // Test if the directory and all files have been removed.
     $this->assertFalse(file_scan_directory($cache_path, '/.*/'), 'Cached JavaScript files have been removed.');
     $this->assertFalse(file_prepare_directory($cache_path), 'Cache directory "public://piwik" has been removed.');
 }
Exemplo n.º 8
0
 /**
  * Tests the Uninstall page and Uninstall confirmation page.
  */
 function testUninstallPage()
 {
     $account = $this->drupalCreateUser(array('administer modules'));
     $this->drupalLogin($account);
     // Create a node type.
     $node_type = entity_create('node_type', array('type' => 'uninstall_blocker', 'name' => 'Uninstall blocker'));
     // Create a dependency that can be fixed.
     $node_type->setThirdPartySetting('module_test', 'key', 'value');
     $node_type->save();
     // Add a node to prevent node from being uninstalled.
     $node = entity_create('node', array('type' => 'uninstall_blocker'));
     $node->save();
     $this->drupalGet('admin/modules/uninstall');
     $this->assertTitle(t('Uninstall') . ' | Drupal');
     $this->assertText(\Drupal::translation()->translate('The following reasons prevents Node from being uninstalled: There is content for the entity type: Content'), 'Content prevents uninstalling node module.');
     // Delete the node to allow node to be uninstalled.
     $node->delete();
     // Uninstall module_test.
     $edit = array();
     $edit['uninstall[module_test]'] = TRUE;
     $this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall'));
     $this->assertNoText(\Drupal::translation()->translate('Configuration deletions'), 'No configuration deletions listed on the module install confirmation page.');
     $this->assertText(\Drupal::translation()->translate('Configuration updates'), 'Configuration updates listed on the module install confirmation page.');
     $this->assertText($node_type->label(), SafeMarkup::format('The entity label "!label" found.', array('!label' => $node_type->label())));
     $this->drupalPostForm(NULL, NULL, t('Uninstall'));
     $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
     // Uninstall node testing that the configuration that will be deleted is
     // listed.
     $node_dependencies = \Drupal::service('config.manager')->findConfigEntityDependentsAsEntities('module', array('node'));
     $edit = array();
     $edit['uninstall[node]'] = TRUE;
     $this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall'));
     $this->assertText(\Drupal::translation()->translate('Configuration deletions'), 'Configuration deletions listed on the module install confirmation page.');
     $this->assertNoText(\Drupal::translation()->translate('Configuration updates'), 'No configuration updates listed on the module install confirmation page.');
     $entity_types = array();
     foreach ($node_dependencies as $entity) {
         $label = $entity->label() ?: $entity->id();
         $this->assertText($label, SafeMarkup::format('The entity label "!label" found.', array('!label' => $label)));
         $entity_types[] = $entity->getEntityTypeId();
     }
     $entity_types = array_unique($entity_types);
     foreach ($entity_types as $entity_type_id) {
         $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
         // Add h3's since the entity type label is often repeated in the entity
         // labels.
         $this->assertRaw('<h3>' . $entity_type->getLabel() . '</h3>');
     }
     // Set a unique cache entry to be able to test whether all caches are
     // cleared during the uninstall.
     \Drupal::cache()->set('uninstall_test', 'test_uninstall_page', Cache::PERMANENT);
     $cached = \Drupal::cache()->get('uninstall_test');
     $this->assertEqual($cached->data, 'test_uninstall_page', SafeMarkup::format('Cache entry found: @bin', array('@bin' => $cached->data)));
     $this->drupalPostForm(NULL, NULL, t('Uninstall'));
     $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
     $this->assertNoRaw('&lt;label', 'The page does not have double escaped HTML tags.');
     // Make sure our unique cache entry is gone.
     $cached = \Drupal::cache()->get('uninstall_test');
     $this->assertFalse($cached, 'Cache entry not found');
 }
Exemplo n.º 9
0
 /**
  * Implements \Symfony\Component\Translation\TranslatorInterface::transChoice().
  */
 public function transChoice($id, $number, array $parameters = array(), $domain = NULL, $locale = NULL)
 {
     // Violation messages can separated singular and plural versions by "|".
     $ids = explode('|', $id);
     if (!isset($ids[1])) {
         throw new \InvalidArgumentException(sprintf('The message "%s" cannot be pluralized, because it is missing a plural (e.g. "There is one apple|There are @count apples").', $id));
     }
     return \Drupal::translation()->formatPlural($number, $ids[0], $ids[1], $this->processParameters($parameters), $this->getOptions($domain, $locale));
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function settingsSummary()
 {
     $summary = array();
     if ($this->getSetting('open')) {
         $summary[] = \Drupal::translation()->translate('Default state open');
     } else {
         $summary[] = \Drupal::translation()->translate('Default state closed');
     }
     return $summary;
 }
Exemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_nodes = $this->database->query("SELECT COUNT(*) FROM {crm_core_contact} WHERE type = :type", array(':type' => $this->entity->id()))->fetchField();
     if ($num_nodes) {
         $caption = \Drupal::translation()->formatPlural($num_nodes, '%type is used by one contact on your site. You can not remove this contact type until you have removed all of the %type contacts.', '%type is used by @count contacts on your site. You may not remove %type until you have removed all of the %type contacts.', array('%type' => $this->entity->label()));
         $form['#title'] = $this->getQuestion();
         $form['description'] = array('#markup' => '<p>' . $caption . '</p>');
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
Exemplo n.º 12
0
 /**
  * {@inheritdoc}
  */
 public function settingsSummary()
 {
     $summary = array();
     if ($this->getSetting('required_fields')) {
         $summary[] = \Drupal::translation()->translate('Mark as required');
     }
     if ($this->getSetting('description')) {
         $summary[] = \Drupal::translation()->translate('Description : @description', array('@description' => $this->getSetting('description')));
     }
     return $summary;
 }
Exemplo n.º 13
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_profiles = $this->queryFactory->get('profile')->condition('type', $this->entity->id())->count()->execute();
     if ($num_profiles) {
         $caption = '<p>' . \Drupal::translation()->formatPlural($num_profiles, '%type is used by 1 profile on your site. You can not remove this profile type until you have removed all of the %type profiles.', '%type is used by @count profiles on your site. You may not remove %type until you have removed all of the %type profiles.', ['%type' => $this->entity->label()]) . '</p>';
         $form['#title'] = $this->entity->label();
         $form['description'] = ['#markup' => $caption];
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
Exemplo n.º 14
0
 /**
  * Assert that a hook_file_* hook was called a certain number of times.
  *
  * @param string $hook
  *   String with the hook name; for instance, 'load', 'save', 'insert', etc.
  * @param int $expected_count
  *   Optional integer count.
  * @param string|NULL $message
  *   Optional translated string message.
  */
 function assertFileHookCalled($hook, $expected_count = 1, $message = NULL)
 {
     $actual_count = count(file_test_get_calls($hook));
     if (!isset($message)) {
         if ($actual_count == $expected_count) {
             $message = format_string('hook_file_@name was called correctly.', array('@name' => $hook));
         } elseif ($expected_count == 0) {
             $message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count));
         } else {
             $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count));
         }
     }
     $this->assertEqual($actual_count, $expected_count, $message);
 }
Exemplo n.º 15
0
 /**
  * {@inheritdoc}
  */
 public function preRender(&$element)
 {
     $add = array('#type' => 'details', '#id' => 'edit-' . $this->group->group_name, '#title' => String::checkPlain(\Drupal::translation()->translate($this->getLabel())), '#description' => $this->getSetting('description'));
     if ($this->getSetting('classes')) {
         $element['#attributes']['class'] = explode(' ', $this->getSetting('classes'));
     }
     // Front-end and back-end on configuration will lead
     // to vertical tabs nested in a separate vertical group.
     if (!empty($this->group->parent_name)) {
         $add['#group'] = $this->group->parent_name;
         $add['#parents'] = array($add['#group']);
     }
     $element += $add;
 }
Exemplo n.º 16
0
 /**
  * {@inheritdoc}
  */
 public function settingsSummary()
 {
     $summary = parent::settingsSummary();
     $summary[] = \Drupal::translation()->translate('Element: @element', array('@element' => $this->getSetting('element')));
     if ($this->getSetting('show_label')) {
         $summary[] = \Drupal::translation()->translate('Label element: @element', array('@element' => $this->getSetting('label_element')));
     }
     if ($this->getSetting('attributes')) {
         $summary[] = \Drupal::translation()->translate('Attributes: @attributes', array('@attributes' => $this->getSetting('attributes')));
     }
     if ($this->getSetting('required_fields')) {
         $summary[] = \Drupal::translation()->translate('Mark as required');
     }
     return $summary;
 }
 protected function doDisplay(array $context, array $blocks = array())
 {
     $tags = array("if" => 12, "trans" => 13);
     $filters = array("safe_join" => 18, "t" => 20);
     $functions = array();
     try {
         $this->env->getExtension('sandbox')->checkSecurity(array('if', 'trans'), array('safe_join', 't'), array());
     } catch (Twig_Sandbox_SecurityError $e) {
         $e->setTemplateFile($this->getTemplateName());
         if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
             $e->setTemplateLine($tags[$e->getTagName()]);
         } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
             $e->setTemplateLine($filters[$e->getFilterName()]);
         } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
             $e->setTemplateLine($functions[$e->getFunctionName()]);
         }
         throw $e;
     }
     // line 10
     echo "<h3 class=\"views-ui-view-title views-table-filter-text-source\">";
     echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute(isset($context["view"]) ? $context["view"] : null, "label", array()), "html", null, true));
     echo "</h3>\n<div class=\"views-ui-view-displays\">\n  ";
     // line 12
     if (isset($context["displays"]) ? $context["displays"] : null) {
         // line 13
         echo "    ";
         echo \Drupal::translation()->formatPlural(abs(isset($context["displays"]) ? $context["displays"] : null), "Display", "Displays", array());
         // line 17
         echo ":\n    <em>";
         // line 18
         echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($this->env->getExtension('drupal_core')->safeJoin($this->env, isset($context["displays"]) ? $context["displays"] : null, ", ")));
         echo "</em>\n  ";
     } else {
         // line 20
         echo "    ";
         echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("None")));
         echo "\n  ";
     }
     // line 22
     echo "</div>\n<div class=\"views-ui-view-machine-name\">\n  ";
     // line 24
     echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Machine name:")));
     echo "\n  <span class=\"views-table-filter-text-source\">";
     // line 25
     echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute(isset($context["view"]) ? $context["view"] : null, "id", array()), "html", null, true));
     echo "</span>\n</div>\n";
 }
Exemplo n.º 18
0
/**
 * Implements hook_form_system_theme_settings_alter().
 */
function d8_materialize_form_system_theme_settings_alter(&$form, $form_state, $form_id = NULL)
{
    $colors = array('materialize-red' => 'materialize-red', 'red' => 'red', 'pink' => 'pink', 'purple' => 'purple', 'deep-purple' => 'deep-purple', 'indigo' => 'indigo', 'blue' => 'blue', 'light-blue' => 'light-blue', 'cyan' => 'cyan', 'teal' => 'teal', 'green' => 'green', 'light-green' => 'light-green', 'lime' => 'lime', 'yellow' => 'yellow', 'amber' => 'amber', 'orange' => 'orange', 'deep-orange' => 'deep-orange', 'brown' => 'brown', 'blue-grey' => 'blue-grey', 'grey' => 'grey');
    $intensity = array("lighten-5" => "lighten-5", "lighten-4" => "lighten-4", "lighten-3" => "lighten-3", "lighten-2" => "lighten-2", "lighten-1" => "lighten-1", "base" => "base", "darken-1" => "darken-1", "darken-2" => "darken-2", "darken-3" => "darken-3", "darken-4" => "darken-4");
    $form['primary'] = array('#type' => 'details', '#title' => \Drupal::translation()->translate('Primary color schema selector'), '#wight' => -10, '#open' => TRUE);
    $form['primary']['primary_color'] = array('#type' => 'select', '#title' => \Drupal::translation()->translate('Primary color selector'), '#default_value' => theme_get_setting('primary_color'), '#description' => \Drupal::translation()->translate('Please select the primary color'), '#options' => $colors, '#weight' => -10);
    $form['primary']['primary_color_intensity'] = array('#type' => 'select', '#title' => \Drupal::translation()->translate('Primary color intensity selector'), '#default_value' => theme_get_setting('primary_color_intensity'), '#description' => \Drupal::translation()->translate('Select the intensity of the primary color'), '#options' => $intensity, '#weight' => -10);
    $form['secondary'] = array('#type' => 'details', '#title' => \Drupal::translation()->translate('Secondary color schema selector'), '#wight' => -10, '#open' => TRUE);
    $form['secondary']['secondary_color'] = array('#type' => 'select', '#title' => \Drupal::translation()->translate('Secondary color selector'), '#default_value' => theme_get_setting('secondary_color'), '#description' => \Drupal::translation()->translate('Please select the secondary color'), '#options' => $colors, '#weight' => -10);
    $form['secondary']['secondary_color_intensity'] = array('#type' => 'select', '#title' => \Drupal::translation()->translate('Secondary color intensity selector'), '#default_value' => theme_get_setting('secondary_color_intensity'), '#description' => \Drupal::translation()->translate('Select the intensity of the secondary color'), '#options' => $intensity, '#weight' => -10);
    $form['form_color'] = array('#type' => 'details', '#title' => \Drupal::translation()->translate('Form color schema selector'), '#wight' => -10, '#open' => TRUE);
    $form['form_color']['form_color'] = array('#type' => 'select', '#title' => \Drupal::translation()->translate('Form color selector'), '#default_value' => theme_get_setting('form_color'), '#description' => \Drupal::translation()->translate('Please select the form elements color'), '#options' => $colors, '#weight' => -10);
    $form['form_color']['form_color_intensity'] = array('#type' => 'select', '#title' => \Drupal::translation()->translate('Form color intensity selector'), '#default_value' => theme_get_setting('form_color_intensity'), '#description' => \Drupal::translation()->translate('Select the intensity of the form elements color'), '#options' => $intensity, '#weight' => -10);
    $template_options = array('default' => 'default', 'single_page' => 'single_page', 'blog' => 'blog');
    $form['page_twig_template'] = array('#type' => 'details', '#title' => \Drupal::translation()->translate('Chose template'), '#wight' => -9, '#open' => TRUE);
    $form['page_twig_template']['d8_template'] = array('#type' => 'select', '#title' => \Drupal::translation()->translate('Form color selector'), '#default_value' => theme_get_setting('d8_template'), '#description' => \Drupal::translation()->translate('Please select the form elements color'), '#options' => $template_options);
}
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $config = $this->config('simplenews.settings');
     $form['simplenews_mail_backend']['simplenews_use_cron'] = array('#type' => 'checkbox', '#title' => $this->t('Use cron to send newsletters'), '#default_value' => $config->get('mail.use_cron'), '#description' => $this->t('When checked cron will be used to send newsletters (recommended). Test newsletters and confirmation emails will be sent immediately. Leave unchecked for testing purposes.'));
     $throttle_val = array(1, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000);
     $throttle = array_combine($throttle_val, $throttle_val);
     $throttle[SpoolStorageInterface::UNLIMITED] = $this->t('Unlimited');
     if (function_exists('getrusage')) {
         $description_extra = '<br />' . $this->t('Cron execution must not exceed the PHP maximum execution time of %max seconds. You find the time spend to send emails in the <a href="/admin/reports/dblog">Recent log entries</a>.', array('%max' => ini_get('max_execution_time')));
     } else {
         $description_extra = '<br />' . $this->t('Cron execution must not exceed the PHP maximum execution time of %max seconds.', array('%max' => ini_get('max_execution_time')));
     }
     $form['simplenews_mail_backend']['simplenews_throttle'] = array('#type' => 'select', '#title' => $this->t('Cron throttle'), '#options' => $throttle, '#default_value' => $config->get('mail.throttle'), '#description' => $this->t('Sets the numbers of newsletters sent per cron run. Failure to send will also be counted.') . $description_extra);
     $form['simplenews_mail_backend']['simplenews_spool_expire'] = array('#type' => 'select', '#title' => $this->t('Mail spool expiration'), '#options' => array(0 => $this->t('Immediate'), 1 => \Drupal::translation()->formatPlural(1, '1 day', '@count days'), 7 => \Drupal::translation()->formatPlural(1, '1 week', '@count weeks'), 14 => \Drupal::translation()->formatPlural(2, '1 week', '@count weeks')), '#default_value' => $config->get('mail.spool_expire'), '#description' => $this->t('Newsletter mails are spooled. How long must messages be retained in the spool after successful sending. Keeping the message in the spool allows mail statistics (which is not yet implemented). If cron is not used, immediate expiration is advised.'));
     $form['simplenews_mail_backend']['simplenews_debug'] = array('#type' => 'checkbox', '#title' => $this->t('Log emails'), '#default_value' => $config->get('mail.debug'), '#description' => $this->t('When checked all outgoing simplenews emails are logged in the system log. A logged email does not guarantee that it is send or will be delivered. It only indicates that a message is sent to the PHP mail() function. No status information is available of delivery by the PHP mail() function.'));
     return parent::buildForm($form, $form_state);
 }
Exemplo n.º 20
0
 /**
  * {@inheritdoc}
  */
 public function preprocessVariables(Variables $variables, $hook, array $info)
 {
     if (!empty($variables['description'])) {
         $variables['description'] = FieldFilteredMarkup::create($variables['description']);
     }
     $descriptions = [];
     $cardinality = $variables['cardinality'];
     if (isset($cardinality)) {
         if ($cardinality == -1) {
             $descriptions[] = t('Unlimited number of files can be uploaded to this field.');
         } else {
             $descriptions[] = \Drupal::translation()->formatPlural($cardinality, 'One file only.', 'Maximum @count files.');
         }
     }
     $upload_validators = $variables['upload_validators'];
     if (isset($upload_validators['file_validate_size'])) {
         $descriptions[] = t('@size limit.', ['@size' => format_size($upload_validators['file_validate_size'][0])]);
     }
     if (isset($upload_validators['file_validate_extensions'])) {
         $extensions = new FormattableMarkup('<code>@extensions</code>', ['@extensions' => implode(', ', explode(' ', $upload_validators['file_validate_extensions'][0]))]);
         $descriptions[] = t('Allowed types: @extensions.', ['@extensions' => $extensions]);
     }
     if (isset($upload_validators['file_validate_image_resolution'])) {
         $max = $upload_validators['file_validate_image_resolution'][0];
         $min = $upload_validators['file_validate_image_resolution'][1];
         if ($min && $max && $min == $max) {
             $descriptions[] = t('Images must be exactly <strong>@size</strong> pixels.', ['@size' => $max]);
         } elseif ($min && $max) {
             $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels. Images larger than <strong>@max</strong> pixels will be resized.', ['@min' => $min, '@max' => $max]);
         } elseif ($min) {
             $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels.', ['@min' => $min]);
         } elseif ($max) {
             $descriptions[] = t('Images larger than <strong>@max</strong> pixels will be resized.', ['@max' => $max]);
         }
     }
     $variables['descriptions'] = $descriptions;
     if ($descriptions) {
         $build = array();
         $id = Html::getUniqueId('upload-instructions');
         $build['toggle'] = ['#type' => 'link', '#title' => t('Upload requirements'), '#url' => Url::fromUserInput("#{$id}"), '#icon' => Bootstrap::glyphicon('question-sign'), '#attributes' => ['class' => ['icon-before'], 'data-toggle' => 'popover', 'data-html' => 'true', 'data-placement' => 'bottom', 'data-title' => t('Upload requirements')]];
         $build['requirements'] = ['#type' => 'container', '#theme_wrappers' => ['container__file_upload_help'], '#attributes' => ['id' => $id, 'class' => ['hidden', 'help-block'], 'aria-hidden' => 'true']];
         $build['requirements']['descriptions'] = ['#theme' => 'item_list__file_upload_help', '#items' => $descriptions];
         $variables['popover'] = $build;
     }
 }
Exemplo n.º 21
0
 /**
  * {@inheritdoc}
  */
 public function settingsSummary()
 {
     $summary = parent::settingsSummary();
     if ($this->getSetting('effect') != 'none') {
         $summary[] = \Drupal::translation()->translate('Effect : @effect', array('@effect' => $this->getSetting('effect')));
         $summary[] = \Drupal::translation()->translate('Speed : @speed', array('@speed' => $this->getSetting('speed')));
     }
     if ($this->getSetting('show_label')) {
         $summary[] = \Drupal::translation()->translate('Label element @element', array('@element' => $this->getSetting('label_element')));
     }
     if ($this->getSetting('required_fields')) {
         $summary[] = \Drupal::translation()->translate('Mark as required');
     }
     if ($this->getSetting('description')) {
         $summary[] = \Drupal::translation()->translate('Description : @description', array('@description' => $this->getSetting('description')));
     }
     return $summary;
 }
Exemplo n.º 22
0
 /**
  * {@inheritdoc}
  */
 public function alterForm(array &$form, FormStateInterface $form_state, $form_id = NULL)
 {
     parent::alterForm($form, $form_state, $form_id);
     $update_manager = new UpdateManager($this->theme);
     $pending = $update_manager->getPendingUpdates();
     if ($pending) {
         $form['update'] = ['#type' => 'details', '#title' => \Drupal::translation()->formatPlural(count($pending), 'Pending Update', 'Pending Updates'), '#panel_type' => 'primary', '#weight' => -20];
         $rows = [];
         foreach ($pending as $version => $update) {
             $row = [];
             $row[] = $version;
             $row[] = new FormattableMarkup('<strong>@title</strong><p class="help-block">@description</p>', ['@title' => $update->getTitle(), '@description' => $update->getDescription()]);
             $rows[] = ['class' => [$update->getLevel() ?: 'default'], 'data' => $row];
         }
         $form['update']['table'] = ['#type' => 'table', '#header' => [t('Update'), t('Description')], '#rows' => $rows];
         $form['update']['update'] = ['#type' => 'submit', '#value' => t('Update @theme', ['@theme' => $this->theme->getTitle()]), '#icon' => Bootstrap::glyphicon('open'), '#attributes' => ['class' => ['btn-primary']], '#submit' => [[get_class($this), 'updateTheme']]];
     }
 }
Exemplo n.º 23
0
 /**
  * {@inheritdoc}
  */
 protected function generateElements(array $values)
 {
     $num = $values['num'];
     $kill = $values['kill'];
     if ($kill) {
         $this->setMessage(t('Old examples have been deleted.'));
     }
     //Creating user in order to demonstrate
     // how to override default business login generation.
     $edit = array('uid' => NULL, 'name' => 'example_devel_generate', 'pass' => '', 'mail' => '*****@*****.**', 'status' => 1, 'created' => REQUEST_TIME, 'roles' => '', 'devel_generate' => TRUE);
     $account = user_load_by_name('example_devel_generate');
     if (!$account) {
         $account = entity_create('user', $edit);
     }
     // Populate all core fields on behalf of field.module
     DevelGenerateFieldBase::generateFields($account, 'user', 'user', 'register', 'devel_generate_example');
     $account->save();
     $this->setMessage(t('!num_examples created.', array('!num_examples' => \Drupal::translation()->formatPlural($num, '1 example', '@count examples'))));
 }
Exemplo n.º 24
0
 /**
  * {@inheritdoc}
  */
 public function transChoice($id, $number, array $parameters = array(), $domain = NULL, $locale = NULL)
 {
     // Violation messages can separated singular and plural versions by "|".
     $ids = explode('|', $id);
     if (!isset($ids[1])) {
         throw new \InvalidArgumentException(sprintf('The message "%s" cannot be pluralized, because it is missing a plural (e.g. "There is one apple|There are @count apples").', $id));
     }
     // Normally, calls to formatPlural() need to use literal strings, like
     //   formatPlural($count, '1 item', '@count items')
     // so that the Drupal project POTX string extractor will correctly
     // extract the strings for translation and save them in a format that
     // formatPlural() can work with. However, this is a special case, because
     // Drupal is supporting a constraint message format from Symfony. So
     // although $id looks like a variable here, it is actually coming from a
     // static string in a constraint class that the POTX extractor knows about
     // and has processed to work with formatPlural(), so this specific call to
     // formatPlural() will work correctly.
     return \Drupal::translation()->formatPlural($number, $ids[0], $ids[1], $this->processParameters($parameters), $this->getOptions($domain, $locale));
 }
Exemplo n.º 25
0
/**
 * Prepares variables for file upload help text templates.
 *
 * Default template: file-upload-help.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - description: The normal description for this field, specified by the
 *     user.
 *   - upload_validators: An array of upload validators as used in
 *     $element['#upload_validators'].
 */
function bootstrap_preprocess_file_upload_help(&$variables)
{
    $config = \Drupal::config('bootstrap.settings');
    $upload_validators = $variables['upload_validators'];
    $cardinality = $variables['cardinality'];
    $descriptions = array();
    if (isset($cardinality)) {
        if ($cardinality == -1) {
            $descriptions[] = t('Unlimited number of files can be uploaded to this field.');
        } else {
            $descriptions[] = \Drupal::translation()->formatPlural($cardinality, 'One file only.', 'Maximum @count files.');
        }
    }
    if (isset($upload_validators['file_validate_size'])) {
        $descriptions[] = t('@size limit.', array('@size' => format_size($upload_validators['file_validate_size'][0])));
    }
    if (isset($upload_validators['file_validate_extensions'])) {
        $descriptions[] = t('Allowed types: @extensions.', array('@extensions' => $upload_validators['file_validate_extensions'][0]));
    }
    if (isset($upload_validators['file_validate_image_resolution'])) {
        $max = $upload_validators['file_validate_image_resolution'][0];
        $min = $upload_validators['file_validate_image_resolution'][1];
        if ($min && $max && $min == $max) {
            $descriptions[] = t('Images must be exactly <strong>@size</strong> pixels.', array('@size' => $max));
        } elseif ($min && $max) {
            $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels. Images larger than <strong>@max</strong> pixels will be resized.', array('@min' => $min, '@max' => $max));
        } elseif ($min) {
            $descriptions[] = t('Images must be larger than <strong>@min</strong> pixels.', array('@min' => $min));
        } elseif ($max) {
            $descriptions[] = t('Images larger than <strong>@max</strong> pixels will be resized.', array('@max' => $max));
        }
    }
    // If popovers are enabled.
    if ($config->get('bootstrap_popover_enabled')) {
        $id = html::getUniqueId('upload-instructions');
        $icon = _bootstrap_icon('question-sign');
        $link_title = SafeMarkup::format($icon . ' ' . '@text', array('@text' => 'More information'));
        $variables['popover_link'] = _bootstrap_popover_link($link_title, $id, t('File requirements'), 'bottom');
        $description_content = array('#theme' => 'item_list', '#items' => $descriptions);
        $variables['popover_content'] = _bootstrap_popover_content($id, array($description_content));
    }
    $variables['descriptions'] = $descriptions;
}
Exemplo n.º 26
0
 /**
  * Tests the overview page.
  */
 function testOverviewPage()
 {
     $feed = $this->createFeed($this->getRSS091Sample());
     $this->drupalGet('admin/config/services/aggregator');
     $result = $this->xpath('//table/tbody/tr');
     // Check if the amount of feeds in the overview matches the amount created.
     $this->assertEqual(1, count($result), 'Created feed is found in the overview');
     // Check if the fields in the table match with what's expected.
     $this->assertEqual($feed->label(), (string) $result[0]->td[0]->a);
     $count = $this->container->get('entity.manager')->getStorage('aggregator_item')->getItemCount($feed);
     $this->assertEqual(\Drupal::translation()->formatPlural($count, '1 item', '@count items'), (string) $result[0]->td[1]);
     // Update the items of the first feed.
     $feed->refreshItems();
     $this->drupalGet('admin/config/services/aggregator');
     $result = $this->xpath('//table/tbody/tr');
     // Check if the fields in the table match with what's expected.
     $this->assertEqual($feed->label(), (string) $result[0]->td[0]->a);
     $count = $this->container->get('entity.manager')->getStorage('aggregator_item')->getItemCount($feed);
     $this->assertEqual(\Drupal::translation()->formatPlural($count, '1 item', '@count items'), (string) $result[0]->td[1]);
 }
Exemplo n.º 27
0
 /**
  * Test user operations.
  */
 function testUserOperations()
 {
     $account = $this->drupalCreateUser();
     // Delete all current URL aliases.
     $this->deleteAllAliases();
     // Find the position of just created account in the user_admin_people view.
     $view = Views::getView('user_admin_people');
     $view->initDisplay();
     $view->preview('page_1');
     foreach ($view->result as $key => $row) {
         if ($view->field['name']->getValue($row) == $account->getUsername()) {
             break;
         }
     }
     $edit = array('action' => 'pathauto_update_alias_user', "user_bulk_form[{$key}]" => TRUE);
     $this->drupalPostForm('admin/people', $edit, t('Apply'));
     $this->assertRaw(\Drupal::translation()->formatPlural(1, '%action was applied to @count item.', '%action was applied to @count items.', array('%action' => 'Update URL-Alias')));
     $this->assertEntityAlias($account, 'users/' . Unicode::strtolower($account->getUsername()));
     $this->assertEntityAlias($this->adminUser, 'user/' . $this->adminUser->id());
 }
 /**
  * Finish batch.
  *
  */
 public static function finishBatch($success, $results, $operations)
 {
     if ($success) {
         if (!empty($results['errors'])) {
             foreach ($results['errors'] as $error) {
                 drupal_set_message($error, 'error');
                 \Drupal::logger('config_sync')->error($error);
             }
             drupal_set_message(\Drupal::translation()->translate('The database was synchronized with errors.'), 'warning');
         } else {
             drupal_set_message(\Drupal::translation()->translate('The database was synchronized successfully.'), 'warning');
         }
     } else {
         // An error occurred.
         // $operations contains the operations that remained unprocessed.
         $error_operation = reset($operations);
         $message = \Drupal::translation()->translate('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
         drupal_set_message($message, 'error');
     }
 }
 /**
  * Test registration types in UI.
  */
 function testRegistrationTypes()
 {
     $web_user = $this->drupalCreateUser(['administer registration types', 'access administration pages']);
     $this->drupalLogin($web_user);
     // Create and delete the testing registration type.
     $this->drupalGet('admin/structure/rng/registration_types/manage/' . $this->registration_type->id());
     $this->registration_type->delete();
     // Administration.
     $this->drupalGet('admin/structure');
     $this->assertLinkByHref(Url::fromRoute('rng.registration_type.overview')->toString());
     $this->drupalGet('admin/structure/rng/registration_types');
     $this->assertRaw('No registration types found.', 'Registration type list is empty');
     $this->assertEqual(0, count(RegistrationType::loadMultiple()));
     // Local action.
     $this->assertLinkByHref(Url::fromRoute('entity.registration_type.add')->toString());
     // Add.
     $edit = ['label' => 'Foobar1', 'id' => 'foobar'];
     $this->drupalPostForm('admin/structure/rng/registration_types/add', $edit, t('Save'));
     $this->assertRaw(t('%label registration type was added.', ['%label' => 'Foobar1']));
     $this->assertEqual(1, count(RegistrationType::loadMultiple()));
     // Registration type list.
     $this->assertUrl(Url::fromRoute('rng.registration_type.overview', [], ['absolute' => TRUE])->toString(), []);
     $this->assertRaw('<td>Foobar1</td>', 'New registration type shows in list.');
     // Edit.
     $edit = ['label' => 'Foobar2'];
     $this->drupalPostForm('admin/structure/rng/registration_types/manage/foobar', $edit, t('Save'));
     $this->assertRaw(t('%label registration type was updated.', ['%label' => 'Foobar2']));
     $registration[0] = $this->createRegistration($this->event, 'foobar');
     $registration[1] = $this->createRegistration($this->event, 'foobar');
     $this->drupalGet('admin/structure/rng/registration_types/manage/foobar/delete');
     $this->assertRaw(\Drupal::translation()->formatPlural(count($registration), 'Unable to delete registration type. It is used by @count registration.', 'Unable to delete registration type. It is used by @count registrations.'));
     $registration[0]->delete();
     $registration[1]->delete();
     // No registrations; delete is allowed.
     $this->drupalGet('admin/structure/rng/registration_types/manage/foobar/delete');
     $this->assertRaw(t('This action cannot be undone.'));
     // Delete.
     $this->drupalPostForm('admin/structure/rng/registration_types/manage/foobar/delete', [], t('Delete'));
     $this->assertRaw(t('Registration type %label was deleted.', ['%label' => 'Foobar2']));
     $this->assertEqual(0, count(RegistrationType::loadMultiple()), 'Registration type entity removed from storage.');
 }
Exemplo n.º 30
0
 /**
  * Callback for updating a theme.
  *
  * @param array $form
  *   Nested array of form elements that comprise the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public static function updateTheme(array $form, FormStateInterface $form_state)
 {
     if ($theme = SystemThemeSettings::getTheme($form, $form_state)) {
         // Due to the fact that the batch API stores it's arguments in DB storage,
         // theme based objects cannot be passed as an operation argument here.
         // During _batch_page(), the DB item will attempt to restore the arguments
         // using unserialize() and the autoload fix include added below may not
         // yet have been invoked to register the theme namespaces. So instead,
         // we capture the relevant information needed to reconstruct these objects
         // in the batch processing callback.
         $theme_name = $theme->getName();
         // Create an operation for each update.
         $operations = [];
         foreach ($theme->getPendingUpdates() as $update) {
             $operations[] = [[__CLASS__, 'batchProcessUpdate'], [$theme_name, $update->getProvider() . ':' . $update->getSchema()]];
         }
         if ($operations) {
             $variables = ['@theme_title' => $theme->getTitle()];
             batch_set(['operations' => $operations, 'finished' => [__CLASS__, 'batchFinished'], 'title' => t('Updating @theme_title', $variables), 'init_message' => \Drupal::translation()->formatPlural(count($operations), 'Initializing 1 theme update for @theme_title...', 'Initializing @count theme updates for @theme_title...', $variables), 'progress_message' => t('Processing update @current of @total...', $variables), 'error_message' => t('An error was encountered while attempting to update the @theme_title theme.', $variables), 'file' => Bootstrap::autoloadFixInclude()]);
         }
     }
 }