Exemple #1
0
 /**
  * {@inheritdoc}
  */
 public function setPluralFormula($langcode, $plural_count, array $formula)
 {
     // Ensure that the formulae are loaded.
     $this->loadFormulae();
     $this->formulae[$langcode] = ['plurals' => $plural_count, 'formula' => $formula];
     $this->state->set('locale.translation.formulae', $this->formulae);
     return $this;
 }
Exemple #2
0
 /**
  * {@inheritdoc}
  */
 public function import(Row $row, array $old_destination_id_values = array())
 {
     if ($row->isStub() && ($state = $this->state->get('comment.maintain_entity_statistics', 0))) {
         $this->state->set('comment.maintain_entity_statistics', 0);
     }
     $return = parent::import($row, $old_destination_id_values);
     if ($row->isStub() && $state) {
         $this->state->set('comment.maintain_entity_statistics', $state);
     }
     return $return;
 }
 /**
  * Tests that changes to the info file are picked up.
  */
 public function testChanges()
 {
     $this->themeHandler->install(array('test_theme'));
     $this->themeHandler->setDefault('test_theme');
     $this->themeManager->resetActiveTheme();
     $active_theme = $this->themeManager->getActiveTheme();
     // Make sure we are not testing the wrong theme.
     $this->assertEqual('test_theme', $active_theme->getName());
     $this->assertEqual(['classy/base', 'core/normalize', 'test_theme/global-styling'], $active_theme->getLibraries());
     // @see theme_test_system_info_alter()
     $this->state->set('theme_test.modify_info_files', TRUE);
     drupal_flush_all_caches();
     $active_theme = $this->themeManager->getActiveTheme();
     $this->assertEqual(['classy/base', 'core/normalize', 'test_theme/global-styling', 'core/backbone'], $active_theme->getLibraries());
 }
 /**
  * Tests task system integration for the deleteAllIndexItems() method.
  */
 public function testDeleteAllIndexItems()
 {
     // Set exception for deleteAllIndexItems() and reset the list of successful
     // backend method calls.
     $this->state->set('search_api_test_backend.exception.deleteAllIndexItems', TRUE);
     $this->getCalledServerMethods();
     // Try to update the index.
     $this->server->deleteAllIndexItems($this->index);
     $this->assertEqual($this->getCalledServerMethods(), array(), 'deleteAllIndexItems correctly threw an exception.');
     $tasks = $this->getServerTasks();
     if (count($tasks) == 1) {
         $task_created = $tasks[0]->type === 'deleteAllIndexItems';
     }
     $this->assertTrue(!empty($task_created), 'The deleteAllIndexItems task was successfully added.');
     if ($tasks) {
         $this->assertEqual($tasks[0]->index_id, $this->index->id(), 'The right index ID was used for the deleteAllIndexItems task.');
     }
     // Check whether other task-system-integrated methods now fail, too.
     $this->server->updateIndex($this->index);
     $this->assertEqual($this->getCalledServerMethods(), array(), 'updateIndex was not executed.');
     $tasks = $this->getServerTasks();
     if (count($tasks) == 2) {
         $this->pass("Second task ('updateIndex') was added.");
         $this->assertEqual($tasks[0]->type, 'deleteAllIndexItems', 'First task stayed the same.');
         $this->assertEqual($tasks[1]->type, 'updateIndex', 'New task was queued as last.');
     } else {
         $this->fail("Second task (updateIndex) was not added.");
     }
     // Let deleteAllIndexItems() succeed again, then trigger the task execution
     // with a call to indexItems().
     $this->state->set('search_api_test_backend.exception.deleteAllIndexItems', FALSE);
     $this->server->indexItems($this->index, array());
     $this->assertEqual($this->getServerTasks(), array(), 'Server tasks were correctly executed.');
     $this->assertEqual($this->getCalledServerMethods(), array('deleteAllIndexItems', 'updateIndex', 'indexItems'), 'Right methods were called during task execution.');
 }
 /**
  * {@inheritdoc}
  */
 public function stopTracking(IndexInterface $index, array $datasource_ids = NULL)
 {
     $valid_tracker = $index->hasValidTracker();
     if (!isset($datasource_ids)) {
         $this->state->delete($this->getIndexStateKey($index));
         if ($valid_tracker) {
             $index->getTrackerInstance()->trackAllItemsDeleted();
         }
         return;
     }
     // Catch the case of being called with an empty array of datasources.
     if (!$datasource_ids) {
         return;
     }
     // If no state is saved, this will return NULL, making the following unset()
     // statements no-ops.
     $index_state = $this->getIndexState($index, FALSE);
     foreach ($datasource_ids as $datasource_id) {
         unset($index_state['pages'][$datasource_id]);
         if ($valid_tracker) {
             $index->getTrackerInstance()->trackAllItemsDeleted($datasource_id);
         }
     }
     // If we had an index state saved, update it now.
     if (isset($index_state)) {
         if (empty($index_state['pages'])) {
             $this->state->delete($this->getIndexStateKey($index));
         } else {
             $this->state->set($this->getIndexStateKey($index), $index_state);
         }
     }
 }
Exemple #6
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $this->config('system.site')->set('name', (string) $form_state->getValue('site_name'))->set('mail', (string) $form_state->getValue('site_mail'))->save(TRUE);
     $this->config('system.date')->set('timezone.default', (string) $form_state->getValue('date_default_timezone'))->set('country.default', (string) $form_state->getValue('site_default_country'))->save(TRUE);
     $account_values = $form_state->getValue('account');
     // Enable update.module if this option was selected.
     $update_status_module = $form_state->getValue('update_status_module');
     if ($update_status_module[1]) {
         $this->moduleInstaller->install(array('file', 'update'), FALSE);
         // Add the site maintenance account's email address to the list of
         // addresses to be notified when updates are available, if selected.
         if ($update_status_module[2]) {
             // Reset the configuration factory so it is updated with the new module.
             $this->resetConfigFactory();
             $this->config('update.settings')->set('notification.emails', array($account_values['mail']))->save(TRUE);
         }
     }
     // We precreated user 1 with placeholder values. Let's save the real values.
     $account = $this->userStorage->load(1);
     $account->init = $account->mail = $account_values['mail'];
     $account->roles = $account->getRoles();
     $account->activate();
     $account->timezone = $form_state->getValue('date_default_timezone');
     $account->pass = $account_values['pass'];
     $account->name = $account_values['name'];
     $account->save();
     // Record when this install ran.
     $this->state->set('install_time', $_SERVER['REQUEST_TIME']);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $modules = $input->getArgument('module');
     if (!$this->lock->acquire('cron', 900.0)) {
         $io->warning($this->trans('commands.cron.execute.messages.lock'));
         return 1;
     }
     if (in_array('all', $modules)) {
         $modules = $this->moduleHandler->getImplementations('cron');
     }
     foreach ($modules as $module) {
         if (!$this->moduleHandler->implementsHook($module, 'cron')) {
             $io->warning(sprintf($this->trans('commands.cron.execute.messages.module-invalid'), $module));
             continue;
         }
         try {
             $io->info(sprintf($this->trans('commands.cron.execute.messages.executing-cron'), $module));
             $this->moduleHandler->invoke($module, 'cron');
         } catch (\Exception $e) {
             watchdog_exception('cron', $e);
             $io->error($e->getMessage());
         }
     }
     $this->state->set('system.cron_last', REQUEST_TIME);
     $this->lock->release('cron');
     $this->chainQueue->addCommand('cache:rebuild', ['cache' => 'all']);
     $io->success($this->trans('commands.cron.execute.messages.success'));
     return 0;
 }
 /**
  * Returns the entity_test hook invocation info.
  *
  * @return array
  *   An associative array of arbitrary hook data keyed by hook name.
  */
 protected function getHooksInfo()
 {
     $key = 'entity_test.hooks';
     $hooks = $this->state->get($key);
     $this->state->set($key, array());
     return $hooks;
 }
Exemple #9
0
 /**
  * Reacts to a config delete and records information in state for testing.
  *
  * @param \Drupal\Core\Config\ConfigCrudEvent $event
  */
 public function onConfigDelete(ConfigCrudEvent $event)
 {
     $config = $event->getConfig();
     if ($config->getName() == 'action.settings') {
         $value = $this->state->get('ConfigImportUITest.action.settings.delete', 0);
         $this->state->set('ConfigImportUITest.action.settings.delete', $value + 1);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state) {
   $show_global = $form_state->getValue('block_visibility_group_show_global', 1);
   $this->state->set('block_visibility_group_show_global', $show_global);
   // Prevent sending an empty value, which would unset all blocks.
   if (!empty($form_state->getValue('blocks'))) {
     parent::submitForm($form, $form_state);
   }
 }
 /**
  * {@inheritdoc}
  */
 public function delete(array $entities)
 {
     $return = parent::delete($entities);
     // Update the state of registered events.
     // @todo Should we trigger a container rebuild here as well? Might be a bit
     // expensive on every delete?
     $this->stateService->set('rules.registered_events', $this->getRegisteredEvents());
     return $return;
 }
Exemple #12
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Save the state
     $values = $form_state->getValues();
     $this->state->set($values['state_name'], $values['parsed_value']);
     $form_state->setRedirectUrl(Url::fromRoute('devel.state_system_page'));
     drupal_set_message($this->t('Variable %variable was successfully edited.', array('%variable' => $values['state_name'])));
     $this->logger('devel')->info('Variable %variable was successfully edited.', array('%variable' => $values['state_name']));
 }
 /**
  * Submission handler for the confirmation form.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public function submitConfirmForm(array &$form, FormStateInterface $form_state)
 {
     $storage = $form_state->getStorage();
     $migrations = $storage['migrations'];
     $config['source_base_path'] = $storage['source_base_path'];
     $batch = ['title' => $this->t('Running upgrade'), 'progress_message' => '', 'operations' => [[[MigrateUpgradeRunBatch::class, 'run'], [array_keys($migrations), 'import', $config]]], 'finished' => [MigrateUpgradeRunBatch::class, 'finished']];
     batch_set($batch);
     $form_state->setRedirect('<front>');
     $this->state->set('migrate_drupal_ui.performed', REQUEST_TIME);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     //$state = $this->getDrupalService('state');
     $io->info($this->trans('commands.site.maintenance.messages.maintenance-on'));
     $io->info($this->trans('commands.update.entities.messages.start'));
     $this->state->set('system.maintenance_mode', true);
     try {
         $this->entityDefinitionUpdateManager->applyUpdates();
         /* @var EntityStorageException $e */
     } catch (EntityStorageException $e) {
         /* @var Error $variables */
         $variables = Error::decodeException($e);
         $io->info($this->trans('commands.update.entities.messages.error'));
         $io->info($variables);
     }
     $this->state->set('system.maintenance_mode', false);
     $io->info($this->trans('commands.update.entities.messages.end'));
     $this->chainQueue->addCommand('cache:rebuild', ['cache' => 'all']);
     $io->info($this->trans('commands.site.maintenance.messages.maintenance-off'));
 }
 /**
  * Tests state edit.
  */
 public function testStateEdit()
 {
     // Create some state variables for the test.
     $this->state->set('devel.simple', 0);
     $this->state->set('devel.array', ['devel' => 'value']);
     $this->state->set('devel.object', $this->randomObject());
     // Ensure that state edit form is accessible only by users with the
     // adequate permissions.
     $this->drupalLogin($this->develUser);
     $this->drupalGet('devel/state/edit/devel.simple');
     $this->assertResponse(403);
     $this->drupalLogin($this->adminUser);
     // Ensure that accessing an un-existent state variable cause a warning
     // message.
     $this->drupalGet('devel/state/edit/devel.unknown');
     $this->assertText(t('State @name does not exist in the system.', ['@name' => 'devel.unknown']));
     // Ensure that state variables that contain simple type can be edited and
     // saved.
     $this->drupalGet('devel/state/edit/devel.simple');
     $this->assertResponse(200);
     $this->assertText(t('Edit state variable: @name', ['@name' => 'devel.simple']));
     $this->assertInputNotDisabledById('edit-new-value');
     $this->assertInputNotDisabledById('edit-submit');
     $edit = ['new_value' => 1];
     $this->drupalPostForm('devel/state/edit/devel.simple', $edit, t('Save'));
     $this->assertText(t('Variable @name was successfully edited.', ['@name' => 'devel.simple']));
     $this->assertEqual(1, $this->state->get('devel.simple'));
     // Ensure that state variables that contain array can be edited and saved
     // and the new value is properly validated.
     $this->drupalGet('devel/state/edit/devel.array');
     $this->assertResponse(200);
     $this->assertText(t('Edit state variable: @name', ['@name' => 'devel.array']));
     $this->assertInputNotDisabledById('edit-new-value');
     $this->assertInputNotDisabledById('edit-submit');
     // Try to save an invalid yaml input.
     $edit = ['new_value' => 'devel: \'value updated'];
     $this->drupalPostForm('devel/state/edit/devel.array', $edit, t('Save'));
     $this->assertText(t('Invalid input:'));
     $edit = ['new_value' => 'devel: \'value updated\''];
     $this->drupalPostForm('devel/state/edit/devel.array', $edit, t('Save'));
     $this->assertText(t('Variable @name was successfully edited.', ['@name' => 'devel.array']));
     $this->assertEqual(['devel' => 'value updated'], $this->state->get('devel.array'));
     // Ensure that state variables that contain objects cannot be edited.
     $this->drupalGet('devel/state/edit/devel.object');
     $this->assertResponse(200);
     $this->assertText(t('Edit state variable: @name', ['@name' => 'devel.object']));
     $this->assertText(t('Only simple structures are allowed to be edited. State @name contains objects.', ['@name' => 'devel.object']));
     $this->assertInputDisabledById('edit-new-value');
     $this->assertInputDisabledById('edit-submit');
     // Ensure that the cancel link works as expected.
     $this->clickLink(t('Cancel'));
     $this->assertUrl('devel/state');
 }
Exemple #16
0
 /**
  * Starts the database update batch process.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request object.
  */
 protected function triggerBatch(Request $request)
 {
     $maintenance_mode = $this->state->get('system.maintenance_mode', FALSE);
     // Store the current maintenance mode status in the session so that it can
     // be restored at the end of the batch.
     $_SESSION['maintenance_mode'] = $maintenance_mode;
     // During the update, always put the site into maintenance mode so that
     // in-progress schema changes do not affect visiting users.
     if (empty($maintenance_mode)) {
         $this->state->set('system.maintenance_mode', TRUE);
     }
     $operations = array();
     // Resolve any update dependencies to determine the actual updates that will
     // be run and the order they will be run in.
     $start = $this->getModuleUpdates();
     $updates = update_resolve_dependencies($start);
     // Store the dependencies for each update function in an array which the
     // batch API can pass in to the batch operation each time it is called. (We
     // do not store the entire update dependency array here because it is
     // potentially very large.)
     $dependency_map = array();
     foreach ($updates as $function => $update) {
         $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array();
     }
     // Determine updates to be performed.
     foreach ($updates as $function => $update) {
         if ($update['allowed']) {
             // Set the installed version of each module so updates will start at the
             // correct place. (The updates are already sorted, so we can simply base
             // this on the first one we come across in the above foreach loop.)
             if (isset($start[$update['module']])) {
                 drupal_set_installed_schema_version($update['module'], $update['number'] - 1);
                 unset($start[$update['module']]);
             }
             $operations[] = array('update_do_one', array($update['module'], $update['number'], $dependency_map[$function]));
         }
     }
     $post_updates = $this->postUpdateRegistry->getPendingUpdateFunctions();
     if ($post_updates) {
         // Now we rebuild all caches and after that execute the hook_post_update()
         // functions.
         $operations[] = ['drupal_flush_all_caches', []];
         foreach ($post_updates as $function) {
             $operations[] = ['update_invoke_post_update', [$function]];
         }
     }
     $batch['operations'] = $operations;
     $batch += array('title' => $this->t('Updating'), 'init_message' => $this->t('Starting updates'), 'error_message' => $this->t('An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.'), 'finished' => array('\\Drupal\\system\\Controller\\DbUpdateController', 'batchFinished'));
     batch_set($batch);
     // @todo Revisit once https://www.drupal.org/node/2548095 is in.
     return batch_process(Url::fromUri('base://results'), Url::fromUri('base://start'));
 }
 protected function assertFlag($variable, $assert_value = TRUE, $reset_if_true = TRUE)
 {
     $value = xmlsitemap_var($variable);
     if ($reset_if_true && $value) {
         $state_variables = xmlsitemap_state_variables();
         if (isset($state_variables[$variable])) {
             $this->state->set($variable, FALSE);
         } else {
             $this->config->set($variable, FALSE)->save();
         }
     }
     return $this->assertEqual($value, $assert_value, "xmlsitemap_{$variable} is " . ($assert_value ? 'TRUE' : 'FALSE'));
 }
Exemple #18
0
 /**
  * Stores the values passed to a toolkit call.
  *
  * @param string $op
  *   One of the toolkit methods 'parseFile', 'save', 'settings', or 'apply'.
  * @param array $args
  *   Values passed to hook.
  *
  * @see \Drupal\system\Tests\Image\ToolkitTestBase::imageTestReset()
  * @see \Drupal\system\Tests\Image\ToolkitTestBase::imageTestGetAllCalls()
  */
 protected function logCall($op, $args)
 {
     $results = $this->state->get('image_test.results') ?: array();
     $results[$op][] = $args;
     // A call to apply is also logged under its operation name whereby the
     // array of arguments are logged as separate arguments, this because at the
     // ImageInterface level we still have methods named after the operations.
     if ($op === 'apply') {
         $operation = array_shift($args);
         $results[$operation][] = array_values(reset($args));
     }
     $this->state->set('image_test.results', $results);
 }
Exemple #19
0
 /**
  * Starts the database update batch process.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request object.
  */
 protected function triggerBatch(Request $request)
 {
     // During the update, bring the site offline so that schema changes do not
     // affect visiting users.
     $maintenance_mode = $this->config('system.maintenance')->get('enabled');
     if (isset($maintenance_mode)) {
         $_SESSION['maintenance_mode'] = $maintenance_mode;
     }
     if (empty($_SESSION['maintenance_mode'])) {
         $this->state->set('system.maintenance_mode', TRUE);
     }
     $operations = array();
     // Resolve any update dependencies to determine the actual updates that will
     // be run and the order they will be run in.
     $start = $this->getModuleUpdates();
     $updates = update_resolve_dependencies($start);
     // Store the dependencies for each update function in an array which the
     // batch API can pass in to the batch operation each time it is called. (We
     // do not store the entire update dependency array here because it is
     // potentially very large.)
     $dependency_map = array();
     foreach ($updates as $function => $update) {
         $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array();
     }
     // Determine updates to be performed.
     foreach ($updates as $function => $update) {
         if ($update['allowed']) {
             // Set the installed version of each module so updates will start at the
             // correct place. (The updates are already sorted, so we can simply base
             // this on the first one we come across in the above foreach loop.)
             if (isset($start[$update['module']])) {
                 drupal_set_installed_schema_version($update['module'], $update['number'] - 1);
                 unset($start[$update['module']]);
             }
             $operations[] = array('update_do_one', array($update['module'], $update['number'], $dependency_map[$function]));
         }
     }
     // Lastly, perform entity definition updates, which will update storage
     // schema if needed. If module update functions need to work with specific
     // entity schema they should call the entity update service for the specific
     // update themselves.
     // @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface::applyEntityUpdate()
     // @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface::applyFieldUpdate()
     if ($this->entityDefinitionUpdateManager->needsUpdates()) {
         $operations[] = array('update_entity_definitions', array());
     }
     $batch['operations'] = $operations;
     $batch += array('title' => $this->t('Updating'), 'init_message' => $this->t('Starting updates'), 'error_message' => $this->t('An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.'), 'finished' => array('\\Drupal\\system\\Controller\\DbUpdateController', 'batchFinished'));
     batch_set($batch);
     return batch_process('update.php/results', Url::fromRoute('system.db_update', array('op' => 'start')));
 }
Exemple #20
0
 /**
  * Dumps a set of routes to the router table in the database.
  *
  * Available options:
  * - provider: The route grouping that is being dumped. All existing
  *   routes with this provider will be deleted on dump.
  * - base_class: The base class name.
  *
  * @param array $options
  *   An array of options.
  */
 public function dump(array $options = array())
 {
     // Convert all of the routes into database records.
     // Accumulate the menu masks on top of any we found before.
     $masks = array_flip($this->state->get('routing.menu_masks.' . $this->tableName, array()));
     // Delete any old records first, then insert the new ones. That avoids
     // stale data. The transaction makes it atomic to avoid unstable router
     // states due to random failures.
     $transaction = $this->connection->startTransaction();
     try {
         // We don't use truncate, because it is not guaranteed to be transaction
         // safe.
         try {
             $this->connection->delete($this->tableName)->execute();
         } catch (\Exception $e) {
             $this->ensureTableExists();
         }
         // Split the routes into chunks to avoid big INSERT queries.
         $route_chunks = array_chunk($this->routes->all(), 50, TRUE);
         foreach ($route_chunks as $routes) {
             $insert = $this->connection->insert($this->tableName)->fields(array('name', 'fit', 'path', 'pattern_outline', 'number_parts', 'route'));
             $names = array();
             foreach ($routes as $name => $route) {
                 /** @var \Symfony\Component\Routing\Route $route */
                 $route->setOption('compiler_class', '\\Drupal\\Core\\Routing\\RouteCompiler');
                 /** @var \Drupal\Core\Routing\CompiledRoute $compiled */
                 $compiled = $route->compile();
                 // The fit value is a binary number which has 1 at every fixed path
                 // position and 0 where there is a wildcard. We keep track of all such
                 // patterns that exist so that we can minimize the number of path
                 // patterns we need to check in the RouteProvider.
                 $masks[$compiled->getFit()] = 1;
                 $names[] = $name;
                 $values = array('name' => $name, 'fit' => $compiled->getFit(), 'path' => $route->getPath(), 'pattern_outline' => $compiled->getPatternOutline(), 'number_parts' => $compiled->getNumParts(), 'route' => serialize($route));
                 $insert->values($values);
             }
             // Insert all new routes.
             $insert->execute();
         }
     } catch (\Exception $e) {
         $transaction->rollback();
         watchdog_exception('Routing', $e);
         throw $e;
     }
     // Sort the masks so they are in order of descending fit.
     $masks = array_keys($masks);
     rsort($masks);
     $this->state->set('routing.menu_masks.' . $this->tableName, $masks);
     $this->routes = NULL;
 }
Exemple #21
0
 /**
  * {@inheritdoc}
  */
 public function uninstall(array $theme_list)
 {
     $extension_config = $this->configFactory->getEditable('core.extension');
     $theme_config = $this->configFactory->getEditable('system.theme');
     $list = $this->themeHandler->listInfo();
     foreach ($theme_list as $key) {
         if (!isset($list[$key])) {
             throw new \InvalidArgumentException("Unknown theme: {$key}.");
         }
         if ($key === $theme_config->get('default')) {
             throw new \InvalidArgumentException("The current default theme {$key} cannot be uninstalled.");
         }
         if ($key === $theme_config->get('admin')) {
             throw new \InvalidArgumentException("The current admin theme {$key} cannot be uninstalled.");
         }
         // Base themes cannot be uninstalled if sub themes are installed, and if
         // they are not uninstalled at the same time.
         // @todo https://www.drupal.org/node/474684 and
         //   https://www.drupal.org/node/1297856 themes should leverage the module
         //   dependency system.
         if (!empty($list[$key]->sub_themes)) {
             foreach ($list[$key]->sub_themes as $sub_key => $sub_label) {
                 if (isset($list[$sub_key]) && !in_array($sub_key, $theme_list, TRUE)) {
                     throw new \InvalidArgumentException("The base theme {$key} cannot be uninstalled, because theme {$sub_key} depends on it.");
                 }
             }
         }
     }
     $this->cssCollectionOptimizer->deleteAll();
     $current_theme_data = $this->state->get('system.theme.data', array());
     foreach ($theme_list as $key) {
         // The value is not used; the weight is ignored for themes currently.
         $extension_config->clear("theme.{$key}");
         // Update the current theme data accordingly.
         unset($current_theme_data[$key]);
         // Reset theme settings.
         $theme_settings =& drupal_static('theme_get_setting');
         unset($theme_settings[$key]);
         // Remove all configuration belonging to the theme.
         $this->configManager->uninstall('theme', $key);
     }
     // Don't check schema when uninstalling a theme since we are only clearing
     // keys.
     $extension_config->save(TRUE);
     $this->state->set('system.theme.data', $current_theme_data);
     // @todo Remove system_list().
     $this->themeHandler->refreshInfo();
     $this->resetSystem();
     $this->moduleHandler->invokeAll('themes_uninstalled', [$theme_list]);
 }
 /**
  * Tests the hooks provided by entity_embed module.
  *
  * This method tests all the hooks provided by entity_embed except
  * hook_entity_embed_display_plugins_alter, which is tested by a separate
  * method.
  */
 public function testEntityEmbedHooks()
 {
     // Enable entity_embed_test.module's hook_entity_embed_alter()
     // implementation and ensure it is working as designed.
     $this->state->set('entity_embed_test_entity_embed_alter', TRUE);
     $content = '<drupal-entity data-entity-type="node" data-entity-uuid="' . $this->node->uuid() . '" data-entity-embed-display="default" data-entity-embed-settings=\'{"view_mode":"teaser"}\'>This placeholder should not be rendered.</drupal-entity>';
     $settings = array();
     $settings['type'] = 'page';
     $settings['title'] = 'Test hook_entity_embed_alter()';
     $settings['body'] = array(array('value' => $content, 'format' => 'custom_format'));
     $node = $this->drupalCreateNode($settings);
     $this->drupalGet('node/' . $node->id());
     $this->assertText($this->node->body->value, 'Embedded node exists in page.');
     $this->assertNoText(strip_tags($content), 'Placeholder does not appears in the output when embed is successful.');
     // Ensure that embedded node's title has been replaced.
     $this->assertText('Title set by hook_entity_embed_alter', 'Title of the embedded node is replaced by hook_entity_embed_alter()');
     $this->assertNoText($this->node->title->value, 'Original title of the embedded node is not visible.');
     $this->state->set('entity_embed_test_entity_embed_alter', FALSE);
     // Enable entity_embed_test.module's hook_entity_embed_context_alter()
     // implementation and ensure it is working as designed.
     $this->state->set('entity_embed_test_entity_embed_context_alter', TRUE);
     $content = '<drupal-entity data-entity-type="node" data-entity-uuid="' . $this->node->uuid() . '" data-entity-embed-display="default" data-entity-embed-settings=\'{"view_mode":"teaser"}\'>This placeholder should not be rendered.</drupal-entity>';
     $settings = array();
     $settings['type'] = 'page';
     $settings['title'] = 'Test hook_entity_embed_context_alter()';
     $settings['body'] = array(array('value' => $content, 'format' => 'custom_format'));
     $node = $this->drupalCreateNode($settings);
     $this->drupalGet('node/' . $node->id());
     $this->assertNoText(strip_tags($content), 'Placeholder does not appears in the output when embed is successful.');
     // To ensure that 'label' plugin is used, verify that the body of the
     // embedded node is not visible and the title links to the embedded node.
     $this->assertNoText($this->node->body->value, 'Body of the embedded node does not exists in page.');
     $this->assertText('Title set by hook_entity_embed_context_alter', 'Title of the embedded node is replaced by hook_entity_embed_context_alter()');
     $this->assertNoText($this->node->title->value, 'Original title of the embedded node is not visible.');
     $this->assertLinkByHref('node/' . $this->node->id(), 0, 'Link to the embedded node exists.');
     $this->state->set('entity_embed_test_entity_embed_context_alter', FALSE);
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $account_values = $form_state->getValue('account');
     // We precreated user 1 with placeholder values. Let's save the real values.
     $account = $this->userStorage->load(1);
     $account->init = $account->mail = $account_values['mail'];
     $account->roles = $account->getRoles();
     $account->activate();
     $account->timezone = $form_state->getValue('date_default_timezone');
     $account->pass = $account_values['pass'];
     $account->name = $account_values['name'];
     $account->save();
     // Record when this install ran.
     $this->state->set('install_time', $_SERVER['REQUEST_TIME']);
 }
 /**
  * Allow user to directly execute cron, optionally forcing it.
  */
 public function cronRun(array &$form, FormStateInterface &$form_state)
 {
     $config = $this->configFactory->getEditable('examples.cron');
     $cron_reset = $form_state->getValue('cron_reset');
     if (!empty($cron_reset)) {
         $config->set('next_execution', 0);
     }
     // Use a state variable to signal that cron was run manually from this form.
     $this->state->set('cron_example_show_status_message', TRUE);
     if ($this->cron->run()) {
         drupal_set_message($this->t('Cron ran successfully.'));
     } else {
         drupal_set_message($this->t('Cron run failed.'), 'error');
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Store maintenance_mode setting so we can restore it when done.
     $_SESSION['maintenance_mode'] = $this->state->get('system.maintenance_mode');
     if ($form_state->getValue('maintenance_mode') == TRUE) {
         $this->state->set('system.maintenance_mode', TRUE);
     }
     if (!empty($_SESSION['update_manager_update_projects'])) {
         // Make sure the Updater registry is loaded.
         drupal_get_updaters();
         $updates = array();
         $directory = _update_manager_extract_directory();
         $projects = $_SESSION['update_manager_update_projects'];
         unset($_SESSION['update_manager_update_projects']);
         $project_real_location = NULL;
         foreach ($projects as $project => $url) {
             $project_location = $directory . '/' . $project;
             $updater = Updater::factory($project_location);
             $project_real_location = drupal_realpath($project_location);
             $updates[] = array('project' => $project, 'updater_name' => get_class($updater), 'local_url' => $project_real_location);
         }
         // If the owner of the last directory we extracted is the same as the
         // owner of our configuration directory (e.g. sites/default) where we're
         // trying to install the code, there's no need to prompt for FTP/SSH
         // credentials. Instead, we instantiate a Drupal\Core\FileTransfer\Local
         // and invoke update_authorize_run_update() directly.
         if (fileowner($project_real_location) == fileowner(conf_path())) {
             $this->moduleHandler->loadInclude('update', 'inc', 'update.authorize');
             $filetransfer = new Local(DRUPAL_ROOT);
             update_authorize_run_update($filetransfer, $updates);
         } else {
             system_authorized_init('update_authorize_run_update', drupal_get_path('module', 'update') . '/update.authorize.inc', array($updates), $this->t('Update manager'));
             $form_state->setRedirectUrl(system_authorized_get_url());
         }
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $mode = $input->getArgument('mode');
     $stateName = 'system.maintenance_mode';
     $modeMessage = null;
     $cacheRebuild = true;
     if ('ON' === strtoupper($mode)) {
         $this->state->set($stateName, true);
         $modeMessage = 'commands.site.maintenance.messages.maintenance-on';
     }
     if ('OFF' === strtoupper($mode)) {
         $this->state->set($stateName, false);
         $modeMessage = 'commands.site.maintenance.messages.maintenance-off';
     }
     if ($modeMessage === null) {
         $modeMessage = 'commands.site.maintenance.errors.invalid-mode';
         $cacheRebuild = false;
     }
     $io->info($this->trans($modeMessage));
     if ($cacheRebuild) {
         $this->chainQueue->addCommand('cache:rebuild', ['cache' => 'all']);
     }
 }
Exemple #27
0
 /**
  * {@inheritdoc}
  */
 public function processFetchTask($project)
 {
     global $base_url;
     // This can be in the middle of a long-running batch, so REQUEST_TIME won't
     // necessarily be valid.
     $request_time_difference = time() - REQUEST_TIME;
     if (empty($this->failed)) {
         // If we have valid data about release history XML servers that we have
         // failed to fetch from on previous attempts, load that.
         $this->failed = $this->tempStore->get('fetch_failures');
     }
     $max_fetch_attempts = $this->updateSettings->get('fetch.max_attempts');
     $success = FALSE;
     $available = array();
     $site_key = Crypt::hmacBase64($base_url, $this->privateKey->get());
     $fetch_url_base = $this->updateFetcher->getFetchBaseUrl($project);
     $project_name = $project['name'];
     if (empty($this->failed[$fetch_url_base]) || $this->failed[$fetch_url_base] < $max_fetch_attempts) {
         $data = $this->updateFetcher->fetchProjectData($project, $site_key);
     }
     if (!empty($data)) {
         $available = $this->parseXml($data);
         // @todo: Purge release data we don't need. See
         //   https://www.drupal.org/node/238950.
         if (!empty($available)) {
             // Only if we fetched and parsed something sane do we return success.
             $success = TRUE;
         }
     } else {
         $available['project_status'] = 'not-fetched';
         if (empty($this->failed[$fetch_url_base])) {
             $this->failed[$fetch_url_base] = 1;
         } else {
             $this->failed[$fetch_url_base]++;
         }
     }
     $frequency = $this->updateSettings->get('check.interval_days');
     $available['last_fetch'] = REQUEST_TIME + $request_time_difference;
     $this->availableReleasesTempStore->setWithExpire($project_name, $available, $request_time_difference + 60 * 60 * 24 * $frequency);
     // Stash the $this->failed data back in the DB for the next 5 minutes.
     $this->tempStore->setWithExpire('fetch_failures', $this->failed, $request_time_difference + 60 * 5);
     // Whether this worked or not, we did just (try to) check for updates.
     $this->stateStore->set('update.last_check', REQUEST_TIME + $request_time_difference);
     // Now that we processed the fetch task for this project, clear out the
     // record for this task so we're willing to fetch again.
     $this->fetchTaskStore->delete($project_name);
     return $success;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $state_variables = xmlsitemap_engines_state_variables();
     $config_variables = xmlsitemap_engines_config_variables();
     $keys = array('engines', 'minimum_lifetime', 'xmlsitemap_engines_submit_updated', 'custom_urls');
     $values = $form_state->getValues();
     foreach ($keys as $key) {
         if (isset($state_variables[$key])) {
             $this->state->set($key, $values[$key]);
         } else {
             $this->config('xmlsitemap_engines.settings')->set($key, $values[$key]);
         }
     }
     $this->config('xmlsitemap_engines.settings')->save();
     parent::submitForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  */
 public function checkChangedLinks(array $conditions = array(), array $updates = array(), $flag = FALSE)
 {
     // If we are changing status or access, check for negative current values.
     $conditions['status'] = !empty($updates['status']) && empty($conditions['status']) ? 0 : 1;
     $conditions['access'] = !empty($updates['access']) && empty($conditions['access']) ? 0 : 1;
     $query = db_select('xmlsitemap');
     $query->addExpression('1');
     foreach ($conditions as $field => $value) {
         $query->condition($field, $value);
     }
     $query->range(0, 1);
     $changed = $query->execute()->fetchField();
     if ($changed && $flag) {
         $this->state->set('xmlsitemap_regenerate_needed', TRUE);
     }
     return $changed;
 }
 /**
  * {@inheritdoc}
  */
 public function delete(array $entities)
 {
     // After deleting a set of reaction rules, sometimes we may need to rebuild
     // the container, to clean it up, so that the generic subscriber is not
     // registered in the container for the rule events which we do not use
     // anymore. So we do that if there is any change in the registered events,
     // after the reaction rules are deleted.
     $events_before = $this->getRegisteredEvents();
     $return = parent::delete($entities);
     $events_after = $this->getRegisteredEvents();
     // Update the state of registered events and rebuild the container.
     if ($events_before != $events_after) {
         $this->stateService->set('rules.registered_events', $events_after);
         $this->drupalKernel->rebuildContainer();
     }
     return $return;
 }