You are here

social_event.module in Open Social 8.2

The Social event module.

File

modules/social_features/social_event/social_event.module
View source
<?php

/**
 * @file
 * The Social event module.
 */
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\group\Entity\GroupContent;
use Drupal\group\GroupMembershipLoaderInterface;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_form_form_ID_alter().
 *
 * Enhance the exposed filter form of the event overview.
 */
function social_event_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] === 'views-exposed-form-events-events-overview') {
    $form['status']['#options'][0] = t('Unpublished');
    $form['status']['#options'][1] = t('Published');
    $account_uid = \Drupal::routeMatch()
      ->getParameter('user');
    $current_uid = \Drupal::currentUser()
      ->id();
    if ($account_uid !== $current_uid) {
      $form['status']['#access'] = FALSE;
    }

    // Enable the reset button.
    // @todo make sure the block content refreshes on submit as well (AJAX).
    $form['actions']['reset']['#access'] = TRUE;

    // @todo make sure exposed form filtering redirects to the proper view
    // page, when views is updated.
    $form['#action'] = '/user/' . $account_uid . '/events';
  }
  if ($form['#id'] === 'views-exposed-form-group-events-page-group-events') {
    $group_from_route = _social_group_get_current_group();

    // Get group from route.
    if (!empty($group_from_route)) {
      $group_id = $group_from_route
        ->id();
    }
    $form['actions']['reset']['#access'] = TRUE;

    // Make sure we redirect to the current group page.
    $form['#action'] = '/group/' . $group_id . '/events';
  }
}

/**
 * Implements hook_views_query_alter().
 */
function social_event_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view
    ->id() == 'events' && $view
    ->getDisplay()->display['id'] == 'events_overview') {
    $account_uid = \Drupal::routeMatch()
      ->getParameter('user');
    $current_uid = \Drupal::currentUser()
      ->id();
    if ($view->exposed_raw_input['status'] == NODE_PUBLISHED || $account_uid !== $current_uid) {
      $query->where[1]['conditions'][] = [
        'field' => 'node_field_data.status',
        'value' => NODE_PUBLISHED,
        'operator' => '=',
      ];
    }
  }
}

/**
 * Implements hook_block_view_alter().
 *
 * Add a title to the exposed filter block on the events overview.
 */
function social_event_block_view_alter(array &$build, BlockPluginInterface $block) {

  // @todo check out why this happens, is this is a views bug?
  if (isset($build['#plugin_id']) && $build['#plugin_id'] === 'views_exposed_filter_block:events-events_overview') {
    $build['#configuration']['label'] = $build['#configuration']['views_label'];
  }
}

/**
 * Implements hook_menu_local_tasks_alter().
 */
function social_event_menu_local_tasks_alter(&$data, $route_name) {
  $can_show_enrollments_link = FALSE;
  $routes_to_check = [
    'view.event_enrollments.view_enrollments',
    'entity.node.canonical',
    'view.managers.view_managers',
  ];
  if (in_array($route_name, $routes_to_check)) {
    $node = \Drupal::service('current_route_match')
      ->getParameter('node');
    if (!is_null($node) && !$node instanceof Node) {
      $node = Node::load($node);
    }
    if ($node instanceof Node && $node
      ->getType() === 'event') {
      $can_show_enrollments_link = TRUE;
    }
  }

  // PLace this here, since hiding it should happen always
  // and not only on the mentioned routes.
  if (!$can_show_enrollments_link) {
    unset($data['tabs'][0]['views_view:view.event_enrollments.view_enrollments']);
  }
}

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function social_event_node_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  if ($entity
    ->getType() === 'event' && ($display
    ->getMode() === 'teaser' || $display
    ->getMode() === 'small_teaser')) {
    $current_user = \Drupal::currentUser();
    $uid = $current_user
      ->id();
    $nid = $entity
      ->id();

    // Create our custom enrollment tag so we can also invalidate f.e. teasers
    // cache when people enrol. See EnrollActionForm->submitForm().
    $enrollmenttag = 'enrollment:' . $nid . '-' . $uid;
    $build['#cache']['tags'][] = $enrollmenttag;
    $build['#cache']['contexts'][] = 'user';
    if (empty($nid)) {
      return;
    }
    $conditions = [
      'field_account' => $uid,
      'field_event' => $nid,
    ];
    $enrollments = \Drupal::service('entity.manager')
      ->getStorage('event_enrollment')
      ->loadByProperties($conditions);

    // Redirect anonymous use to login page before enrolling to an event.
    if ($enrollment = array_pop($enrollments)) {
      $current_enrollment_status = $enrollment->field_enrollment_status->value;
      if ($current_enrollment_status === '1') {
        $build['enrolled'] = [
          '#type' => '#text_field',
          '#markup' => t('Enrolled'),
        ];
      }
    }
  }
}

/**
 * Prepares variables for node templates.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An array of elements to display in view mode.
 *   - node: The node object.
 *   - view_mode: View mode; e.g., 'full', 'teaser', etc.
 */
function social_event_preprocess_node(array &$variables) {
  $view_mode = $variables['view_mode'];
  $node = $variables['node'];
  if ($node
    ->getType() === 'event') {
    $variables['event_date'] = _social_event_format_date($node, $view_mode);
  }
}

/**
 * Implements hook_views_data_alter().
 */
function social_event_views_data_alter(array &$data) {
  $data['node']['event_enrolled_or_created_filter'] = [
    'title' => t('Event enrolled or created'),
    'filter' => [
      'title' => t('Event enrolled or created'),
      'help' => t('Enable events for on the user profiles.'),
      'field' => 'field_event',
      'id' => 'event_enrolled_or_created',
    ],
  ];
  $data['node']['event_passed_upcoming_sort'] = [
    'title' => t('Event sorting (passed and upcoming)'),
    'help' => t('For upcoming events sort ASC by start date and for passed events change order to DESC.'),
    'sort' => [
      'field' => 'field_event_date_value',
      'id' => 'event_passed_upcoming_sort',
    ],
  ];
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function social_event_flagging_insert(EntityInterface $entity) {
  $group_type_ids = \Drupal::config('social_event.settings')
    ->get('enroll');
  if (empty($group_type_ids)) {
    return;
  }
  $current_user = \Drupal::currentUser();
  $owner = $entity
    ->getOwnerId() == $current_user
    ->id();
  $is_node = $entity->entity_type->value == 'node';
  $following = $entity
    ->getFlagId() == 'follow_content';
  if (!($owner && $is_node && $following)) {
    return;
  }
  $nid = $entity->entity_id->value;
  $node = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->load($nid);

  /** @var \Drupal\group\Entity\GroupContentInterface $groupcontent */
  foreach (GroupContent::loadByEntity($node) as $groupcontent) {

    /** @var \Drupal\group\Entity\GroupInterface $group */
    $group = $groupcontent
      ->getGroup();
    $allowed_type = in_array($group
      ->bundle(), $group_type_ids);
    $is_member = $group
      ->getMember($current_user) instanceof GroupMembershipLoaderInterface;
    if ($allowed_type && !$is_member) {
      $account = \Drupal::entityTypeManager()
        ->getStorage('user')
        ->load($current_user
        ->id());
      $group
        ->addMember($account);
    }
  }
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function social_event_user_delete(EntityInterface $entity) {
  $storage = \Drupal::entityTypeManager()
    ->getStorage('event_enrollment');
  $entities = $storage
    ->loadByProperties([
    'user_id' => $entity
      ->id(),
  ]);
  $storage
    ->delete($entities);
}

/**
 * Formats the event start end date.
 */
function _social_event_format_date($event, $view_mode) {
  $event_date = '';

  // This will get the users timezone, which is either set by the user
  // or defaults back to the sites timezone if the user didn't select any.
  $timezone = drupal_get_user_timezone();

  // Get start and end dates.
  if ($start_date_field = $event->field_event_date) {
    if (!empty($start_date_field->value)) {

      // Since dates are stored as UTC, we will declare our event values
      // as UTC. So we can actually calculate them back to the users timezone.
      // This is necessary because we do not store the event value as being UTC
      // so declaring it with setTimezone will result in wrong values.
      $start_datetime = new DateTime($start_date_field->value, new DateTimeZone("UTC"));
      $start_datetime
        ->setTimezone(new DateTimeZone($timezone));
      $start_datetime = $start_datetime
        ->getTimestamp();
    }
  }
  if ($end_date_field = $event->field_event_date_end) {
    if (!empty($end_date_field->value)) {

      // Since dates are stored as UTC, we will declare our event values
      // as UTC. So we can actually calculate them back to the users timezone.
      // This is necessary because we do not store the event value as being UTC
      // so declaring it with setTimezone will result in wrong values.
      $end_datetime = new DateTime($end_date_field->value, new DateTimeZone("UTC"));

      // We now calculate it back to the users timezone.
      $end_datetime
        ->setTimezone(new DateTimeZone($timezone));
      $end_datetime = $end_datetime
        ->getTimestamp();
    }
  }

  // Get date and time formats.
  $date_formatter = \Drupal::service('date.formatter');
  $date_format = $view_mode === 'hero' ? 'social_long_date' : 'social_medium_extended_date';
  $time_format = 'social_time';
  if (!empty($start_datetime)) {

    // Date are the same or there are no end date.
    if (empty($end_datetime) || $start_datetime == $end_datetime) {
      $date = $date_formatter
        ->format($start_datetime, $date_format);
      $time = $date_formatter
        ->format($start_datetime, $time_format);
      $event_date = "{$date} - {$time}";
    }
    elseif (date('Y-m-d', $start_datetime) == date('Y-m-d', $end_datetime)) {
      $date = $date_formatter
        ->format($start_datetime, $date_format);
      $start_time = $date_formatter
        ->format($start_datetime, $time_format);
      $end_time = $date_formatter
        ->format($end_datetime, $time_format);
      $event_date = "{$date} {$start_time} - {$end_time}";
    }
    elseif (!empty($end_datetime)) {
      $start_date = $date_formatter
        ->format($start_datetime, $date_format);
      $end_date = $date_formatter
        ->format($end_datetime, $date_format);
      $start_time = $date_formatter
        ->format($start_datetime, $time_format);
      $end_time = $date_formatter
        ->format($end_datetime, $time_format);
      $event_date = "{$start_date} {$start_time} - {$end_date} {$end_time}";
    }
  }
  return $event_date;
}