/**
  * Test successful execution of hook_requirements() during install/enable.
  *
  * Function module_enable() does not check requirements, unlike normal
  * enabling, so we need to invoke the hook manually to simulate it.
  */
 public function testEnable()
 {
     module_load_install(static::MODULE);
     module_invoke(static::MODULE, 'requirements', 'install');
     module_enable([static::MODULE], FALSE);
     $this->pass('Successfully enabled mongodb.module.');
 }
 protected function setUp()
 {
     parent::setUp();
     module_load_install('system');
     $schema = system_schema();
     db_create_table('key_value_expire', $schema['key_value_expire']);
 }
예제 #3
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $config = $this->config('system.theme');
     $config->set('default', 'bartik');
     $config->set('admin', 'seven');
     $config->save();
     foreach (static::$modules as $module) {
         $function = $module . '_schema';
         module_load_install($module);
         if (function_exists($function)) {
             $schema = $function();
             $this->installSchema($module, array_keys($schema));
         }
     }
     $this->installEntitySchema('aggregator_feed');
     $this->installEntitySchema('aggregator_item');
     $this->installEntitySchema('block_content');
     $this->installEntitySchema('comment');
     $this->installEntitySchema('file');
     $this->installEntitySchema('node');
     $this->installEntitySchema('menu_link_content');
     $this->installEntitySchema('taxonomy_term');
     $this->installEntitySchema('user');
     $this->installConfig(['block_content', 'comment', 'file', 'node', 'simpletest']);
     // Install one of D8's test themes.
     \Drupal::service('theme_handler')->install(array('test_theme'));
     // Create a new user which needs to have UID 1, because that is expected by
     // the assertions from
     // \Drupal\migrate_drupal\Tests\d6\MigrateNodeRevisionTest.
     User::create(['uid' => 1, 'name' => $this->randomMachineName(), 'status' => 1])->enforceIsNew(TRUE)->save();
     $this->installMigrations('Drupal 6');
 }
 function setUp()
 {
     parent::setUp();
     // Run the install hook.
     // @TODO: figure out why this is necessary.
     module_load_install('domain_source');
     domain_source_install();
 }
예제 #5
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Create the test field.
     module_load_install('entity_test');
     entity_test_install();
     // Install required default configuration for filter module.
     $this->installConfig(array('system', 'filter'));
 }
 /**
  * Returns the table definition for the URL alias fixtures.
  *
  * @return array
  *   Table definitions.
  */
 public function tableDefinition()
 {
     $tables = array();
     module_load_install('system');
     $schema = system_schema();
     $tables['url_alias'] = $schema['url_alias'];
     $tables['key_value'] = $schema['key_value'];
     return $tables;
 }
예제 #7
0
 public function moduleRequirement($module)
 {
     foreach ($module as $module_name) {
         module_load_install($module_name);
         if ($requirements = \Drupal::moduleHandler()->invoke($module_name, 'requirements', array('install'))) {
             foreach ($requirements as $requirement) {
                 throw new \Exception($module_name . ' can not be installed: ' . $requirement['description']);
             }
         }
     }
 }
예제 #8
0
 protected function setUp()
 {
     parent::setUp();
     module_load_install('system');
     $schema = system_schema();
     db_create_table('key_value', $schema['key_value']);
     $this->container->register('database', 'Drupal\\Core\\Database\\Connection')->setFactoryClass('Drupal\\Core\\Database\\Database')->setFactoryMethod('getConnection')->addArgument('default');
     $this->container->register('keyvalue.database', 'Drupal\\Core\\KeyValueStore\\KeyValueDatabaseFactory')->addArgument(new Reference('serialization.phpserialize'))->addArgument(new Reference('database'));
     $this->container->register('serialization.phpserialize', 'Drupal\\Component\\Serialization\\PhpSerialize');
     $this->settingsSet('keyvalue_default', 'keyvalue.database');
 }
예제 #9
0
 protected function setUp()
 {
     parent::setUp();
     // Install field configuration.
     $this->installConfig(array('field'));
     // The users table is needed for creating dummy user accounts.
     $this->installEntitySchema('user');
     // Register entity_test text field.
     module_load_install('entity_test');
     entity_test_install();
 }
예제 #10
0
 function setUp()
 {
     parent::setUp();
     // Run the install hook.
     // @TODO: figure out why this is necessary.
     module_load_install('domain_access');
     domain_access_install();
     // Set the access handler.
     $this->accessHandler = \Drupal::entityManager()->getAccessControlHandler('node');
     // Clear permissions for authenticated users.
     $this->config('user.role.' . DRUPAL_AUTHENTICATED_RID)->set('permissions', array())->save();
 }
예제 #11
0
 /**
  * Returns the table definition for the URL alias fixtures.
  *
  * @return array
  *   Table definitions.
  */
 public function tableDefinition()
 {
     $tables = array();
     // Prime the drupal_get_filename() cache with the location of the system
     // module as its location is known and shouldn't change.
     // @todo Remove as part of https://www.drupal.org/node/2186491
     drupal_get_filename('module', 'system', 'core/modules/system/system.info.yml');
     module_load_install('system');
     $schema = system_schema();
     $tables['url_alias'] = AliasStorage::schemaDefinition();
     $tables['key_value'] = $schema['key_value'];
     return $tables;
 }
예제 #12
0
 protected function setUp()
 {
     parent::setUp();
     // Install system tables to test the key/value storage without installing a
     // full Drupal environment.
     module_load_install('system');
     $schema = system_schema();
     db_create_table('semaphore', $schema['semaphore']);
     db_create_table('key_value_expire', $schema['key_value_expire']);
     // Create several objects for testing.
     for ($i = 0; $i <= 3; $i++) {
         $this->objects[$i] = $this->randomObject();
     }
 }
예제 #13
0
 protected function setUp()
 {
     parent::setUp();
     foreach (entity_test_entity_types() as $entity_type_id) {
         // The entity_test schema is installed by the parent.
         if ($entity_type_id != 'entity_test') {
             $this->installEntitySchema($entity_type_id);
         }
     }
     // Create the test field.
     module_load_install('entity_test');
     entity_test_install();
     // Install required default configuration for filter module.
     $this->installConfig(array('system', 'filter'));
 }
예제 #14
0
 public function setUp()
 {
     parent::setUp();
     // Clear permissions for authenticated users.
     $this->config('user.role.' . RoleInterface::AUTHENTICATED_ID)->set('permissions', array())->save();
     // Create Basic page node type.
     if ($this->profile != 'standard') {
         $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page', 'display_submitted' => FALSE));
     }
     $this->accessHandler = \Drupal::entityManager()->getAccessControlHandler('node');
     $this->manager = \Drupal::service('domain_access.manager');
     // Create 5 domains.
     $this->domainCreateTestDomains(5);
     // Run the install hook.
     // @TODO: figure out why this is necessary.
     module_load_install('domain_access');
     domain_access_install();
 }
 /**
  * Implements hook_init().
  */
 function onRequest()
 {
     // On all Mollom administration pages, check the module configuration and
     // display the corresponding requirements error, if invalid.
     $url = Url::fromRoute('<current>');
     $current_path = $url->toString();
     if (empty($_POST) && strpos($current_path, 'admin/config/content/mollom') === 0 && \Drupal::currentUser()->hasPermission('administer mollom')) {
         // Re-check the status on the settings form only.
         $status = \Drupal\mollom\Utility\MollomUtilities::getAPIKeyStatus($current_path == 'admin/config/content/mollom/settings');
         if ($status !== TRUE) {
             // Fetch and display requirements error message, without re-checking.
             module_load_install('mollom');
             $requirements = mollom_requirements('runtime', FALSE);
             if (isset($requirements['mollom']['description'])) {
                 drupal_set_message($requirements['mollom']['description'], 'error');
             }
         }
     }
 }
예제 #16
0
 protected function setUp()
 {
     parent::setUp();
     $this->languageManager = $this->container->get('language_manager');
     foreach (entity_test_entity_types() as $entity_type_id) {
         // The entity_test schema is installed by the parent.
         if ($entity_type_id != 'entity_test') {
             $this->installEntitySchema($entity_type_id);
         }
     }
     $this->installConfig(array('language'));
     // Create the test field.
     module_load_install('entity_test');
     entity_test_install();
     // Enable translations for the test entity type.
     $this->state->set('entity_test.translation', TRUE);
     // Create a translatable test field.
     $this->fieldName = Unicode::strtolower($this->randomMachineName() . '_field_name');
     // Create an untranslatable test field.
     $this->untranslatableFieldName = Unicode::strtolower($this->randomMachineName() . '_field_name');
     // Create field fields in all entity variations.
     foreach (entity_test_entity_types() as $entity_type) {
         entity_create('field_storage_config', array('field_name' => $this->fieldName, 'entity_type' => $entity_type, 'type' => 'text', 'cardinality' => 4))->save();
         entity_create('field_config', array('field_name' => $this->fieldName, 'entity_type' => $entity_type, 'bundle' => $entity_type, 'translatable' => TRUE))->save();
         $this->field[$entity_type] = FieldConfig::load($entity_type . '.' . $entity_type . '.' . $this->fieldName);
         entity_create('field_storage_config', array('field_name' => $this->untranslatableFieldName, 'entity_type' => $entity_type, 'type' => 'text', 'cardinality' => 4))->save();
         entity_create('field_config', array('field_name' => $this->untranslatableFieldName, 'entity_type' => $entity_type, 'bundle' => $entity_type, 'translatable' => FALSE))->save();
     }
     // Create the default languages.
     $this->installConfig(array('language'));
     // Create test languages.
     $this->langcodes = array();
     for ($i = 0; $i < 3; ++$i) {
         $language = ConfigurableLanguage::create(array('id' => 'l' . $i, 'label' => $this->randomString(), 'weight' => $i));
         $this->langcodes[$i] = $language->getId();
         $language->save();
     }
 }
 function installLanguage($langcode)
 {
     $this->addLanguage($langcode, TRUE, TRUE);
     if (module_exists('atrium_translate')) {
         module_load_install('atrium_translate');
         module_load_include('inc', 'l10n_update');
         $release = _atrium_translate_default_release($langcode);
         //$release = l10n_update_project_get_release('atrium', $langcode, ATRIUM_L10N_VERSION, ATRIUM_L10N_SERVER);
         if ($release && !empty($release['download_link'])) {
             $project = _l10n_update_build_project('atrium', ATRIUM_L10N_VERSION, ATRIUM_L10N_SERVER);
             if ($file = l10n_update_download_file($release['download_link'])) {
                 l10n_update_import_file($file, $langcode);
                 l10n_update_download_history($project, $release);
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function uninstall(array $module_list, $uninstall_dependents = TRUE)
 {
     // Get all module data so we can find dependencies and sort.
     $module_data = system_rebuild_module_data();
     $module_list = $module_list ? array_combine($module_list, $module_list) : array();
     if (array_diff_key($module_list, $module_data)) {
         // One or more of the given modules doesn't exist.
         return FALSE;
     }
     // Only process currently installed modules.
     $extension_config = \Drupal::config('core.extension');
     $installed_modules = $extension_config->get('module') ?: array();
     if (!($module_list = array_intersect_key($module_list, $installed_modules))) {
         // Nothing to do. All modules already uninstalled.
         return TRUE;
     }
     if ($uninstall_dependents) {
         // Add dependent modules to the list. The new modules will be processed as
         // the while loop continues.
         $profile = drupal_get_profile();
         while (list($module) = each($module_list)) {
             foreach (array_keys($module_data[$module]->required_by) as $dependent) {
                 if (!isset($module_data[$dependent])) {
                     // The dependent module does not exist.
                     return FALSE;
                 }
                 // Skip already uninstalled modules.
                 if (isset($installed_modules[$dependent]) && !isset($module_list[$dependent]) && $dependent != $profile) {
                     $module_list[$dependent] = $dependent;
                 }
             }
         }
     }
     // Set the actual module weights.
     $module_list = array_map(function ($module) use($module_data) {
         return $module_data[$module]->sort;
     }, $module_list);
     // Sort the module list by their weights.
     asort($module_list);
     $module_list = array_keys($module_list);
     // Only process modules that are enabled. A module is only enabled if it is
     // configured as enabled. Custom or overridden module handlers might contain
     // the module already, which means that it might be loaded, but not
     // necessarily installed.
     $schema_store = \Drupal::keyValue('system.schema');
     $entity_manager = \Drupal::entityManager();
     foreach ($module_list as $module) {
         // Clean up all entity bundles (including fields) of every entity type
         // provided by the module that is being uninstalled.
         foreach ($entity_manager->getDefinitions() as $entity_type_id => $entity_type) {
             if ($entity_type->getProvider() == $module) {
                 foreach (array_keys($entity_manager->getBundleInfo($entity_type_id)) as $bundle) {
                     $entity_manager->onBundleDelete($bundle, $entity_type_id);
                 }
             }
         }
         // Allow modules to react prior to the uninstallation of a module.
         $this->invokeAll('module_preuninstall', array($module));
         // Uninstall the module.
         module_load_install($module);
         $this->invoke($module, 'uninstall');
         // Remove all configuration belonging to the module.
         \Drupal::service('config.manager')->uninstall('module', $module);
         // Notify the entity manager that this module's entity types are being
         // deleted, so that it can notify all interested handlers. For example,
         // a SQL-based storage handler can use this as an opportunity to drop
         // the corresponding database tables.
         foreach ($entity_manager->getDefinitions() as $entity_type) {
             if ($entity_type->getProvider() == $module) {
                 $entity_manager->onEntityTypeDelete($entity_type);
             }
         }
         // Remove the schema.
         drupal_uninstall_schema($module);
         // Remove the module's entry from the config.
         $extension_config->clear("module.{$module}")->save();
         // Update the module handler to remove the module.
         // The current ModuleHandler instance is obsolete with the kernel rebuild
         // below.
         $module_filenames = $this->getModuleList();
         unset($module_filenames[$module]);
         $this->setModuleList($module_filenames);
         // Remove any potential cache bins provided by the module.
         $this->removeCacheBins($module);
         // Clear the static cache of system_rebuild_module_data() to pick up the
         // new module, since it merges the installation status of modules into
         // its statically cached list.
         drupal_static_reset('system_rebuild_module_data');
         // Clear plugin manager caches and flag router to rebuild if requested.
         \Drupal::getContainer()->get('plugin.cache_clearer')->clearCachedDefinitions();
         \Drupal::service('router.builder_indicator')->setRebuildNeeded();
         // Update the kernel to exclude the uninstalled modules.
         \Drupal::service('kernel')->updateModules($module_filenames, $module_filenames);
         // Update the theme registry to remove the newly uninstalled module.
         drupal_theme_rebuild();
         // Modules can alter theme info, so refresh theme data.
         // @todo ThemeHandler cannot be injected into ModuleHandler, since that
         //   causes a circular service dependency.
         // @see https://drupal.org/node/2208429
         \Drupal::service('theme_handler')->refreshInfo();
         \Drupal::logger('system')->info('%module module uninstalled.', array('%module' => $module));
         $schema_store->delete($module);
     }
     drupal_get_installed_schema_version(NULL, TRUE);
     // Let other modules react.
     $this->invokeAll('modules_uninstalled', array($module_list));
     return TRUE;
 }
예제 #19
0
 /**
  * {@inheritdoc}
  */
 public function uninstall(array $module_list, $uninstall_dependents = TRUE)
 {
     // Get all module data so we can find dependencies and sort.
     $module_data = system_rebuild_module_data();
     $module_list = $module_list ? array_combine($module_list, $module_list) : array();
     if (array_diff_key($module_list, $module_data)) {
         // One or more of the given modules doesn't exist.
         return FALSE;
     }
     $extension_config = \Drupal::configFactory()->getEditable('core.extension');
     $installed_modules = $extension_config->get('module') ?: array();
     if (!($module_list = array_intersect_key($module_list, $installed_modules))) {
         // Nothing to do. All modules already uninstalled.
         return TRUE;
     }
     if ($uninstall_dependents) {
         // Add dependent modules to the list. The new modules will be processed as
         // the while loop continues.
         $profile = drupal_get_profile();
         while (list($module) = each($module_list)) {
             foreach (array_keys($module_data[$module]->required_by) as $dependent) {
                 if (!isset($module_data[$dependent])) {
                     // The dependent module does not exist.
                     return FALSE;
                 }
                 // Skip already uninstalled modules.
                 if (isset($installed_modules[$dependent]) && !isset($module_list[$dependent]) && $dependent != $profile) {
                     $module_list[$dependent] = $dependent;
                 }
             }
         }
     }
     // Use the validators and throw an exception with the reasons.
     if ($reasons = $this->validateUninstall($module_list)) {
         foreach ($reasons as $reason) {
             $reason_message[] = implode(', ', $reason);
         }
         throw new ModuleUninstallValidatorException('The following reasons prevent the modules from being uninstalled: ' . implode('; ', $reason_message));
     }
     // Set the actual module weights.
     $module_list = array_map(function ($module) use($module_data) {
         return $module_data[$module]->sort;
     }, $module_list);
     // Sort the module list by their weights.
     asort($module_list);
     $module_list = array_keys($module_list);
     // Only process modules that are enabled. A module is only enabled if it is
     // configured as enabled. Custom or overridden module handlers might contain
     // the module already, which means that it might be loaded, but not
     // necessarily installed.
     foreach ($module_list as $module) {
         // Clean up all entity bundles (including fields) of every entity type
         // provided by the module that is being uninstalled.
         // @todo Clean this up in https://www.drupal.org/node/2350111.
         $entity_manager = \Drupal::entityManager();
         foreach ($entity_manager->getDefinitions() as $entity_type_id => $entity_type) {
             if ($entity_type->getProvider() == $module) {
                 foreach (array_keys($entity_manager->getBundleInfo($entity_type_id)) as $bundle) {
                     $entity_manager->onBundleDelete($bundle, $entity_type_id);
                 }
             }
         }
         // Allow modules to react prior to the uninstallation of a module.
         $this->moduleHandler->invokeAll('module_preuninstall', array($module));
         // Uninstall the module.
         module_load_install($module);
         $this->moduleHandler->invoke($module, 'uninstall');
         // Remove all configuration belonging to the module.
         \Drupal::service('config.manager')->uninstall('module', $module);
         // In order to make uninstalling transactional if anything uses routes.
         \Drupal::getContainer()->set('router.route_provider.old', \Drupal::service('router.route_provider'));
         \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.lazy_builder'));
         // Notify interested components that this module's entity types are being
         // deleted. For example, a SQL-based storage handler can use this as an
         // opportunity to drop the corresponding database tables.
         // @todo Clean this up in https://www.drupal.org/node/2350111.
         $update_manager = \Drupal::entityDefinitionUpdateManager();
         foreach ($entity_manager->getDefinitions() as $entity_type) {
             if ($entity_type->getProvider() == $module) {
                 $update_manager->uninstallEntityType($entity_type);
             } elseif ($entity_type->isSubclassOf(FieldableEntityInterface::CLASS)) {
                 // The module being installed may be adding new fields to existing
                 // entity types. Field definitions for any entity type defined by
                 // the module are handled in the if branch.
                 $entity_type_id = $entity_type->id();
                 /** @var \Drupal\Core\Entity\FieldableEntityStorageInterface $storage */
                 $storage = $entity_manager->getStorage($entity_type_id);
                 foreach ($entity_manager->getFieldStorageDefinitions($entity_type_id) as $storage_definition) {
                     // @todo We need to trigger field purging here.
                     //   See https://www.drupal.org/node/2282119.
                     if ($storage_definition->getProvider() == $module && !$storage->countFieldData($storage_definition, TRUE)) {
                         $update_manager->uninstallFieldStorageDefinition($storage_definition);
                     }
                 }
             }
         }
         // Remove the schema.
         drupal_uninstall_schema($module);
         // Remove the module's entry from the config. Don't check schema when
         // uninstalling a module since we are only clearing a key.
         \Drupal::configFactory()->getEditable('core.extension')->clear("module.{$module}")->save(TRUE);
         // Update the module handler to remove the module.
         // The current ModuleHandler instance is obsolete with the kernel rebuild
         // below.
         $module_filenames = $this->moduleHandler->getModuleList();
         unset($module_filenames[$module]);
         $this->moduleHandler->setModuleList($module_filenames);
         // Remove any potential cache bins provided by the module.
         $this->removeCacheBins($module);
         // Clear the static cache of system_rebuild_module_data() to pick up the
         // new module, since it merges the installation status of modules into
         // its statically cached list.
         drupal_static_reset('system_rebuild_module_data');
         // Clear plugin manager caches.
         \Drupal::getContainer()->get('plugin.cache_clearer')->clearCachedDefinitions();
         // Update the kernel to exclude the uninstalled modules.
         $this->updateKernel($module_filenames);
         // Update the theme registry to remove the newly uninstalled module.
         drupal_theme_rebuild();
         // Modules can alter theme info, so refresh theme data.
         // @todo ThemeHandler cannot be injected into ModuleHandler, since that
         //   causes a circular service dependency.
         // @see https://www.drupal.org/node/2208429
         \Drupal::service('theme_handler')->refreshInfo();
         \Drupal::logger('system')->info('%module module uninstalled.', array('%module' => $module));
         $schema_store = \Drupal::keyValue('system.schema');
         $schema_store->delete($module);
         /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
         $post_update_registry = \Drupal::service('update.post_update_registry');
         $post_update_registry->filterOutInvokedUpdatesByModule($module);
     }
     // Rebuild routes after installing module. This is done here on top of
     // \Drupal\Core\Routing\RouteBuilder::destruct to not run into errors on
     // fastCGI which executes ::destruct() after the Module uninstallation page
     // was sent already.
     \Drupal::service('router.builder')->rebuild();
     drupal_get_installed_schema_version(NULL, TRUE);
     // Let other modules react.
     $this->moduleHandler->invokeAll('modules_uninstalled', array($module_list));
     // Flush all persistent caches.
     // Any cache entry might implicitly depend on the uninstalled modules,
     // so clear all of them explicitly.
     $this->moduleHandler->invokeAll('cache_flush');
     foreach (Cache::getBins() as $service_id => $cache_backend) {
         $cache_backend->deleteAll();
     }
     return TRUE;
 }
예제 #20
0
 /**
  * Gets the status of Mollom's API key configuration and also displays a
  * warning message if the Mollom API keys are not configured.
  *
  * To be used within the Mollom administration pages only.
  *
  * @param bool $force
  *   (optional) Boolean whether to ignore the cached state and re-check.
  *   Defaults to FALSE.
  * @param bool $update
  *   (optional) Whether to update Mollom with locally stored configuration.
  *   Defaults to FALSE.
  *
  * @return array
  *   An associative array describing the current status of the module:
  *   - isConfigured: Boolean whether Mollom API keys have been configured.
  *   - isVerified: Boolean whether Mollom API keys have been verified.
  *   - response: The response error code of the API verification request.
  *   - ...: The full site resource, as returned by the Mollom API.
  *
  * @see Mollom::getAPIKeyStatus().
  */
 public static function getAdminAPIKeyStatus($force = FALSE, $update = FALSE)
 {
     $status = MollomUtilities::getAPIKeyStatus($force, $update);
     if (empty($_POST) && !$status['isVerified']) {
         // Fetch and display requirements error message, without re-checking.
         module_load_install('mollom');
         $requirements = mollom_requirements('runtime', FALSE);
         if (isset($requirements['mollom']['description'])) {
             drupal_set_message($requirements['mollom']['description'], 'error');
         }
     }
     return $status;
 }
예제 #21
0
 public static function changeSchema(array &$field, array $column_renames = array())
 {
     // Update the field schema
     $old_schema = array_intersect_key($field, array('columns' => '', 'indexes' => '', 'foreign keys' => ''));
     module_load_install($field['module']);
     $new_schema = (array) module_invoke($field['module'], 'field_schema', $field);
     $new_schema += array('columns' => array(), 'indexes' => array(), 'foreign keys' => array());
     $field['data']['columns'] = $new_schema['columns'];
     $field['data']['indexes'] = $new_schema['indexes'];
     $field['data']['foreign keys'] = $new_schema['foreign keys'];
     $data_table = _field_sql_storage_tablename($field);
     $revision_table = _field_sql_storage_revision_tablename($field);
     // Validate that all the columns described in the existing schema actually exist.
     foreach (array_keys($old_schema['columns']) as $old_column) {
         $old_column_name = _field_sql_storage_columnname($field['field_name'], $old_column);
         if (!db_field_exists($data_table, $old_column_name)) {
             throw new Exception();
         }
         if (!db_field_exists($revision_table, $old_column_name)) {
             throw new Exception();
         }
         // Attempt to re-use any columns that have the same name.
         // This can be skipped by setting $column_renames['column-name'] = FALSE;
         if (!empty($new_schema['columns'][$old_column]) && !isset($column_renames[$old_column])) {
             $column_renames[$old_column] = $old_column;
         }
     }
     // Validate that any columns to be renamed actually exist.
     foreach ($column_renames as $old_column => $new_column) {
         if (!isset($old_schema['columns'][$old_column])) {
             throw new Exception("Cannot rename field {$field['field_name']} column {$old_column} because it does not exist in the old schema.");
         }
         if (!isset($new_schema['columns'][$new_column])) {
             throw new Exception("Cannot rename field {$field['field_name']} column {$old_column} to {$new_column} because it does not exist in the new schema.");
         }
     }
     // Remove all existing indexes.
     foreach ($old_schema['indexes'] as $index => $index_fields) {
         $index_name = _field_sql_storage_indexname($field['field_name'], $index);
         if (db_index_exists($data_table, $index_name)) {
             watchdog('helper', "Dropped index {$data_table}.{$index_name}");
             db_drop_index($data_table, $index_name);
         }
         if (db_index_exists($revision_table, $index_name)) {
             watchdog('helper', "Dropped index {$revision_table}.{$index_name}");
             db_drop_index($revision_table, $index_name);
         }
     }
     // Rename any columns.
     foreach ($column_renames as $old_column => $new_column) {
         $old_column_name = _field_sql_storage_columnname($field['field_name'], $old_column);
         if ($new_column === FALSE) {
             db_drop_field($data_table, $old_column_name);
             watchdog('helper', "Dropped column {$data_table}.{$old_column_name}");
             db_drop_field($revision_table, $old_column_name);
             watchdog('helper', "Dropped column {$revision_table}.{$old_column_name}");
             unset($old_schema['columns'][$old_column]);
         } else {
             $new_column_name = _field_sql_storage_columnname($field['field_name'], $new_column);
             db_change_field($data_table, $old_column_name, $new_column_name, $new_schema['columns'][$new_column]);
             watchdog('helper', "Changed column {$data_table}.{$old_column_name}<br/><pre>" . print_r($new_schema['columns'][$new_column], TRUE) . '</pre>');
             db_change_field($revision_table, $old_column_name, $new_column_name, $new_schema['columns'][$new_column]);
             watchdog('helper', "Changed column {$revision_table}.{$old_column_name}<br/><pre>" . print_r($new_schema['columns'][$new_column], TRUE) . '</pre>');
             // Remove these fields so they aren't removed or added in the code below.
             unset($new_schema['columns'][$new_column]);
             unset($old_schema['columns'][$old_column]);
         }
     }
     // Remove any old columns.
     $old_columns = array_diff_key($old_schema['columns'], $new_schema['columns']);
     foreach (array_keys($old_columns) as $old_column) {
         $old_column_name = _field_sql_storage_columnname($field['field_name'], $old_column);
         db_drop_field($data_table, $old_column_name);
         watchdog('helper', "Dropped column {$data_table}.{$old_column_name}");
         db_drop_field($revision_table, $old_column_name);
         watchdog('helper', "Dropped column {$revision_table}.{$old_column_name}");
     }
     // Add any new columns.
     $new_columns = array_diff_key($new_schema['columns'], $old_schema['columns']);
     foreach (array_keys($new_columns) as $new_column) {
         $new_column_name = _field_sql_storage_columnname($field['field_name'], $new_column);
         db_add_field($data_table, $new_column_name, $new_schema['columns'][$new_column]);
         watchdog('helper', "Added column {$data_table}.{$new_column_name}");
         db_add_field($revision_table, $new_column_name, $new_schema['columns'][$new_column]);
         watchdog('helper', "Added column {$revision_table}.{$new_column_name}");
     }
     // Re-add indexes.
     foreach ($new_schema['indexes'] as $index => $index_fields) {
         foreach ($index_fields as &$index_field) {
             if (is_array($index_field)) {
                 $index_field[0] = _field_sql_storage_columnname($field['field_name'], $index_field[0]);
             } else {
                 $index_field = _field_sql_storage_columnname($field['field_name'], $index_field);
             }
         }
         $index_name = _field_sql_storage_indexname($field['field_name'], $index);
         db_add_index($data_table, $index_name, $index_fields);
         watchdog('helper', "Added index {$data_table}.{$index_name}<br/><pre>" . print_r($index_fields, TRUE) . '</pre>');
         db_add_index($revision_table, $index_name, $index_fields);
         watchdog('helper', "Added index {$revision_table}.{$index_name}<br/><pre>" . print_r($index_fields, TRUE) . '</pre>');
     }
 }
 /**
  * Checks system runtime requirements.
  *
  * @return array
  *   An array of system requirements.
  */
 protected function checkSystemRequirements()
 {
     module_load_install('system');
     return system_requirements('runtime');
 }
예제 #23
0
 /**
  * Change the machine name of an existing field.
  *
  * @param $newName string
  *
  * NOTE: This might need additional adjustments for contrib modules
  *   that store field_names (ie. views, context, cck_blocks).
  */
 public function rename($newName)
 {
     $o = $this->field_name;
     $n = $newName;
     db_query("UPDATE field_config SET field_name='{$n}' WHERE field_name='{$o}'");
     db_query("UPDATE field_config_instance SET field_name='{$n}' WHERE field_name='{$o}'");
     db_query("RENAME TABLE `field_data_{$o}` TO `field_data_{$n}`;");
     db_query("RENAME TABLE `field_revision_{$o}` TO `field_revision_{$n}`;");
     \module_load_install($this->module);
     $function = $this->module . '_field_schema';
     $schema = $function(array('type' => $this->type));
     foreach ($schema['columns'] as $column => $specs) {
         db_change_field("field_data_{$n}", "{$o}_{$column}", "{$n}_{$column}", $specs);
         db_change_field("field_revision_{$n}", "{$o}_{$column}", "{$n}_{$column}", $specs);
     }
     $this->field_name = $n;
 }