You are here

opigno_dashboard.module in Opigno dashboard 8

Same filename and directory in other branches
  1. 3.x opigno_dashboard.module

File

opigno_dashboard.module
View source
<?php

/**
 * @file
 * Contains opigno_dashboard.module.
 */
use Drupal\block\Entity\Block;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\GeneratedUrl;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\opigno_dashboard\BlockService;
use Drupal\opigno_tour\OpignoTourFunctions;
use Drupal\user\UserInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\opigno_dashboard\Controller\DashboardController;
define('OPIGNO_DASHBOARD_DEFAULT_CONFIG', '{"1":[{"admin_label":"Latest active trainings","id":"views_block:latest_active_trainings-block"}, {"admin_label":"Private Message: Dashboard - Last Threads","id":"views_block:private_message-block_dashboard"}],"2":[{"admin_label":"Opigno calendar block","id":"views_block:opigno_calendar-month_block"},{"admin_label":"Opigno Notifications: Dashboard - Unread Notifications","id":"views_block:opigno_notifications-block_unread_dashboard"}],"3":[]}');

/**
 * Implements hook_help().
 */
function opigno_dashboard_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {

    // Main module help for the opigno_dashboard module.
    case 'help.page.opigno_dashboard':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Opigno dashboard') . '</p>';
      return $output;
    default:
  }
}

/**
 * Implements hook_theme().
 */
function opigno_dashboard_theme() {
  return [
    'opigno_dashboard' => [
      'base hook' => 'region',
      'variables' => [
        'base_path' => '',
        'base_href' => '',
        'route_name' => '',
        'default_config' => NULL,
      ],
    ],
    'opigno_dashboard_default' => [
      'base hook' => 'region',
      'variables' => [
        'base_path' => '',
        'base_href' => '',
        'route_name' => '',
        'default_config' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_preprocess_region().
 */
function opigno_dashboard_preprocess_region(&$variables) {
  $request = \Drupal::request();
  $route_name = \Drupal::routeMatch()
    ->getRouteName();
  if (in_array($route_name, [
    'view.frontpage.page_1',
    'opigno_dashboard.dashboard_admin_default_settings',
  ]) && $variables['region'] == 'content') {
    $variables['base_path'] = \Drupal::request()
      ->getBasePath();
    $variables['base_href'] = $request
      ->getPathInfo();
    $variables['route_name'] = $route_name;

    // Get default config for dashboard blocks.
    if ($route_name == 'opigno_dashboard.dashboard_admin_default_settings') {
      $variables['default_config'] = '{}';
    }
    else {
      $dashboard = new DashboardController();
      $default_dashboard = $dashboard
        ->getUserDefaultPositioning();
      $positions = json_encode($default_dashboard['positions']);
      $columns = $default_dashboard['columns'];
      $variables['default_config'] = !empty($positions) ? $positions : OPIGNO_DASHBOARD_DEFAULT_CONFIG;
    }
    $variables['default_columns'] = !empty($columns) ? $columns : 3;

    /** @var \Drupal\Core\Menu\LocalTaskManagerInterface $manager */
    $manager = \Drupal::service('plugin.manager.menu.local_task');

    /** @var \Drupal\Core\Cache\CacheableMetadata $cacheability */
    $cacheability = new CacheableMetadata();
    $cacheability
      ->addCacheableDependency($manager);
    $tabs = [
      '#theme' => 'menu_local_tasks',
    ];
    $primary = $manager
      ->getLocalTasks(\Drupal::routeMatch()
      ->getRouteName(), 0);
    $cacheability = $cacheability
      ->merge($primary['cacheability']);
    $tabs += [
      '#primary' => count(Element::getVisibleChildren($primary['tabs'])) > 1 ? $primary['tabs'] : [],
    ];
    $secondary = $manager
      ->getLocalTasks(\Drupal::routeMatch()
      ->getRouteName(), 1);
    $cacheability = $cacheability
      ->merge($secondary['cacheability']);
    $tabs += [
      '#secondary' => count(Element::getVisibleChildren($secondary['tabs'])) > 1 ? $secondary['tabs'] : [],
    ];
    $variables['tabs'] = $tabs;
  }
}

/**
 * Implements hook_theme_suggestions_alter().
 */
function opigno_dashboard_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  // Override default frontpage content region.
  if (\Drupal::routeMatch()
    ->getRouteName() == 'view.frontpage.page_1' && in_array('region__content', $suggestions)) {
    $suggestions[] = 'opigno_dashboard';
  }
  if (\Drupal::routeMatch()
    ->getRouteName() == 'opigno_dashboard.dashboard_admin_default_settings' && in_array('region__content', $suggestions)) {
    $suggestions[] = 'opigno_dashboard_default';
  }
}

/**
 * Implements hook_page_attachments().
 */
function opigno_dashboard_page_attachments(array &$page) {

  // Add dashboard libaries.
  $route_name = \Drupal::routeMatch()
    ->getRouteName();
  if ($route_name == 'view.frontpage.page_1' || $route_name == 'opigno_dashboard.dashboard_admin_default_settings') {
    $page['#attached']['library'][] = 'opigno_dashboard/ng_app';
    $manage_dashboard_access = Drupal::currentUser()
      ->hasPermission('opigno dashboard layout access');
    $page['#attached']['drupalSettings']['manageDashboardAccess'] = $manage_dashboard_access;
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function opigno_dashboard_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $route = \Drupal::routeMatch();
  if (strpos($route
    ->getRouteName(), 'rest.') !== FALSE) {
    return;
  }

  // Restrict by route for avoid issues with REST ect.
  if ($route
    ->getRouteName() == 'user.login') {

    // Redirect user to the previous page.
    $previous_url = \Drupal::request()->query
      ->get('prev_path');
    if (!empty($previous_url)) {

      // Save redirect url to user private_tempstore in the first form loading.
      $tempstore = \Drupal::service('user.private_tempstore')
        ->get('opigno_dashboard');
      $tempstore
        ->set('prev_path', $previous_url);
    }
    else {

      // Drupal will redirect to /user/login page before submit and rebuild form.
      $tempstore = \Drupal::service('user.private_tempstore')
        ->get('opigno_dashboard');
      $prev_path = $tempstore
        ->get('prev_path');
      if (!empty($prev_path)) {
        $form_state
          ->set('prev_path', $prev_path);
      }
    }
  }
}

/**
 * Implements hook_user_login().
 */
function opigno_dashboard_user_login(UserInterface $account) {
  $route_name = \Drupal::routeMatch()
    ->getRouteName();

  // Skip on user reset routed and reset pass.
  if (strpos($route_name, 'rest.') !== FALSE || $route_name === 'user.reset.login') {
    return;
  }
  if (!empty($_GET['profile']) && $_GET['profile'] == 'opigno_lms' && !empty($_POST['form_id']) && $_POST['form_id'] == 'install_configure_form') {

    // Do not use this during installation.
    return;
  }

  // Redirect to the previous page (if exists), otherwise - or to the homepage
  // after the login.
  $previous = \Drupal::service('user.private_tempstore')
    ->get('opigno_dashboard')
    ->get('prev_path') ?? NULL;

  // Add the "tour" parameter to the url to avoid the unneeded page reload in
  // the next case: if the tour module exists and enabled and if the route is in
  // the list of tour-enabled and hasn't been already viewed.
  $params = [];
  $default_path = \Drupal::config('system.site')
    ->get('page.front') ?? '<front>';
  $default_route = \Drupal::pathValidator()
    ->getUrlIfValid($default_path)
    ->getRouteName();
  if (\Drupal::moduleHandler()
    ->moduleExists('opigno_tour') && OpignoTourFunctions::checkRouteTour($default_route) && !OpignoTourFunctions::isPageUserViewed($default_route, $account
    ->id())) {
    $params = [
      'query' => [
        'tour' => 1,
      ],
    ];
  }
  $url = $previous ? Url::fromUri('internal:' . $previous)
    ->toString() : Url::fromRoute('<front>', [], $params)
    ->toString();
  $url = $url instanceof GeneratedUrl ? $url
    ->getGeneratedUrl() : $url;
  $response = new RedirectResponse($url);
  $response
    ->send();
}

/**
 * Updates dashboard blocks with Drupal way machine names.
 */
function opigno_dashboard_blocks_update() {
  $blocks_ids = [
    'views_block:opigno_group_members-block_pending',
    'views_block:comments_recent-block_1',
    'views_block:content_recent-block_1',
    'views_block:latest_active_trainings-block',
    'views_block:opigno_calendar-month_block',
    'views_block:opigno_notifications-block_unread_dashboard',
    'views_block:opigno_score_modules-dashboard_notavaluated_modules',
    'views_block:private_message-block_dashboard',
    'views_block:who_s_new-block_1',
    'views_block:who_s_online-who_s_online_block',
  ];
  $config = \Drupal::configFactory();
  $block_service = new BlockService();
  $blocks = $block_service
    ->getAllBlocks();
  foreach ($blocks_ids as $id) {
    $old_id = $block_service
      ->sanitizeIdOld($id);
    $new_id = str_replace('-', '_', $old_id);
    if ($block_old = Block::load($old_id)) {
      try {
        $block_old
          ->delete();
      } catch (Exception $e) {
        \Drupal::logger('opigno_dashboard')
          ->error($e
          ->getMessage());
      }
    }
    if (!Block::load($new_id)) {
      $admin_label = $blocks[$id]['admin_label'];
      if (is_object($admin_label)) {
        $admin_label = $admin_label
          ->render();
      }
      $settings = [
        'plugin' => $id,
        'region' => 'content',
        'id' => $new_id,
        'theme' => $config
          ->get('system.theme')
          ->get('default'),
        'label' => t('Dashboard:') . ' ' . $admin_label,
        'visibility' => [
          'request_path' => [
            'id' => 'request_path',
            'pages' => '<front>',
            'negate' => FALSE,
            'context_mapping' => [],
          ],
        ],
        'weight' => 0,
      ];
      $values = [];
      foreach ([
        'region',
        'id',
        'theme',
        'plugin',
        'weight',
        'visibility',
      ] as $key) {
        $values[$key] = $settings[$key];

        // Remove extra values that do not belong in the settings array.
        unset($settings[$key]);
      }
      foreach ($values['visibility'] as $id => $visibility) {
        $values['visibility'][$id]['id'] = $id;
      }
      $values['settings'] = $settings;
      $block_new = Block::create($values);
      try {
        $block_new
          ->save();
      } catch (Exception $e) {
        \Drupal::logger('opigno_dashboard')
          ->error($e
          ->getMessage());
      }
    }
  }
  drupal_flush_all_caches();
}

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

/**
 * Remove a block from dashboard config after the block deletion.
 *
 * Implements hook_entity_delete().
 */
function opigno_dashboard_entity_delete(EntityInterface $entity) {
  if ($entity
    ->getEntityTypeId() == 'block') {

    // The block was deleted, need to remove it from dashboard config.
    $config = \Drupal::configFactory()
      ->getEditable('opigno_dashboard.settings');
    if ($blocks = $config
      ->get('blocks')) {
      $key = $entity
        ->getPluginId();
      if (key_exists($key, $blocks)) {
        unset($blocks[$key]);
        $config
          ->set('blocks', $blocks);
        try {
          $config
            ->save();
        } catch (\Exception $e) {
          \Drupal::logger('opigno_dashboard')
            ->error($e
            ->getMessage());
          \Drupal::messenger()
            ->addMessage($e
            ->getMessage(), 'error');
        }
      }
    }
  }
}

Functions

Namesort descending Description
opigno_dashboard_blocks_update Updates dashboard blocks with Drupal way machine names.
opigno_dashboard_entity_delete Remove a block from dashboard config after the block deletion.
opigno_dashboard_form_user_login_form_alter Implements hook_form_FORM_ID_alter().
opigno_dashboard_help Implements hook_help().
opigno_dashboard_page_attachments Implements hook_page_attachments().
opigno_dashboard_preprocess_page_title Implements hook_preprocess_page_title().
opigno_dashboard_preprocess_region Implements hook_preprocess_region().
opigno_dashboard_theme Implements hook_theme().
opigno_dashboard_theme_suggestions_alter Implements hook_theme_suggestions_alter().
opigno_dashboard_user_login Implements hook_user_login().

Constants