apigee_edge-8.x-1.17/apigee_edge.install

apigee_edge.install
<?php

/**
 * @file
 * Copyright 2018 Google Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 2 as published by the
 * Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/**
 * Install, update and uninstall functions for Apigee.
 */

use Drupal\apigee_edge\OauthTokenFileStorage;
use Drupal\apigee_edge\Plugin\EdgeKeyTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Installer\InstallerKernel;
use Drupal\Core\Url;
use Drupal\user\RoleInterface;
use Drupal\Core\Config\FileStorage;

/**
 * Implements hook_requirements().
 */
function apigee_edge_requirements($phase) {
  $requirements = [];

  if ($phase === 'install') {
    // This should be checked only if Drupal is installed.
    if (!InstallerKernel::installationAttempted()) {
      $missing_mails = \Drupal::entityQuery('user')
        ->notExists('mail')
        ->accessCheck(TRUE)
        ->condition('uid', '0', '<>')
        ->execute();
      if (!empty($missing_mails)) {
        $requirements['apigee_edge_missing_mail'] = [
          'title' => t('Apigee'),
          'description' => t('The module can be installed only if all users have emails in Drupal, because email is a required attribute on Apigee.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
    }

  }
  elseif ($phase === 'runtime') {
    /** @var \Drupal\apigee_edge\SDKConnectorInterface $sdk_connector */
    $sdk_connector = \Drupal::service('apigee_edge.sdk_connector');
    try {
      $sdk_connector->testConnection();
    }
    catch (\Exception $exception) {
      $requirements['apigee_edge_connection_error'] = [
        'title' => t('Apigee'),
        'value' => $exception->getMessage(),
        'description' => t('Cannot connect to Apigee server. You have either given wrong credential details or the Apigee server is unreachable. Visit the <a href=":url">Apigee general settings</a> page to get more information.', [
          ':url' => Url::fromRoute('apigee_edge.settings', ['destination' => 'admin/reports/status'])->toString(),
        ]),
        'severity' => REQUIREMENT_WARNING,
      ];
    }

    $auth_config = \Drupal::config('apigee_edge.auth');
    if ($key_id = $auth_config->get('active_key')) {

      // Warning message if insecure Configuration Key provider is being used.
      $key = \Drupal::service('key.repository')->getKey($key_id);
      if ($key && $key->getKeyProvider()->getPluginId() === "config") {
        $requirements['apigee_edge_insecure_config_key_provider'] = [
          'title' => t('Apigee'),
          'description' => t('Edge connection settings are stored in Drupal’s configuration system, which is not designed to store sensitive information. When installing Kickstart for uses other than local development, we highly recommend changing the Apigee connection key provider to a more secure storage location. <a href="https://www.drupal.org/docs/8/modules/apigee-developer-portal-kickstart/apigee-kickstart-faqs#s-during-installation-a-warning-is-displayed-that-the-apigee-edge-connection-key-provider-is-not-considered-secure-what-should-i-do" target="_blank">Learn more.</a>'),
          'severity' => REQUIREMENT_WARNING,
        ];
      }

      // Warning message in status report if using basic auth.
      try {
        if ($key && $key->getKeyType() instanceof EdgeKeyTypeInterface &&
          $key->getKeyType()->getAuthenticationType($key) === EdgeKeyTypeInterface::EDGE_AUTH_TYPE_BASIC &&
          $key->getKeyType()->getInstanceType($key) === EdgeKeyTypeInterface::INSTANCE_TYPE_PUBLIC) {
          $requirements['apigee_edge_http_basic_auth'] = [
            'title' => t('Apigee'),
            'description' => t('Apigee Edge HTTP basic authentication will be deprecated. Please choose another authentication method. Visit the <a href=":url">Apigee general settings</a> page to get more information.', [
              ':url' => Url::fromRoute('apigee_edge.settings', ['destination' => 'admin/reports/status'])->toString(),
            ]),
            'severity' => REQUIREMENT_WARNING,
          ];
        }
      }
      catch (Exception $e) {
        // Do nothing.
      }
    }
  }

  return $requirements;
}

/**
 * Implements hook_install().
 */
function apigee_edge_install() {
  if (\Drupal::moduleHandler()->moduleExists('user')) {
    $authenticated_user_permissions = [
      'view own developer_app',
      'create developer_app',
      'update own developer_app',
      'delete own developer_app',
      'analytics own developer_app',
      'add_api_key own developer_app',
      'revoke_api_key own developer_app',
      'edit_api_products developer_app',
    ];
    user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, $authenticated_user_permissions);
  }
}

/**
 * Implements hook_uninstall().
 */
function apigee_edge_uninstall() {
  // Remove OAuth token data file.
  // We do not check whether OAuth was the authentication method in use
  // because this function does not trigger an error if it was not.
  $storage = \Drupal::service('apigee_edge.authentication.oauth_token_storage');
  if ($storage instanceof OauthTokenFileStorage) {
    $storage->removeTokenFile();
  }
}

/**
 * Implements hook_schema().
 */
function apigee_edge_schema() {
  $schema = [];

  $schema['apigee_edge_job'] = [
    'fields' => [
      'id' => [
        'type' => 'varchar',
        'length' => 36,
        'not null' => TRUE,
      ],
      'status' => [
        'type' => 'int',
        'not null' => TRUE,
      ],
      'tag' => [
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ],
      'job' => [
        'type' => 'blob',
        'not null' => TRUE,
      ],
      'created' => [
        'type' => 'int',
        'not null' => TRUE,
      ],
      'updated' => [
        'type' => 'int',
        'not null' => TRUE,
      ],
    ],
    'primary key' => ['id'],
    'indexes' => [
      'updated_idx' => ['updated'],
      'status_idx' => ['status'],
      'tag_idx' => ['tag'],
    ],
  ];

  return $schema;
}

/**
 * Initialize apigee_edge.dangerzone settings with default values.
 */
function apigee_edge_update_8001() {
  $config_factory = \Drupal::configFactory();

  $dangerzone_settings = $config_factory->getEditable('apigee_edge.dangerzone');
  $dangerzone_settings
    ->set('skip_developer_app_settings_validation', FALSE)
    ->set('do_not_alter_key_entity_forms', FALSE)
    ->save(TRUE);
}

/**
 * Update defaults on Apigee Auth Keys.
 */
function apigee_edge_update_8002() {
  // Empty.
  // Removed because Hybrid support makes this update hook unneeded.
}

/**
 * Increase the max_length for first_name and last_name fields.
 */
function apigee_edge_update_8101() {
  $entity_type_id = 'user';
  $fields = ['first_name', 'last_name'];
  $field_length = 64;

  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');

  /** @var \Drupal\Core\Field\FieldStorageDefinitionInterface[] $field_storage_definitions */
  $field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions($entity_type_id);
  $entity_type = $definition_update_manager->getEntityType($entity_type_id);

  $definition = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
  $data_table = $definition->getDataTable();
  $revision_data_table = $definition->getRevisionDataTable();
  $entity_storage_schema_sql = \Drupal::keyValue('entity.storage_schema.sql');

  $schema = \Drupal::database()->schema();

  // Update the field storage definition.
  foreach ($fields as $field_name) {
    $field_storage_definitions[$field_name]->setSetting('max_length', $field_length);
  }

  $definition_update_manager->updateFieldableEntityType($entity_type, $field_storage_definitions);

  // Update table schema.
  foreach ($fields as $field_name) {
    $schema_key = "$entity_type_id.field_schema_data.$field_name";
    if ($field_schema_data = $entity_storage_schema_sql->get($schema_key)) {
      // Update storage schema for data table.
      $field_schema_data[$data_table]['fields'][$field_name]['length'] = $field_length;

      // Update storage schema for the revision table.
      if ($revision_data_table) {
        $field_schema_data[$revision_data_table]['fields'][$field_name]['length'] = $field_length;
      }

      $entity_storage_schema_sql->set($schema_key, $field_schema_data);

      // Update the base database field.
      $schema->changeField($data_table, $field_name, $field_name, $field_schema_data[$data_table]['fields'][$field_name]);

      // Update schema for the revision table.
      if ($revision_data_table) {
        $schema->changeField($revision_data_table, $field_name, $field_name, $field_schema_data[$revision_data_table]['fields'][$field_name]);
      }
    }
  }
}

/**
 * Update the field storage definitions for first_name and last_name fields.
 */
function apigee_edge_update_8102() {
  $entity_type_id = 'user';
  $fields = ['first_name', 'last_name'];

  /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager */
  $entity_field_manager = Drupal::service('entity_field.manager');
  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
  $last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');

  $field_definitions = $entity_field_manager->getFieldStorageDefinitions($entity_type_id);
  $original_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions($entity_type_id);
  foreach ($fields as $field) {
    $original_storage_definitions[$field] = $field_definitions[$field];
  }

  // The schema updates are already handled in apigee_edge_update_8101().
  // This updates the last installed definition.
  $last_installed_schema_repository->setLastInstalledFieldStorageDefinitions($entity_type_id, $original_storage_definitions);
}

/**
 * Assign the "add_api_key own developer_app" permission to authenticated users.
 */
function apigee_edge_update_8103() {
  if (\Drupal::moduleHandler()->moduleExists('user')) {
    $authenticated_user_permissions = [
      'add_api_key own developer_app',
      'revoke_api_key own developer_app',
      'edit_api_products developer_app',
    ];
    user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, $authenticated_user_permissions);
  }
}

/**
 * Enable warnings field in default app view displays.
 */
function apigee_edge_update_8104() {
  foreach (['developer_app', 'team_app'] as $entity_type_id) {
    if (!\Drupal::entityTypeManager()->getDefinition($entity_type_id, FALSE)) {
      continue;
    }

    /** @var \Drupal\Core\Entity\EntityDisplayRepository $entity_display_repository */
    $entity_display_repository = \Drupal::service('entity_display.repository');
    $entity_view_display = $entity_display_repository->getViewDisplay($entity_type_id, $entity_type_id);

    if ($entity_view_display->getComponent('warnings')) {
      continue;
    }

    $entity_view_display->setComponent('warnings', [
      'region' => 'content',
      'weight' => -100,
    ])->save();
  }
}

/**
 * Deprecated update function.
 */
function apigee_edge_update_8105() {
}

/**
 * Update the default environment config for app analytics.
 */
function apigee_edge_update_8106() {
  $config_factory = \Drupal::configFactory();

  $app_settings = $config_factory->getEditable('apigee_edge.common_app_settings');
  $app_settings
    ->set('analytics_available_environments', [$app_settings->get('analytics_environment')])
    ->save(TRUE);
}

/**
 * Remove OAuth token data file.
 */
function apigee_edge_update_8107() {
  // Replaced unserialize with Json function.
  // We do not want the serialize data so deleting the file.
  $storage = \Drupal::service('apigee_edge.authentication.oauth_token_storage');
  if ($storage instanceof OauthTokenFileStorage) {
    $storage->removeTokenFile();
  }
}

/**
 * Update the field storage defination of Developer App.
 */
function apigee_edge_update_9001() {
  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
  $last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  $entity_type_id = 'developer_app';
  $entity_type = $definition_update_manager->getEntityType($entity_type_id);
  $field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions($entity_type_id);

  $field_storage_definitions['apiProducts'] = BaseFieldDefinition::create('string')
    ->setName('apiproducts')
    ->setTargetEntityTypeId($entity_type_id)
    ->setTargetBundle(NULL)
    ->setStorageRequired(FALSE)
    ->setInternal(TRUE)
    ->setTranslatable(FALSE)
    ->setRevisionable(FALSE);

  $definition_update_manager->updateFieldableEntityType($entity_type, $field_storage_definitions);
}

/**
 * Install Configs for Core Entity View Display for Default Team App
 */
function apigee_edge_update_9002() {
  // Update existing config.
  /** @var \Drupal\Core\Config\StorageInterface $config_storage */
  $config_storage = \Drupal::service('config.storage');
  $module_path = \Drupal::service('extension.list.module')->getPath('apigee_edge');
  $source = new FileStorage("$module_path/config/install");
  $new_edge_settings = $source->read('core.entity_view_display.developer_app.developer_app.default');
  $edge_settings = $config_storage->read('core.entity_view_display.developer_app.developer_app.default');
  $edge_settings['content']['callbackUrl'] = $new_edge_settings['content']['callbackUrl'];
  $config_storage->write('core.entity_view_display.developer_app.developer_app.default', $edge_settings);
}

/**
 * Set cache_insert_chunk_size for API Products, Developers, Developer apps.
 */
function apigee_edge_update_11401(): void {
  $configs = [
    'apigee_edge.api_product_settings',
    'apigee_edge.developer_settings',
    'apigee_edge.developer_app_settings',
  ];
  foreach ($configs as $config) {
    \Drupal::configFactory()->getEditable($config)->set('cache_insert_chunk_size', 100)->save(TRUE);
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc