You are here

social_profile.install in Open Social 10.2.x

Install, update and uninstall functions for the social_profile module.

File

modules/social_features/social_profile/social_profile.install
View source
<?php

/**
 * @file
 * Install, update and uninstall functions for the social_profile module.
 */
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Entity\Entity\EntityViewMode;
use Drupal\file\Entity\File;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\user\Entity\Role;
use Drupal\block\Entity\Block;
use Drupal\profile\Entity\Profile;
use Drupal\profile\Entity\ProfileType;
use Drupal\user\Entity\User;
use Symfony\Component\Yaml\Yaml;

/**
 * Implements hook_install().
 *
 * Perform actions related to the installation of social_profile.
 */
function social_profile_install() {

  // Set some default permissions.
  _social_profile_set_permissions();

  // Add some links.
  _social_profile_create_menu_links();

  // Add default profile image.
  _social_profile_add_default_profile_image();

  // Update the field definitions.
  _social_profile_field_definitions_update();

  // Create a profile for user 1.
  Profile::create([
    'type' => ProfileType::load('profile')
      ->id(),
    'uid' => 1,
  ])
    ->save();
}

/**
 * Function to set default profile image if not set already.
 */
function _social_profile_add_default_profile_image() {

  // Add default image.
  $config_factory = \Drupal::configFactory();
  $field_image_config = $config_factory
    ->getEditable('field.field.profile.profile.field_profile_image');
  $default_image = $field_image_config
    ->get('settings.default_image');
  $uri = Drupal::service('file_system')
    ->copy(drupal_get_path('module', 'social_profile') . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'default-profile-picture.png', 'public://default-profile-picture.png', FileSystemInterface::EXISTS_REPLACE);
  $media = File::create([
    'uri' => $uri,
  ]);
  $media->uuid = '4eb1d927-28f4-402a-8c87-017e637f434a';
  $media->status = 1;
  $media
    ->save();
  $default_image['uuid'] = $media
    ->uuid();
  $default_image['alt'] = 'Default profile image';
  $default_image['title'] = 'Default profile image';
  $default_image['height'] = 200;
  $default_image['width'] = 200;
  $field_image_config
    ->set('settings.default_image', $default_image)
    ->save(TRUE);
  drupal_flush_all_caches();
}

/**
 * Function to set permissions.
 */
function _social_profile_set_permissions() {
  $roles = Role::loadMultiple();

  /** @var \Drupal\user\Entity\Role $role */
  foreach ($roles as $role) {
    if ($role
      ->id() === 'administrator') {
      continue;
    }
    $permissions = _social_profile_get_permissions($role
      ->id());
    user_role_grant_permissions($role
      ->id(), $permissions);
  }
}

/**
 * Return the permissions per role.
 *
 * @param string $role
 *   The role to get the permissions for.
 *
 * @return array
 *   A list of permissions.
 */
function _social_profile_get_permissions($role) {

  // Anonymous.
  $permissions['anonymous'] = [];

  // Authenticated.
  $permissions['authenticated'] = array_merge($permissions['anonymous'], [
    'add own profile profile',
    'update own profile profile',
    'view any profile profile',
    'view own profile profile',
    'view profile',
  ]);

  // Content manager.
  $permissions['contentmanager'] = array_merge($permissions['authenticated'], [
    'add any profile profile',
    'update any profile profile',
    'edit profile tags',
  ]);

  // Site manager.
  $permissions['sitemanager'] = array_merge($permissions['contentmanager'], [
    'delete terms in profile_tag',
    'edit terms in profile_tag',
    'administer profile settings',
    'view profile email',
    'view profile language',
  ]);
  if (isset($permissions[$role])) {
    return $permissions[$role];
  }
  return [];
}

/**
 * Function to create some menu items.
 */
function _social_profile_create_menu_links() {
  $menu_links = MenuLinkContent::loadMultiple();
  $parent = NULL;

  /** @var \Drupal\menu_link_content\Entity\MenuLinkContent $menu_link */
  foreach ($menu_links as $menu_link) {
    if ($menu_link
      ->label() === 'Explore' && $menu_link
      ->isExpanded()) {
      $parent = 'menu_link_content:' . $menu_link
        ->uuid();
    }
  }
  if (!is_null($parent)) {
    MenuLinkContent::create([
      'title' => 'All members',
      'link' => [
        'uri' => 'internal:/all-members',
      ],
      'menu_name' => 'main',
      'expanded' => FALSE,
      'weight' => 50,
      'parent' => $parent,
    ])
      ->save();
  }
}

/**
 * Implements hook_uninstall().
 */
function social_profile_uninstall() {
  \Drupal::service('config.factory')
    ->getEditable('social_profile.settings')
    ->delete();
}

/**
 * Set default profile image.
 */
function social_profile_update_8002(&$sandbox) {

  // Only run when there is not a file added to the file managed table.
  // Confirmed that it's not there on our current platforms. (But is locally).
  $query = \Drupal::database()
    ->select('file_managed', 'fm');
  $query
    ->addField('fm', 'uuid');
  $query
    ->condition('fm.filename', 'default-profile-picture.png');
  $query
    ->range(0, 1);
  $result = $query
    ->execute()
    ->fetchField();

  // $result will be FALSE if there is no UUID available.
  if (!$result) {
    _social_profile_add_default_profile_image();
  }
}

/**
 * Add social_profile.settings config. Update permissions for SM role.
 */
function social_profile_update_8003(&$sandbox) {
  $config = \Drupal::configFactory()
    ->getEditable('social_profile.settings');
  $config
    ->set('social_profile_show_email', 1);
  $config
    ->save();

  // Add permission to view profile email and administer profile settings for
  // sitemanager role.
  $roles = Role::loadMultiple();
  $permissions = [
    'administer profile settings',
    'view profile email',
  ];

  /** @var \Drupal\user\Entity\Role $role */
  foreach ($roles as $role) {
    if ($role
      ->id() === 'sitemanager') {
      user_role_grant_permissions($role
        ->id(), $permissions);
    }
  }
}

/**
 * Add edit own and edit any profile permissions after update to Profile beta1.
 */
function social_profile_update_8004(&$sandbox) {
  $roles = Role::loadMultiple();
  $lu_permissions = [
    'update own profile profile',
  ];
  $cm_permissions = [
    'update any profile profile',
  ];

  /** @var \Drupal\user\Entity\Role $role */
  foreach ($roles as $role) {
    if ($role
      ->id() === 'authenticated') {
      user_role_grant_permissions($role
        ->id(), $lu_permissions);
    }
    if ($role
      ->id() === 'contentmanager' || $role
      ->id() === 'sitemanager') {
      user_role_grant_permissions($role
        ->id(), $cm_permissions);
    }
  }
}

/**
 * Update the context_mapping for profile_hero_block blocks.
 */
function social_profile_update_8005() {
  $blocks = Block::loadMultiple();

  /** @var \Drupal\block\BlockInterface $block */
  foreach ($blocks as $block) {
    if ($block
      ->getPluginId() == 'profile_hero_block') {
      $settings = $block
        ->get('settings');
      if (!isset($settings['context_mapping']['user'])) {
        $settings['context_mapping']['user'] = '@social_user.user_route_context:user';
        $block
          ->set('settings', $settings);
        $block
          ->save();
      }
    }
  }
}

/**
 * Create a profile for users that have none.
 */
function social_profile_update_8006(&$sandbox) {
  if (!isset($sandbox['progress'])) {

    // This must be the first run. Initialize the sandbox.
    $sandbox['progress'] = 0;
    $sandbox['profiles_created'] = 0;

    // We use array_values to get the entity_ids.
    // Not interested in the revisions.
    $sandbox['uids'] = array_values(\Drupal::entityQuery('user')
      ->execute());
    $sandbox['user_count'] = count($sandbox['uids']);
    \Drupal::logger('social_profile')
      ->info('Checking profile status for @count users', [
      '@count' => $sandbox['user_count'],
    ]);
  }

  // Try to do 5 each cycle. Never do more than are available.
  for ($target = $sandbox['progress'] + 5; $sandbox['progress'] < $target && $sandbox['progress'] < $sandbox['user_count']; $sandbox['progress']++) {
    $uid = $sandbox['uids'][$sandbox['progress']];

    /** @var \Drupal\user\Entity\User $account */
    $account = User::load($uid);

    // For anonymous we do nothing.
    if ($account
      ->isAnonymous()) {
      continue;
    }

    // Check if the user has a profile already.
    $profile = \Drupal::entityTypeManager()
      ->getStorage('profile')
      ->loadByUser($account, ProfileType::load('profile')
      ->id(), TRUE);
    if (!$profile) {
      try {
        Profile::create([
          'type' => ProfileType::load('profile')
            ->id(),
          'uid' => $account
            ->id(),
        ])
          ->save();
        $sandbox['profiles_created']++;
      } catch (Exception $e) {
        \Drupal::logger('social_profile')
          ->error('Could not create profile for @user_id', [
          '@user_id' => $uid,
        ]);
      }
    }
  }
  $sandbox['#finished'] = empty($sandbox['user_count']) ? 1 : $sandbox['progress'] / $sandbox['user_count'];
  if ($sandbox['#finished'] === 1) {
    \Drupal::logger('social_profile')
      ->info('Created profiles for @count users', [
      '@count' => $sandbox['profiles'],
    ]);
  }
}

/**
 * Grant the 'view profile' permission.
 */
function social_profile_update_8007(&$sandbox) {
  $roles = [
    'authenticated',
    'contentmanager',
    'sitemanager',
  ];
  $permissions = [
    'view profile',
  ];
  foreach ($roles as $role) {
    user_role_grant_permissions($role, $permissions);
  }
}

/**
 * Remove title property from field_profile_image.
 */
function social_profile_update_8008() {

  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper
    ->executeUpdate('social_profile', 'social_profile_update_8008');

  // Output logged messages to related channel of update execution.
  return $updateHelper
    ->logger()
    ->output();
}

/**
 * Implements hook_update_dependencies().
 */
function social_profile_update_dependencies() {

  // Run the config update after the update_helper module is enabled.
  $dependencies['social_profile'][8808] = [
    'social_core' => 8805,
  ];
  return $dependencies;
}

/**
 * Create medium_teaser profile view mode.
 */
function social_profile_update_8009() {

  // Create a new profile entity view mode.
  EntityViewMode::create([
    'targetEntityType' => 'profile',
    'id' => 'profile.medium_teaser',
    'status' => TRUE,
    'label' => t('Medium Teaser'),
  ])
    ->save();

  // Load teaser profile view mode.
  $display = EntityViewDisplay::load('profile.profile.teaser')
    ->toArray();

  // Make sure that labels are hidden for all fields.
  foreach ($display['content'] as &$field) {
    $field['label'] = 'hidden';
  }

  // Create the corresponding entity view display for profile entity type.
  $display = array_merge($display, [
    'uuid' => NULL,
    'targetEntityType' => 'profile',
    'bundle' => 'profile',
    'mode' => 'medium_teaser',
  ]);
  EntityViewDisplay::create($display)
    ->save();
}

/**
 * Update small_teaser profile view mode.
 */
function social_profile_update_8010() {

  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper
    ->executeUpdate('social_profile', 'social_profile_update_8008');

  // Output logged messages to related channel of update execution.
  return $updateHelper
    ->logger()
    ->output();
}

/**
 * Update small_teaser profile view mode again, last one had the wrong yml file.
 */
function social_profile_update_8801() {

  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper
    ->executeUpdate('social_profile', 'social_profile_update_8010');

  // Output logged messages to related channel of update execution.
  return $updateHelper
    ->logger()
    ->output();
}

/**
 * Update social_profile.settings config & permissions for authenticated role.
 */
function social_profile_update_8802(&$sandbox) {
  $config = \Drupal::configFactory()
    ->getEditable('social_profile.settings');
  $config
    ->set('social_profile_show_language', TRUE);
  $config
    ->save();

  // Add permission to view profile language for authenticated role.
  $roles = Role::loadMultiple();
  $permissions = [
    'view profile language',
  ];

  /** @var \Drupal\user\Entity\Role $role */
  foreach ($roles as $role) {
    if (in_array($role
      ->id(), [
      'sitemanager',
      'contentmanager',
    ])) {
      user_role_grant_permissions($role
        ->id(), $permissions);
    }
  }
}

/**
 * Moved the profile's banner field above image field.
 */
function social_profile_update_8803() {

  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper
    ->executeUpdate('social_profile', 'social_profile_update_8803');

  // Output logged messages to related channel of update execution.
  return $updateHelper
    ->logger()
    ->output();
}

/**
 * Add a new block to display filters (social_tagging) on all-members page.
 *
 * Load in a config file from an specific update hook that will never change.
 */
function social_profile_update_8901() {
  $config_files = [
    'block.block.exposedformnewest_userspage_newest_users' => drupal_get_path('module', 'social_profile') . '/config/static/block.block.exposedformnewest_userspage_newest_users_8901.yml',
    'block.block.socialblue_exposedformnewest_userspage_newest_users' => drupal_get_path('module', 'social_profile') . '/config/static/block.block.socialblue_exposedformnewest_userspage_newest_users_8901.yml',
  ];
  foreach ($config_files as $key => $config_file) {
    if (is_file($config_file)) {
      $settings = Yaml::parse(file_get_contents($config_file));
      if (is_array($settings)) {
        $config = \Drupal::configFactory()
          ->getEditable($key);
        $config
          ->setData($settings)
          ->save(TRUE);
      }
    }
  }
}

/**
 * Enable exposed filters block on all-members views.
 */
function social_profile_update_8902() {

  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper
    ->executeUpdate('social_profile', 'social_profile_update_8902');

  // Output logged messages to related channel of update execution.
  return $updateHelper
    ->logger()
    ->output();
}

/**
 * Sets default profile settings.
 */
function social_profile_update_8903() {
  \Drupal::configFactory()
    ->getEditable('social_profile.settings')
    ->set('enable_profile_tagging', TRUE)
    ->save();
}

/**
 * Update the field definitions on install, or in an update hook.
 */
function _social_profile_field_definitions_update() {

  // Create field storage for the 'Profile Name' base field.
  \Drupal::entityTypeManager()
    ->clearCachedDefinitions();
  \Drupal::service('entity.definition_update_manager')
    ->applyUpdates();
}

/**
 * Install Profile name field to profile entity type.
 */
function social_profile_update_8904() {
  $field_storage_definition = BaseFieldDefinition::create('string')
    ->setLabel(t('Profile name'))
    ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
    ->setReadOnly(TRUE);
  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $update_manager
    ->installFieldStorageDefinition('profile_name', 'profile', 'social_profile', $field_storage_definition);
}

/**
 * Update field definitions.
 */
function social_profile_update_8905() {
  _social_profile_field_definitions_update();
}

/**
 * Update profile form labels.
 */
function social_profile_update_10201() {

  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper
    ->executeUpdate('social_profile', 'social_profile_update_10201');

  // Output logged messages to related channel of update execution.
  return $updateHelper
    ->logger()
    ->output();
}

Functions

Namesort descending Description
social_profile_install Implements hook_install().
social_profile_uninstall Implements hook_uninstall().
social_profile_update_10201 Update profile form labels.
social_profile_update_8002 Set default profile image.
social_profile_update_8003 Add social_profile.settings config. Update permissions for SM role.
social_profile_update_8004 Add edit own and edit any profile permissions after update to Profile beta1.
social_profile_update_8005 Update the context_mapping for profile_hero_block blocks.
social_profile_update_8006 Create a profile for users that have none.
social_profile_update_8007 Grant the 'view profile' permission.
social_profile_update_8008 Remove title property from field_profile_image.
social_profile_update_8009 Create medium_teaser profile view mode.
social_profile_update_8010 Update small_teaser profile view mode.
social_profile_update_8801 Update small_teaser profile view mode again, last one had the wrong yml file.
social_profile_update_8802 Update social_profile.settings config & permissions for authenticated role.
social_profile_update_8803 Moved the profile's banner field above image field.
social_profile_update_8901 Add a new block to display filters (social_tagging) on all-members page.
social_profile_update_8902 Enable exposed filters block on all-members views.
social_profile_update_8903 Sets default profile settings.
social_profile_update_8904 Install Profile name field to profile entity type.
social_profile_update_8905 Update field definitions.
social_profile_update_dependencies Implements hook_update_dependencies().
_social_profile_add_default_profile_image Function to set default profile image if not set already.
_social_profile_create_menu_links Function to create some menu items.
_social_profile_field_definitions_update Update the field definitions on install, or in an update hook.
_social_profile_get_permissions Return the permissions per role.
_social_profile_set_permissions Function to set permissions.