Example #1
1
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     $view = $this->entity;
     $form['#prefix'] = '<div id="views-preview-wrapper" class="views-admin clearfix">';
     $form['#suffix'] = '</div>';
     $form['#id'] = 'views-ui-preview-form';
     $form_state->disableCache();
     $form['controls']['#attributes'] = array('class' => array('clearfix'));
     $form['controls']['title'] = array('#prefix' => '<h2 class="view-preview-form__title">', '#markup' => $this->t('Preview'), '#suffix' => '</h2>');
     // Add a checkbox controlling whether or not this display auto-previews.
     $form['controls']['live_preview'] = array('#type' => 'checkbox', '#id' => 'edit-displays-live-preview', '#title' => $this->t('Auto preview'), '#default_value' => \Drupal::config('views.settings')->get('ui.always_live_preview'));
     // Add the arguments textfield
     $form['controls']['view_args'] = array('#type' => 'textfield', '#title' => $this->t('Preview with contextual filters:'), '#description' => $this->t('Separate contextual filter values with a "/". For example, %example.', array('%example' => '40/12/10')), '#id' => 'preview-args');
     $args = array();
     if (!$form_state->isValueEmpty('view_args')) {
         $args = explode('/', $form_state->getValue('view_args'));
     }
     $user_input = $form_state->getUserInput();
     if ($form_state->get('show_preview') || !empty($user_input['js'])) {
         $form['preview'] = array('#weight' => 110, '#theme_wrappers' => array('container'), '#attributes' => array('id' => 'views-live-preview'), 'preview' => $view->renderPreview($this->displayID, $args));
     }
     $uri = $view->urlInfo('preview-form');
     $uri->setRouteParameter('display_id', $this->displayID);
     $form['#action'] = $uri->toString();
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->drupalPlaceBlock('system_menu_block:account');
     // Make test-page default.
     \Drupal::config('system.site')->set('page.front', 'test-page')->save();
 }
Example #3
0
 /**
  * {@inheritdoc}
  *
  * The file name for the CSS or JS cache file is generated from the hash of
  * the aggregated contents of the files in $data. This forces proxies and
  * browsers to download new CSS when the CSS changes.
  */
 public function dump($data, $file_extension)
 {
     // Prefix filename to prevent blocking by firewalls which reject files
     // starting with "ad*".
     $filename = $file_extension . '_' . Crypt::hashBase64($data) . '.' . $file_extension;
     // Create the css/ or js/ path within the files folder.
     $path = 'public://' . $file_extension;
     $uri = $path . '/' . $filename;
     // Create the CSS or JS file.
     file_prepare_directory($path, FILE_CREATE_DIRECTORY);
     if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
         return FALSE;
     }
     // If CSS/JS gzip compression is enabled and the zlib extension is available
     // then create a gzipped version of this file. This file is served
     // conditionally to browsers that accept gzip using .htaccess rules.
     // It's possible that the rewrite rules in .htaccess aren't working on this
     // server, but there's no harm (other than the time spent generating the
     // file) in generating the file anyway. Sites on servers where rewrite rules
     // aren't working can set css.gzip to FALSE in order to skip
     // generating a file that won't be used.
     if (extension_loaded('zlib') && \Drupal::config('system.performance')->get($file_extension . '.gzip')) {
         if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
             return FALSE;
         }
     }
     return $uri;
 }
 /**
  * Constructs a CheckoutPaneManager object.
  *
  * @param \Traversable $namespaces
  *   An object that implements \Traversable which contains the root paths
  *   keyed by the corresponding namespace to look for plugin implementations,
  * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
  *   Cache backend instance to use.
  * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  *   The module handler.
  */
 public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler)
 {
     parent::__construct('Plugin/Ubercart/CheckoutPane', $namespaces, $module_handler, CheckoutPanePluginInterface::class, CheckoutPane::class);
     $this->alterInfo('payment_method');
     $this->setCacheBackend($cache_backend, 'uc_checkout_panes');
     $this->paneConfig = \Drupal::config('uc_cart.settings')->get('panes');
 }
 /**
  * Purges cache tags on CloudFlare.
  *
  * @todo Once https://github.com/d8-contrib-modules/cloudflare/issues/16 is
  *   done, this should disappear.
  *
  * @param string[] $tags
  *   The list of tags for which to invalidate cache items.
  */
 public function purgeTags(array $tags)
 {
     $config = \Drupal::config('cloudflare.settings');
     $api_key = $config->get('apikey');
     $email = $config->get('email');
     $zone = $config->get('zone');
     // If the module is not yet configured, don't attempt to purge.
     // @todo Improve the rest of the architecture of this module so this check
     //   is not necessary anymore.
     if (!isset($api_key)) {
         return;
     }
     try {
         $this->zoneApi = new ZoneApi($api_key, $email);
         // @todo rethink how to handle cloudflare zones in Drupal.
         if (is_null($zone)) {
             $zones = $this->zoneApi->listZones();
             $zone = $zones[0]->getZoneId();
         }
         $this->zoneApi->purgeTags($zone, $tags);
     } catch (CloudFlareHttpException $e) {
         drupal_set_message("Unable to clear zone cache. " . $e->getMessage(), 'error');
         \Drupal::logger('cloudflare')->error($e->getMessage());
         return;
     } catch (CloudFlareApiException $e) {
         drupal_set_message("Unable to clear zone cache. " . $e->getMessage(), 'error');
         \Drupal::logger('cloudflare')->error($e->getMessage());
         return;
     }
     // If no exceptions have been thrown then the request has been successful.
 }
Example #6
0
 /**
  * Tests that the database was properly loaded.
  */
 public function testDatabaseLoaded()
 {
     foreach (['user', 'node', 'system', 'update_test_schema'] as $module) {
         $this->assertEqual(drupal_get_installed_schema_version($module), 8000, SafeMarkup::format('Module @module schema is 8000', ['@module' => $module]));
     }
     // Ensure that all {router} entries can be unserialized. If they cannot be
     // unserialized a notice will be thrown by PHP.
     $result = \Drupal::database()->query("SELECT name, route from {router}")->fetchAllKeyed(0, 1);
     // For the purpose of fetching the notices and displaying more helpful error
     // messages, let's override the error handler temporarily.
     set_error_handler(function ($severity, $message, $filename, $lineno) {
         throw new \ErrorException($message, 0, $severity, $filename, $lineno);
     });
     foreach ($result as $route_name => $route) {
         try {
             unserialize($route);
         } catch (\Exception $e) {
             $this->fail(sprintf('Error "%s" while unserializing route %s', $e->getMessage(), Html::escape($route_name)));
         }
     }
     restore_error_handler();
     // Before accessing the site we need to run updates first or the site might
     // be broken.
     $this->runUpdates();
     $this->assertEqual(\Drupal::config('system.site')->get('name'), 'Site-Install');
     $this->drupalGet('<front>');
     $this->assertText('Site-Install');
     // Ensure that the database tasks have been run during set up. Neither MySQL
     // nor SQLite make changes that are testable.
     $database = $this->container->get('database');
     if ($database->driver() == 'pgsql') {
         $this->assertEqual('on', $database->query("SHOW standard_conforming_strings")->fetchField());
         $this->assertEqual('escape', $database->query("SHOW bytea_output")->fetchField());
     }
 }
 /**
  * Responds to GET requests.
  *
  * Returns a menu tree for the specified menu name.
  *
  * @param int $menu_name
  *   The machine name of the Drupal menu.
  *
  * @return \Drupal\rest\ResourceResponse
  *   The response containing the menu tree.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\HttpException
  */
 public function get($menu_name = NULL)
 {
     if ($menu_name) {
         // Get menu tree resource config, set at /admin/config/services/menutree.
         $config = \Drupal::config('menutree_resource.services_settings');
         $services_menus = $config->get('services_menus');
         // Only allow a response if the menu is in config
         if (in_array($menu_name, array_filter(array_values($services_menus)))) {
             $menu_tree = \Drupal::menuTree();
             $parameters = new MenuTreeParameters();
             $parameters->onlyEnabledLinks();
             $tree = $menu_tree->load($menu_name, $parameters);
             if (!empty($tree)) {
                 $manipulators = array(array('callable' => 'menu.default_tree_manipulators:checkAccess'), array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'));
                 $tree = $menu_tree->transform($tree, $manipulators);
                 $build = $menu_tree->build($tree);
                 // Clean the menu tree so it's ready for serialisation in a resource response.
                 $items = $this->clean_tree($build['#items']);
                 return new ResourceResponse($items);
             }
             throw new NotFoundHttpException(t('Menu with name @menu_name was not found', array('@menu_name' => $menu_name)));
         }
         throw new NotFoundHttpException(t('Menu tree @menu_name not allowed.', array('@menu_name' => $menu_name)));
     }
     throw new HttpException(t('No menu name was provided'));
 }
Example #8
0
 /**
  * Tests block_example functionality.
  */
 public function testBlockExampleBasic()
 {
     // Login the admin user.
     $this->drupalLogin($this->webUser);
     $theme_name = \Drupal::config('system.theme')->get('default');
     // Verify the blocks are listed to be added.
     $this->drupalGet('admin/structure/block/list/' . $theme_name);
     $this->assertRaw(t('Title of first block (example_configurable_text)'), 'Block configurable-string found.');
     $this->assertRaw(t('Example: empty block'), 'Block empty-block found.');
     $this->assertRaw(t('Example: uppercase this please'), 'Block uppercase found.');
     // Define and place blocks.
     $settings_configurable = array('label' => t('Title of first block (example_configurable_text)'), 'id' => 'block_example_example_configurable_text', 'theme' => $theme_name);
     $this->drupalPlaceBlock('example_configurable_text', $settings_configurable);
     $settings_uppercase = array('label' => t('Configurable block to be uppercased'), 'id' => 'block_example_example_uppercased', 'theme' => $theme_name);
     $this->drupalPlaceBlock('example_uppercase', $settings_uppercase);
     $settings_empty = array('label' => t('Example: empty block'), 'id' => 'block_example_example_empty', 'theme' => $theme_name);
     $this->drupalPlaceBlock('example_empty', $settings_empty);
     // Verify that blocks are there. Empty block will not be shown, because it
     // is empty.
     $this->drupalGet('/');
     $this->assertRaw($settings_configurable['label'], 'Block configurable test not found.');
     $this->assertNoRaw($settings_uppercase['label'], 'Block uppercase with normal label not found.');
     $this->assertRaw(Unicode::strtoupper($settings_uppercase['label']), 'Block uppercase with uppercased label found.');
     $this->assertNoRaw($settings_empty['label'], 'Block empty not found.');
     // Change content of configurable text block.
     $edit = array('settings[block_example_string_text]' => $this->randomMachineName());
     $this->drupalPostForm('admin/structure/block/manage/' . $settings_configurable['id'], $edit, t('Save block'));
     // Verify that new content is shown.
     $this->drupalGet('/');
     $this->assertRaw($edit['settings[block_example_string_text]'], 'Content of configurable text block successfully verified.');
 }
 public function content()
 {
     $config = \Drupal::config('tweets.settings');
     $username = '******' . $config->get('twitter_username') . '">@' . $config->get('twitter_username') . '</a>';
     return array('#theme' => 'tweets_block', '#username' => $username, '#tweets' => $this->tweets, '#attached' => array('library' => array('tweets/base')));
     return array('#type' => 'markup', '#markup' => $this->t('Hello, Systemick World!'));
 }
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $system_roles = user_roles($membersonly = TRUE);
     $config = \Drupal::config('registration_role_with_approval.settings');
     $site_config = \Drupal::configFactory()->get('system.mail');
     $mailing_list = $config->get('mailing_list');
     if ($mailing_list == "") {
         $mailing_list .= $site_config->get('mail');
     }
     $email_subject = $config->get('email_subject');
     $email_body = $config->get('email_body');
     $profile_roles = $config->get('profile_roles');
     $form['roles'] = array('#type' => 'fieldset', '#title' => t('Avaliable Roles on registration form'), '#collapsible' => TRUE);
     foreach ($system_roles as $system_role) {
         $role_id = $system_role->id();
         if ($role_id != '0' && $role_id != 'authenticated') {
             $form['roles'][$system_role->id()] = array('#type' => 'checkbox', '#title' => t($system_role->label()), '#default_value' => $profile_roles[$system_role->id()]['default']);
             $form['roles'][$system_role->id() . "needs_approval"] = array('#type' => 'checkbox', '#title' => t('needs approval'), '#states' => array('invisible' => array(":input[name='{$role_id}']" => array('checked' => FALSE))), '#attributes' => array('style' => 'margin-left: 2em'), '#default_value' => $profile_roles[$system_role->id()]['needs_approval']);
         }
     }
     $form['custom_mail'] = array('#type' => 'fieldset', '#title' => t('Custom registration email configuration'), '#collapsible' => TRUE);
     $form['custom_mail']['new_email'] = array("#type" => "textfield", "#title" => "Enter valid email");
     $form['custom_mail']['add_email'] = array("#type" => "button", "#value" => "Add email", "#ajax" => array('callback' => 'Drupal\\registration_role_with_approval\\Form\\RegistrationRoleWithApprovalSettingsForm::addEmailCallback', 'event' => 'click', 'effect' => 'fade', 'progress' => array('type' => 'throbber')));
     $form['custom_mail']['mailing_list'] = array("#type" => "textarea", "#title" => "Mailing list", "#default_value" => $mailing_list);
     $form['custom_mail']['email_subject'] = array("#type" => "textfield", "#title" => "Email subject", "#default_value" => $email_subject);
     $form['custom_mail']['email_body'] = array("#type" => "textarea", "#title" => "Email body", "#default_value" => $email_body);
     return parent::buildForm($form, $form_state);
 }
 public function testUserName()
 {
     $this->drupalLogin($this->drupalCreateUser(array('access user profiles')));
     $view = Views::getView('test_views_handler_field_user_name');
     $this->executeView($view);
     $view->field['name']->options['link_to_user'] = TRUE;
     $username = $view->result[0]->users_field_data_name = $this->randomMachineName();
     $view->result[0]->users_field_data_uid = 1;
     $render = $view->field['name']->advancedRender($view->result[0]);
     $this->assertTrue(strpos($render, $username) !== FALSE, 'If link to user is checked the username should be part of the output.');
     $this->assertTrue(strpos($render, 'user/1') !== FALSE, 'If link to user is checked the link to the user should appear as well.');
     $view->field['name']->options['link_to_user'] = FALSE;
     $username = $view->result[0]->users_field_data_name = $this->randomMachineName();
     $view->result[0]->users_field_data_uid = 1;
     $render = $view->field['name']->advancedRender($view->result[0]);
     $this->assertIdentical($render, $username, 'If the user is not linked the username should be printed out for a normal user.');
     $view->result[0]->users_field_data_uid = 0;
     $anon_name = \Drupal::config('user.settings')->get('anonymous');
     $view->result[0]->users_field_data_name = '';
     $render = $view->field['name']->advancedRender($view->result[0]);
     $this->assertIdentical($render, $anon_name, 'For user0 it should use the default anonymous name by default.');
     $view->field['name']->options['overwrite_anonymous'] = TRUE;
     $anon_name = $view->field['name']->options['anonymous_text'] = $this->randomMachineName();
     $render = $view->field['name']->advancedRender($view->result[0]);
     $this->assertIdentical($render, $anon_name, 'For user0 it should use the configured anonymous text if overwrite_anonymous is checked.');
 }
 /**
  * {@inheritdoc}
  */
 public function access(Route $route, AccountInterface $account, NodeInterface $node = NULL)
 {
     if ($node->bundle() && \Drupal::config('webform.settings')->get('node_' . $node->bundle())) {
         return AccessResult::allowed();
     }
     return AccessResult::forbidden();
 }
Example #13
0
 /**
  * Creates an indexing batch for a given search index.
  *
  * @param \Drupal\search_api\IndexInterface $index
  *   The search index for which items should be indexed.
  * @param int|null $batch_size
  *   (optional) Number of items to index per batch. Defaults to the cron limit
  *   set for the index.
  * @param int $limit
  *   (optional) Maximum number of items to index. Defaults to indexing all
  *   remaining items.
  *
  * @throws \Drupal\search_api\SearchApiException
  *   Thrown if the batch could not be created.
  */
 public static function create(IndexInterface $index, $batch_size = NULL, $limit = -1) {
   // Check if the size should be determined by the index cron limit option.
   if ($batch_size === NULL) {
     // Use the size set by the index.
     $batch_size = $index->getOption('cron_limit', \Drupal::config('search_api.settings')->get('default_cron_limit'));
   }
   // Check if indexing items is allowed.
   if ($index->status() && !$index->isReadOnly() && $batch_size !== 0 && $limit !== 0) {
     // Define the search index batch definition.
     $batch_definition = array(
       'operations' => array(
         array(array(__CLASS__, 'process'), array($index, $batch_size, $limit)),
       ),
       'finished' => array(__CLASS__, 'finish'),
       'progress_message' => static::t('Completed about @percentage% of the indexing operation (@current of @total).'),
     );
     // Schedule the batch.
     batch_set($batch_definition);
   }
   else {
     $args = array(
       '%size' => $batch_size,
       '%limit' => $limit,
       '%name' => $index->label(),
     );
     throw new SearchApiException(new FormattableMarkup('Failed to create a batch with batch size %size and limit %limit for index %name', $args));
   }
 }
 public function cosign_login(Request $request)
 {
     $request_uri = $request->getRequestUri();
     global $base_path;
     if (!CosignSharedFunctions::cosign_is_https()) {
         return new TrustedRedirectResponse('https://' . $_SERVER['HTTP_HOST'] . $request_uri);
     } else {
         if ($request_uri == $base_path) {
             //The front page is set to /user. we have to login here to avoid a redirect loop
             $username = CosignSharedFunctions::cosign_retrieve_remote_user();
             $user = CosignSharedFunctions::cosign_user_status($username);
             if (empty($user) || $user->id() == 0) {
                 $response = array('#type' => 'markup', '#title' => 'Auto creation of user accounts is disabled.', '#markup' => t('<p>This site does not auto create users from cosign. Please contact the <a href="mailto:' . \Drupal::config("system.site")->get("mail") . '">site administrator</a> to have an account created.</p>'));
                 return $response;
             } else {
                 if (in_array('administrator', $user->getRoles())) {
                     drupal_set_message('When the homepage is set to /user (Drupal default), anonymous browsing will not always work', 'warning');
                 }
                 $referrer = $base_path . 'user';
             }
         } elseif (isset($_SERVER['HTTP_REFERER'])) {
             $referrer = $_SERVER['HTTP_REFERER'];
         } else {
             $referrer = $base_path;
         }
         return new TrustedRedirectResponse($referrer);
     }
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function create(array $values = array())
 {
     $store_config = \Drupal::config('uc_store.settings');
     // Set the primary email address.
     if (empty($values['primary_email']) && !empty($values['uid'])) {
         if ($account = User::load($values['uid'])) {
             $values['primary_email'] = $account->mail;
         }
     }
     // Set the default order status.
     if (empty($values['order_status'])) {
         $values['order_status'] = uc_order_state_default('in_checkout');
     }
     // Set the default currency.
     if (empty($values['currency'])) {
         $values['currency'] = $store_config->get('currency.code');
     }
     // Set the default country codes.
     if (empty($values['billing_country'])) {
         $values['billing_country'] = $store_config->get('address.country');
     }
     if (empty($values['delivery_country'])) {
         $values['delivery_country'] = $store_config->get('address.country');
     }
     // Set the created time to now.
     if (empty($values['created'])) {
         $values['created'] = REQUEST_TIME;
     }
     return parent::create($values);
 }
 /**
  * Tests the format_date() function.
  */
 function testFormatDate()
 {
     $timestamp = strtotime('2007-03-26T00:00:00+00:00');
     $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Sunday, 25-Mar-07 17:00:00 PDT', 'Test all parameters.');
     $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'domingo, 25-Mar-07 17:00:00 PDT', 'Test translated format.');
     $this->assertIdentical(format_date($timestamp, 'custom', '\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'l, 25-Mar-07 17:00:00 PDT', 'Test an escaped format string.');
     $this->assertIdentical(format_date($timestamp, 'custom', '\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), '\\domingo, 25-Mar-07 17:00:00 PDT', 'Test format containing backslash character.');
     $this->assertIdentical(format_date($timestamp, 'custom', '\\\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), '\\l, 25-Mar-07 17:00:00 PDT', 'Test format containing backslash followed by escaped format string.');
     $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London', 'en'), 'Monday, 26-Mar-07 01:00:00 BST', 'Test a different time zone.');
     // Change the default language and timezone.
     \Drupal::config('system.site')->set('langcode', static::LANGCODE)->save();
     date_default_timezone_set('America/Los_Angeles');
     $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Sunday, 25-Mar-07 17:00:00 PDT', 'Test a different language.');
     $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London'), 'Monday, 26-Mar-07 01:00:00 BST', 'Test a different time zone.');
     $this->assertIdentical(format_date($timestamp, 'custom', 'l, d-M-y H:i:s T'), 'domingo, 25-Mar-07 17:00:00 PDT', 'Test custom date format.');
     $this->assertIdentical(format_date($timestamp, 'long'), 'domingo, 25. marzo 2007 - 17:00', 'Test long date format.');
     $this->assertIdentical(format_date($timestamp, 'medium'), '25. marzo 2007 - 17:00', 'Test medium date format.');
     $this->assertIdentical(format_date($timestamp, 'short'), '2007 Mar 25 - 5:00pm', 'Test short date format.');
     $this->assertIdentical(format_date($timestamp), '25. marzo 2007 - 17:00', 'Test default date format.');
     // Test HTML time element formats.
     $this->assertIdentical(format_date($timestamp, 'html_datetime'), '2007-03-25T17:00:00-0700', 'Test html_datetime date format.');
     $this->assertIdentical(format_date($timestamp, 'html_date'), '2007-03-25', 'Test html_date date format.');
     $this->assertIdentical(format_date($timestamp, 'html_time'), '17:00:00', 'Test html_time date format.');
     $this->assertIdentical(format_date($timestamp, 'html_yearless_date'), '03-25', 'Test html_yearless_date date format.');
     $this->assertIdentical(format_date($timestamp, 'html_week'), '2007-W12', 'Test html_week date format.');
     $this->assertIdentical(format_date($timestamp, 'html_month'), '2007-03', 'Test html_month date format.');
     $this->assertIdentical(format_date($timestamp, 'html_year'), '2007', 'Test html_year date format.');
 }
 public function __construct()
 {
     $this->connection = \Drupal\Core\Database\Database::getConnection();
     $this->module_config = \Drupal::config('sociallogin.settings');
     $this->apiSecret = trim($this->module_config->get('api_secret'));
     $this->apiKey = trim($this->module_config->get('api_key'));
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, array &$form_state)
 {
     $feed = $this->entity;
     $importer = $feed->getImporter();
     $args = array('@importer' => $importer->label(), '@title' => $feed->label());
     if ($this->operation == 'update') {
         drupal_set_title($this->t('<em>Edit @importer</em> @title', $args), PASS_THROUGH);
     } elseif ($this->operation == 'create') {
         drupal_set_title($this->t('<em>Add @importer</em>', $args), PASS_THROUGH);
     }
     $user_config = \Drupal::config('user.settings');
     $form['title'] = array('#type' => 'textfield', '#title' => $this->t('Title'), '#default_value' => $feed->label(), '#required' => TRUE);
     foreach ($importer->getPlugins() as $plugin) {
         if ($plugin instanceof FeedPluginFormInterface) {
             // Store the plugin for validate and submit.
             $this->configurablePlugins[] = $plugin;
             $form = $plugin->buildFeedForm($form, $form_state, $feed);
         }
     }
     $form['advanced'] = array('#type' => 'vertical_tabs', '#weight' => 99);
     // Feed author information for administrators.
     $form['author'] = array('#type' => 'details', '#access' => $this->currentUser()->hasPermission('administer feeds'), '#title' => $this->t('Authoring information'), '#collapsed' => TRUE, '#group' => 'advanced', '#weight' => 90);
     $form['author']['name'] = array('#type' => 'textfield', '#title' => $this->t('Authored by'), '#maxlength' => 60, '#autocomplete_path' => 'user/autocomplete', '#default_value' => $feed->getAuthor()->getUsername(), '#description' => $this->t('Leave blank for %anonymous.', array('%anonymous' => $user_config->get('anonymous'))));
     $form['author']['date'] = array('#type' => 'textfield', '#title' => $this->t('Authored on'), '#maxlength' => 25, '#description' => $this->t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', array('%time' => format_date($feed->getCreatedTime(), 'custom', 'Y-m-d H:i:s O'), '%timezone' => format_date($feed->getCreatedTime(), 'custom', 'O'))));
     // Feed options for administrators.
     $form['options'] = array('#type' => 'details', '#access' => $this->currentUser()->hasPermission('administer feeds'), '#title' => $this->t('Import options'), '#collapsed' => TRUE, '#group' => 'advanced');
     $form['options']['status'] = array('#type' => 'checkbox', '#title' => $this->t('Active'), '#default_value' => $feed->isActive());
     return parent::form($form, $form_state);
 }
 /**
  * Tests export of configuration.
  */
 function testExport()
 {
     // Verify the export page with export submit button is available.
     $this->drupalGet('admin/config/development/configuration/full/export');
     $this->assertFieldById('edit-submit', t('Export'));
     // Submit the export form and verify response.
     $this->drupalPostForm('admin/config/development/configuration/full/export', array(), t('Export'));
     $this->assertResponse(200, 'User can access the download callback.');
     // Get the archived binary file provided to user for download.
     $archive_data = $this->drupalGetContent();
     // Temporarily save the archive file.
     $uri = file_unmanaged_save_data($archive_data, 'temporary://config.tar.gz');
     // Extract the archive and verify it's not empty.
     $file_path = file_directory_temp() . '/' . file_uri_target($uri);
     $archiver = new Tar($file_path);
     $archive_contents = $archiver->listContents();
     $this->assert(!empty($archive_contents), 'Downloaded archive file is not empty.');
     // Prepare the list of config files from active storage, see
     // \Drupal\config\Controller\ConfigController::downloadExport().
     $storage_active = $this->container->get('config.storage');
     $config_files = array();
     foreach ($storage_active->listAll() as $config_name) {
         $config_files[] = $config_name . '.yml';
     }
     // Assert that the downloaded archive file contents are the same as the test
     // site active store.
     $this->assertIdentical($archive_contents, $config_files);
     // Ensure the test configuration override is in effect but was not exported.
     $this->assertIdentical(\Drupal::config('system.maintenance')->get('message'), 'Foo');
     $archiver->extract(file_directory_temp(), array('system.maintenance.yml'));
     $file_contents = file_get_contents(file_directory_temp() . '/' . 'system.maintenance.yml');
     $exported = Yaml::decode($file_contents);
     $this->assertNotIdentical($exported['message'], 'Foo');
 }
  /**
   * Test a basic file upload with File (Field) Paths.
   */
  public function testUploadFile() {
    $file_system = \Drupal::service('file_system');

    // Create a File field with 'node/[node:nid]' as the File path and
    // '[node:nid].[file:ffp-extension-original]' as the File name.
    $field_name = Unicode::strtolower($this->randomMachineName());
    $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:nid]';
    $third_party_settings['filefield_paths']['file_name']['value'] = '[node:nid].[file:ffp-extension-original]';
    $this->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings);

    // Create a node with a test file.
    /** @var \Drupal\file\Entity\File $test_file */
    $test_file = $this->getTestFile('text');
    $this->drupalGet("node/add/{$this->contentType}");
    $edit['title[0][value]'] = $this->randomMachineName();
    $edit["files[{$field_name}_0]"] = $file_system->realpath($test_file->getFileUri());
    $this->drupalPostForm(NULL, $edit, t('Upload'));

    // Ensure that the file was put into the Temporary file location.
    $config = \Drupal::config('filefield_paths.settings');
    $this->assertRaw(file_create_url("{$config->get('temp_location')}/{$test_file->getFilename()}"), $this->t('File has been uploaded to the temporary file location.'));

    // Save the node.
    $this->drupalPostForm(NULL, [], t('Save and publish'));

    // Get created Node ID.
    $matches = [];
    preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
    $nid = $matches[1];

    // Ensure that the File path has been processed correctly.
    $this->assertRaw("{$this->publicFilesDirectory}/node/{$nid}/{$nid}.txt", $this->t('The File path has been processed correctly.'));
  }
Example #21
0
/**
 * Alter the REST relation URI.
 *
 * Modules may wish to alter the relation URI generated for a resource based on
 * the context of the serializer/normalizer operation.
 *
 * @param string $uri
 *   The URI to alter.
 * @param array $context
 *   The context from the serializer/normalizer operation.
 *
 * @see \Symfony\Component\Serializer\SerializerInterface::serialize()
 * @see \Symfony\Component\Serializer\SerializerInterface::deserialize()
 * @see \Symfony\Component\Serializer\NormalizerInterface::normalize()
 * @see \Symfony\Component\Serializer\DenormalizerInterface::denormalize()
 */
function hook_rest_relation_uri_alter(&$uri, $context = array())
{
    if ($context['mymodule'] == TRUE) {
        $base = \Drupal::config('rest.settings')->get('link_domain');
        $uri = str_replace($base, 'http://mymodule.domain', $uri);
    }
}
 /**
  * Test the creation of a field instance.
  */
 function testCreateFieldInstance()
 {
     $instance = entity_create('field_instance_config', $this->instanceDefinition);
     $instance->save();
     // Read the configuration. Check against raw configuration data rather than
     // the loaded ConfigEntity, to be sure we check that the defaults are
     // applied on write.
     $config = \Drupal::config('field.instance.' . $instance->id())->get();
     $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
     // Check that default values are set.
     $this->assertEqual($config['required'], FALSE, 'Required defaults to false.');
     $this->assertIdentical($config['label'], $this->instanceDefinition['field_name'], 'Label defaults to field name.');
     $this->assertIdentical($config['description'], '', 'Description defaults to empty string.');
     // Check that default settings are set.
     $this->assertEqual($config['settings'], $field_type_manager->getDefaultInstanceSettings($this->fieldStorageDefinition['type']), 'Default instance settings have been written.');
     // Check that the denormalized 'field_type' was properly written.
     $this->assertEqual($config['field_type'], $this->fieldStorageDefinition['type']);
     // Guarantee that the field/bundle combination is unique.
     try {
         entity_create('field_instance_config', $this->instanceDefinition)->save();
         $this->fail(t('Cannot create two instances with the same field / bundle combination.'));
     } catch (EntityStorageException $e) {
         $this->pass(t('Cannot create two instances with the same field / bundle combination.'));
     }
     // Check that the specified field exists.
     try {
         $this->instanceDefinition['field_name'] = $this->randomMachineName();
         entity_create('field_instance_config', $this->instanceDefinition)->save();
         $this->fail(t('Cannot create an instance of a non-existing field.'));
     } catch (FieldException $e) {
         $this->pass(t('Cannot create an instance of a non-existing field.'));
     }
     // TODO: test other failures.
 }
 /**
  * Test our new email form.
  *
  * Tests for the following:
  *
  * - A link to the email_example in the Tools menu.
  * - That you can successfully access the email_example page.
  */
 public function testEmailExampleBasic()
 {
     // Test for a link to the email_example in the Tools menu.
     $this->drupalGet('');
     $this->assertResponse(200, 'The Home page is available.');
     $this->assertLinkByHref('examples/email_example');
     // Verify if we can successfully access the email_example page.
     $this->drupalGet('examples/email_example');
     $this->assertResponse(200, 'The Email Example description page is available.');
     // Verifiy email form has email & message fields.
     $this->assertFieldById('edit-email', NULL, 'The email field appears.');
     $this->assertFieldById('edit-message', NULL, 'The message field appears.');
     // Verifiy email form is submitted.
     $edit = array('email' => '*****@*****.**', 'message' => 'test');
     $this->drupalPostForm('examples/email_example', $edit, t('Submit'));
     $this->assertResponse(200);
     // Verifiy comfirmation page.
     $this->assertText(t('Your message has been sent.'), 'The text "Your message has been sent." appears on the email example page.', 'Form response with the right message.');
     $this->assertMailString('to', $edit['email'], 1);
     // Verifiy correct email recieved.
     $from = \Drupal::config('system.site')->get('mail');
     $t_options = array('langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId());
     $this->assertMailString('subject', t('E-mail sent from @site-name', array('@site-name' => $from), $t_options), 1);
     $this->assertMailString('body', $edit['message'], 1);
     $this->assertMailString('body', t("\n--\nMail altered by email_example module.", array(), $t_options), 1);
 }
Example #24
0
/**
 * Defines shipping types for shipping methods.
 *
 * This hook defines a shipping type that this module is designed to handle.
 * These types are specified by a machine- and human-readable name called 'id',
 * and 'title' respectively. Shipping types may be set for individual products,
 * manufacturers, and for the entire store catalog. Shipping modules should be
 * careful to use the same shipping type ids as other similar shipping modules
 * (i.e., FedEx and UPS both operate on "small package" shipments). Modules that
 * do not fulfill orders may not need to implement this hook.
 *
 * @return
 *   An array of shipping types keyed by a machine-readable name.
 */
function hook_uc_shipping_type()
{
    $weight = \Drupal::config('uc_quote.settings')->get('type_weight');
    $types = array();
    $types['small_package'] = array('id' => 'small_package', 'title' => t('Small package'), 'weight' => $weight['small_package']);
    return $types;
}
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     $view = $this->entity;
     $form['#prefix'] = '<div id="views-preview-wrapper" class="views-admin clearfix">';
     $form['#suffix'] = '</div>';
     $form['#id'] = 'views-ui-preview-form';
     // Reset the cache of IDs. Drupal rather aggressively prevents ID
     // duplication but this causes it to remember IDs that are no longer even
     // being used.
     $seen_ids_init =& drupal_static('drupal_html_id:init');
     $seen_ids_init = array();
     $form_state['no_cache'] = TRUE;
     $form['controls']['#attributes'] = array('class' => array('clearfix'));
     // Add a checkbox controlling whether or not this display auto-previews.
     $form['controls']['live_preview'] = array('#type' => 'checkbox', '#id' => 'edit-displays-live-preview', '#title' => $this->t('Auto preview'), '#default_value' => \Drupal::config('views.settings')->get('ui.always_live_preview'));
     // Add the arguments textfield
     $form['controls']['view_args'] = array('#type' => 'textfield', '#title' => $this->t('Preview with contextual filters:'), '#description' => $this->t('Separate contextual filter values with a "/". For example, %example.', array('%example' => '40/12/10')), '#id' => 'preview-args');
     $args = array();
     if (!empty($form_state['values']['view_args'])) {
         $args = explode('/', $form_state['values']['view_args']);
     }
     if (!empty($form_state['show_preview']) || !empty($form_state['input']['js'])) {
         $form['preview'] = array('#weight' => 110, '#theme_wrappers' => array('container'), '#attributes' => array('id' => 'views-live-preview'), '#markup' => $view->renderPreview($this->displayID, $args));
     }
     $uri = $view->urlInfo('preview-form');
     $uri->setRouteParameter('display_id', $this->displayID);
     $form['#action'] = $uri->toString();
     return $form;
 }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function getAssets($types = NULL)
 {
     $assets = [];
     // If no type is set, return all CSS and JS.
     if (!isset($types)) {
         $types = ['css', 'js'];
     }
     $types = is_array($types) ? $types : [$types];
     // Ensure default arrays exist for the requested types.
     foreach ($types as $type) {
         $assets[$type] = [];
     }
     // Iterate over each type.
     foreach ($types as $type) {
         $files = \Drupal::config("preprocess_{$type}") && isset($this->assets['min'][$type]) ? $this->assets['min'][$type] : (isset($this->assets[$type]) ? $this->assets[$type] : []);
         foreach ($files as $asset) {
             $data = ['data' => $asset, 'type' => 'external', 'weight' => -19.999];
             // CSS library assets use "SMACSS" categorization, assign it to "base".
             if ($type === 'css') {
                 $assets[$type]['base'][$asset] = $data;
             } else {
                 $assets[$type][$asset] = $data;
             }
         }
     }
     return count($types) === 1 ? $assets[$types[0]] : $assets;
 }
 /**
  * {@inheritdoc}
  */
 public function getDerivativeDefinitions($base_definition)
 {
     $derivatives = [];
     $config = \Drupal::config('drupalmoduleupgrader.functions')->get();
     foreach ($config as $key => $info) {
         // Only disable functions that have been explicitly marked for disabling.
         if (empty($info['disable'])) {
             continue;
         }
         // $key can either be the name of a single function, or an arbitrary string
         // identifying a group of functions to handle.
         if (empty($info['functions'])) {
             $info['functions'] = [$key];
         }
         foreach ($info['functions'] as $function) {
             $derivative = $base_definition;
             $variables = ['@function' => $function . '()'];
             $derivative['function'] = $function;
             $derivative['description'] = $this->t('Disables calls to @function().', $variables);
             if (isset($info['fixme'])) {
                 $derivative['fixme'] = $this->t($info['fixme'], $variables);
             }
             $derivative['documentation'] = $info['documentation'];
             $derivatives[$function] = $derivative;
         }
     }
     return $derivatives;
 }
Example #28
0
 public function testAddressFormat()
 {
     $address = new Address();
     $address->country = NULL;
     $formatted = (string) $address;
     $expected = '';
     $this->assertEqual($formatted, $expected, 'Formatted empty address is an empty string.');
     $address = $this->test_address[1];
     // Expected format depends on the store country.
     $store_country = \Drupal::config('uc_store.settings')->get('address.country');
     $formatted = (string) $address;
     if ($store_country == 'US') {
         $expected = "CTW, INC.<br>\nELMO MONSTER<br>\n123 SESAME STREET<br>\nNEW YORK, NY 10010";
     } else {
         $expected = "CTW, INC.<br>\nELMO MONSTER<br>\n123 SESAME STREET<br>\nNEW YORK, NY 10010<br>\nUNITED STATES";
     }
     $this->assertEqual($formatted, $expected, 'Formatted address matches expected value.');
     $address->city = 'Victoria';
     $address->zone = 'BC';
     $address->country = 'CA';
     $formatted = (string) $address;
     if ($store_country == 'CA') {
         $expected = "CTW, INC.<br>\nELMO MONSTER<br>\n123 SESAME STREET<br>\nVICTORIA BC  10010";
     } else {
         $expected = "CTW, INC.<br>\nELMO MONSTER<br>\n123 SESAME STREET<br>\nVICTORIA BC  10010<br>\nCANADA";
     }
     $this->assertEqual($formatted, $expected, 'Formatted address with non-default country matches expected value.');
 }
Example #29
0
 public function testUserHooks()
 {
     FieldStorageConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user'))->save();
     FieldConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user', 'bundle' => 'user'))->save();
     $this->assertIdentical('', \Drupal::config('name.settings')->get('user_preferred'));
     FieldStorageConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user'))->save();
     FieldStorageConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user'))->save();
     $field = FieldConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
     $field->save();
     $field2 = FieldConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
     $field2->save();
     $this->assertEqual($field->getName(), \Drupal::config('name.settings')->get('user_preferred'));
     \Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field2->getName())->save();
     $field2->delete();
     $this->assertEqual('', \Drupal::config('name.settings')->get('user_preferred'));
     \Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field->getName())->save();
     $account = User::create(array('name' => 'test'));
     $account->field_name_test[0] = array('given' => 'Max', 'family' => 'Mustermann');
     $account->save();
     $account = User::load($account->id());
     $this->assertEqual('Max Mustermann', $account->realname);
     $this->assertEqual('Max Mustermann', user_format_name($account));
     $this->assertEqual('test', $account->getUsername());
     $this->assertEqual('Max Mustermann', $account->getDisplayName());
 }
Example #30
0
 /**
  * {@inheritdoc}
  */
 public function getPathByAlias($alias, $langcode = NULL)
 {
     // If no language is explicitly specified we default to the current URL
     // language. If we used a language different from the one conveyed by the
     // requested URL, we might end up being unable to check if there is a path
     // alias matching the URL path.
     $langcode = $langcode ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId();
     // If we already know that there are no paths for this alias simply return.
     if (empty($alias) || !empty($this->noPath[$langcode][$alias])) {
         return \Drupal::config('system.site')->get('page.front');
     }
     // Look for the alias within the cached map.
     if (isset($this->lookupMap[$langcode]) && ($path = array_search($alias, $this->lookupMap[$langcode]))) {
         return $path;
     }
     // Look for path in storage.
     if ($path = $this->storage->lookupPathSource($alias, $langcode)) {
         $this->lookupMap[$langcode][$path] = $alias;
         return $path;
     }
     // We can't record anything into $this->lookupMap because we didn't find any
     // paths for this alias. Thus cache to $this->noPath.
     $this->noPath[$langcode][$alias] = TRUE;
     return $alias;
 }