MaintenanceModeSubscriber.php 2.64 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
<?php

/**
 * @file
 * Contains \Drupal\user\EventSubscriber\MaintenanceModeSubscriber.
 */

namespace Drupal\user\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Maintenance mode subscriber to logout users.
 */
class MaintenanceModeSubscriber implements EventSubscriberInterface {

  /**
   * Determine whether the page is configured to be offline.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The event to process.
   */
  public function onKernelRequestMaintenance(GetResponseEvent $event) {
27
    $user = \Drupal::currentUser();
28 29
    $request = $event->getRequest();
    $site_status = $request->attributes->get('_maintenance');
30
    $path = $request->attributes->get('_system_path');
31 32
    if ($site_status == MENU_SITE_OFFLINE) {
      // If the site is offline, log out unprivileged users.
33
      if ($user->isAuthenticated() && !$user->hasPermission('access site in maintenance mode')) {
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
        user_logout();
        // Redirect to homepage.
        $event->setResponse(new RedirectResponse(url('<front>', array('absolute' => TRUE))));
        return;
      }

      if (user_is_anonymous()) {
        switch ($path) {
          case 'user':
            // Forward anonymous user to login page.
            $event->setResponse(new RedirectResponse(url('user/login', array('absolute' => TRUE))));
            return;
          case 'user/login':
          case 'user/password':
            // Disable offline mode.
            $request->attributes->set('_maintenance', MENU_SITE_ONLINE);
            break;
          default:
            if (strpos($path, 'user/reset/') === 0) {
              // Disable offline mode.
              $request->attributes->set('_maintenance', MENU_SITE_ONLINE);
            }
            break;
        }
      }
    }
60
    if ($user->isAuthenticated()) {
61 62 63 64 65 66 67
      if ($path == 'user/login') {
        // If user is logged in, redirect to 'user' instead of giving 403.
        $event->setResponse(new RedirectResponse(url('user', array('absolute' => TRUE))));
        return;
      }
      if ($path == 'user/register') {
        // Authenticated user should be redirected to user edit page.
68
        $event->setResponse(new RedirectResponse(url('user/' . $user->id() . '/edit', array('absolute' => TRUE))));
69 70 71 72 73 74 75 76 77 78 79 80 81 82
        return;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('onKernelRequestMaintenance', 35);
    return $events;
  }

}