You are here

opigno_calendar.module in Opigno calendar 3.x

Same filename and directory in other branches
  1. 8 opigno_calendar.module

File

opigno_calendar.module
View source
<?php

/**
 * @file
 * Contains opigno_calendar.module.
 */
use Drupal\Component\Datetime\DateTimePlus;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Url;
use Drupal\user\Entity\User;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_theme().
 */
function opigno_calendar_theme($existing, $type, $theme, $path) {
  return [
    'block__opigno_calendar' => [
      'base hook' => 'block',
      'add_event_link' => NULL,
    ],
    'opigno_calendar_add_event' => [
      'variables' => [
        'add_event_link' => NULL,
      ],
    ],
    'opigno_calendar_today' => [
      'variables' => [],
    ],
  ];
}

/**
 * Implements hook_page_attachments().
 */
function opigno_calendar_page_attachments(array &$page) {
  $route = \Drupal::routeMatch()
    ->getRouteName();

  // Attach library to front page.
  if (in_array($route, [
    'opigno_dashboard.dashboard_admin_default_settings',
    'view.frontpage.page_1',
  ])) {
    $page['#attached']['library'][] = 'opigno_calendar/month_block';
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function opigno_calendar_preprocess_calendar_month_col(&$variables) {
  if (empty($variables['item']['entry'])) {
    return;
  }
  $entry =& $variables['item']['entry'];
  if ($variables['item']['date'] === date('Y-m-d')) {
    $variables['item']['entry']['#selected'] = TRUE;
  }
  if (!is_array($entry) || isset($entry['#theme'])) {
    return;
  }
  $attached = [
    'library' => [
      'opigno_calendar/month_block',
    ],
  ];
  if (isset($entry[0]['#theme']) && $entry[0]['#theme'] === 'calendar_empty_day') {
    $entry['#attached'] = $attached;
    return;
  }

  /** @var \Drupal\views\ViewExecutable $view */
  $view = $entry[0]['#view'];
  if (!$view || $view
    ->getDisplay()
    ->getOption('css_class') !== 'opigno-calendar-views' && $view
    ->getDisplay()
    ->getOption('css_class') !== 'view-opigno-calendar' || $view->current_display !== 'month_block' && $view->current_display !== 'page_month') {
    return;
  }

  // Add see more link for month_block.
  if ($view->current_display === 'month_block') {

    // display only 2 events.
    if (count($entry) > 2) {
      $entry = array_slice($entry, 0, 2);
    }
    $month = $view->args[0];
    $entry[] = [
      '#title' => t('See more'),
      '#type' => 'link',
      '#url' => URL::fromUri('internal:/opigno/calendar/' . $month, [
        'query' => [
          'day' => $variables['item']['day_of_month'],
        ],
      ]),
    ];
  }
  $entry = opigno_calendar_generate_entry($variables, $entry, $attached);
}

/**
 * Build day date box.
 */
function opigno_calendar_generate_entry($variables, $content, $attached) {
  $date = new DateTimePlus($variables['item']['date']);
  return [
    '#attached' => $attached,
    'date_box' => [
      '#theme_wrappers' => [
        'container',
      ],
      '#attributes' => [
        'class' => [
          'date-box',
        ],
      ],
      'content' => [
        'day' => [
          '#type' => 'html_tag',
          '#tag' => 'span',
          '#attributes' => [
            'class' => [
              'date-day',
            ],
          ],
          '#value' => $date
            ->format('d'),
        ],
        'month' => [
          '#type' => 'html_tag',
          '#tag' => 'span',
          '#attributes' => [
            'class' => [
              'date-month',
            ],
          ],
          '#value' => t($date
            ->format('F')),
        ],
        'year' => [
          '#type' => 'html_tag',
          '#tag' => 'span',
          '#attributes' => [
            'class' => [
              'date-year',
            ],
          ],
          '#value' => $date
            ->format('Y'),
        ],
      ],
    ],
    'items' => [
      '#theme_wrappers' => [
        'container',
      ],
      '#attributes' => [
        'class' => [
          'items',
        ],
      ],
      'content' => $content,
    ],
  ];
}

/**
 * Implements hook_theme_suggestions_alter().
 */
function opigno_calendar_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['elements']['content']['#view_id'])) {
    if (\Drupal::routeMatch()
      ->getRouteName() == 'view.opigno_calendar.page_month' && $variables['elements']['content']['#view_id'] == 'opigno_calendar' && $hook == 'block') {
      $suggestions[] = 'block__opigno_calendar';
    }
  }
}

/**
 * Implements hook_theme_registry_alter
 */
function opigno_calendar_theme_registry_alter(&$theme_registry) {
  $theme_registry['calendar_month_col']['path'] = drupal_get_path('module', 'opigno_calendar') . '/templates';
}

/**
 * Implements hook_preprocess_HOOK().
 */
function opigno_calendar_preprocess_block__opigno_calendar(&$variables) {
  $user = \Drupal::currentUser();
  if (isset($variables['elements']['content']['#view_id'])) {
    if ($variables['elements']['content']['#view_id'] == 'opigno_calendar' && $user
      ->hasPermission('create opigno_calendar_event')) {

      // Add to calendar block 'add event' button.
      $url = Url::fromRoute('entity.opigno_calendar_event.add_form', [
        'opigno_calendar_event_type' => 'opigno_calendar_event',
      ]);
      if ($url
        ->access()) {
        $variables['add_event_link'] = Markup::create("<div class='next-link d-flex justify-content-end mb-4 text-uppercase'><a class='btn btn-success color-white add_event_link' href='" . $url
          ->toString() . "'><i class='icon-pencil mr-2'></i>" . t('add event') . "</a></div>");
      }
    }
  }
  return $variables;
}

/**
 * Implements hook_form_alter().
 */
function opigno_calendar_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, [
    'opigno_calendar_event_opigno_calendar_event_form',
    'opigno_calendar_event_opigno_calendar_event_edit_form',
  ])) {
    $current_user = \Drupal::currentUser();
    $uid = $current_user
      ->id();
    $current_user = User::load($uid);

    /** @var \Drupal\Core\Entity\EntityFormInterface $form_object */
    $form_object = $form_state
      ->getFormObject();

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_object
      ->getEntity();
    if (!$entity
      ->hasField('field_calendar_event_members')) {
      return;
    }

    // Save in storage current user id.
    $storage = $form_state
      ->getStorage();
    $storage['current_user_id'] = $uid;
    $form_state
      ->setStorage($storage);
    $plugin_service = \Drupal::service('opigno_learning_path.members.manager');
    $plugin_instance = $plugin_service
      ->createInstance('members_plugin');
    $plugin_instance
      ->getMembersForm($form, $form_state, $current_user);
    $form['#validate'][] = 'opigno_calendar_event_opigno_calendar_event_form_validate';
    if ($form_id == 'opigno_calendar_event_opigno_calendar_event_form') {

      // Add redirect handler to form.
      $form['actions']['submit']['#submit'][] = 'opigno_calendar_event_form_submit_handler';
      $members =& $form['members']['field_calendar_event_members'];
      if (!empty($members["widget"]["#options"]) && array_key_exists($uid, $members["widget"]["#options"])) {

        // Remove current user from options.
        unset($members["widget"]["#options"][$uid]);
      }
      $form['#attached']['library'][] = 'opigno_calendar/form';
    }
  }
}

/**
 * Submit callback used in opigno_calendar_form_alter().
 *
 * @see opigno_calendar_form_alter()
 */
function opigno_calendar_event_form_submit_handler(&$form, FormStateInterface $form_state) {

  // Set redirect to calendar page.
  $form_state
    ->setRedirect('view.opigno_calendar.page_month');
}

/**
 * Custom validation.
 */
function opigno_calendar_event_opigno_calendar_event_form_validate(&$form, FormStateInterface $form_state) {
  if (!isset($_GET["ajax_form"])) {
    $no_errors = TRUE;
    $title = $form_state
      ->getValue('title');
    if (empty($title[0]['value'])) {
      $form_state
        ->setErrorByName('title', t("Please enter a title!"));
      $no_errors = FALSE;
    }
    $date = $form_state
      ->getValue('date_daterange');
    if (isset($date[0]["value_wrapper"]["date"]) && empty($date[0]["value_wrapper"]["date"])) {
      $form_state
        ->setErrorByName('date_daterange', t("Please select start date!"));
      $no_errors = FALSE;
    }
    if (isset($date[0]["end_value_wrapper"]["date"]) && empty($date[0]["end_value_wrapper"]["date"])) {
      $form_state
        ->setErrorByName('date_daterange', t("Please select end date!"));
      $no_errors = FALSE;
    }
    if ($no_errors) {
      $storage = $form_state
        ->getStorage();
      if (!empty($storage["current_user_id"])) {
        $add_as_member = FALSE;
        $members = $form_state
          ->getValue('field_calendar_event_members');
        if ($form["#form_id"] == 'opigno_calendar_event_opigno_calendar_event_form') {

          // If event was just created.
          $add_as_member = TRUE;
        }
        else {

          // If event was edited.
          $route = \Drupal::routeMatch();
          if ($event = $route
            ->getParameter('opigno_calendar_event')) {

            // Get event author.
            $author_id = $event
              ->get('uid')
              ->getValue();
            $author_id = $author_id[0]['target_id'];
            if ($author_id == $storage["current_user_id"] && !in_array($storage["current_user_id"], array_column($members, 'target_id'))) {
              $add_as_member = TRUE;
            }
          }
        }
        if ($add_as_member) {

          // Add current user as a member if he is an author.
          $members[] = [
            'target_id' => $storage["current_user_id"],
          ];
          $form_state
            ->setValue('field_calendar_event_members', $members);
        }
      }
    }
  }
}

/**
 * Implements hook_views_pre_render().
 */
function opigno_calendar_views_pre_render(ViewExecutable $view) {
  if ($view
    ->id() !== 'opigno_calendar') {
    return;
  }
  $account = Drupal::currentUser();
  if (!empty($view->result)) {
    foreach ($view->result as $key => $result) {
      if (empty($result->_entity)) {
        continue;
      }

      // Allow access for admins and other user with according permissions.
      if ($account
        ->hasPermission('manage group members in any group') || $account
        ->hasPermission('manage group content in any group')) {
        continue;
      }

      // If current user is a direct member of the calendar event.
      if ($result->_entity
        ->hasField('field_calendar_event_members')) {

        // If there are no members - continue.
        if (!count($result->_entity
          ->get('field_calendar_event_members')
          ->getValue())) {
          continue;
        }
        $members = array_map(function ($member) {
          return (int) $member['target_id'];
        }, $result->_entity
          ->get('field_calendar_event_members')
          ->getValue());
        if (in_array($account
          ->id(), $members)) {
          continue;
        }
      }
      else {
        continue;
      }
      unset($view->result[$key]);
    }
  }
}

/**
 * Implements hook_preprocess_page_title().
 */
function opigno_calendar_preprocess_page_title(&$variables) {
  if (\Drupal::routeMatch()
    ->getRouteName() == 'view.opigno_calendar.page_month') {
    $variables['title']['#allowed_tags'][] = 'span';
    $variables['title']['#markup'] = '<span class="sr-only">' . $variables['title']['#markup'] . '</span>';
  }
}