<?php

/**
 * @file
 * Control where users are directed to, once they login
 */

// Page constants.
define('LOGIN_DESTINATION_REDIRECT_NOTLISTED', 0);
define('LOGIN_DESTINATION_REDIRECT_LISTED', 1);
define('LOGIN_DESTINATION_REDIRECT_PHP', 2);

// Destination constants.
define('LOGIN_DESTINATION_STATIC', 0);
define('LOGIN_DESTINATION_SNIPPET', 1);

/**
 * Implements hook_help().
 */
function login_destination_help($path, $arg) {
  switch ($path) {
    case 'admin/help#login_destination':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Login Destination module allows you to customize the destination that the user is redirected to after logging in, registering to the site, using a one-time login link or logging out. The destination can be an internal page or an external URL. You may specify certain conditions like pages or user roles and make the destination depend upon them. You may also use a PHP snippets to provide custom conditions and destinations. Note that PHP Filter module has to be enabled and you have to be granted the "Use PHP for settings" permissions to be able to enter PHP code.') . '</p>';
      return $output;

    case 'admin/config/people/login-destination':
      return '<p>' . t('Login destination rules are evaluated each time a user logs in, registers to the site, uses a one-time login link or logs out. Each rule consists of the destination, path conditions and user roles conditions. First matching rule gets executed.') . '</p>';
  }
}

/**
 * Implements hook_menu().
 */
function login_destination_menu() {
  $items['admin/config/people/login-destination'] = array(
    'title' => 'Login destinations',
    'description' => 'Customize the destination that the user is redirected to after login.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('login_destination_overview_form'),
    'access arguments' => array('administer users'),
    'file' => 'login_destination.admin.inc',
    'weight' => 10,
  );
  $items['admin/config/people/login-destination/add'] = array(
    'title' => 'Add login destination rule',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('login_destination_edit_form'),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_ACTION,
    'weight' => 1,
    'file' => 'login_destination.admin.inc',
  );
  $items['admin/config/people/login-destination/edit/%login_destination'] = array(
    'title' => 'Edit login destination rule',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('login_destination_edit_form', 5),
    'access arguments' => array('administer users'),
    'file' => 'login_destination.admin.inc',
  );
  $items['admin/config/people/login-destination/delete/%login_destination'] = array(
    'title' => 'Delete login destination rule',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('login_destination_delete_form', 5),
    'access arguments' => array('administer users'),
    'file' => 'login_destination.admin.inc',
  );
  $items['admin/config/people/login-destination/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/config/people/login-destination/settings'] = array(
    'title' => 'Settings',
    'description' => 'Change Login Destination settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('login_destination_settings'),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'login_destination.admin.inc',
    'weight' => 10,
  );

  return $items;
}

/**
 * Load a login destination.
 */
function login_destination_load($id) {
  $result = db_select('login_destination', 'l')
    ->fields('l')
    ->condition('id', $id)
    ->execute()
    ->fetchAssoc();

  $result['triggers'] = unserialize($result['triggers']);
  if (empty($result['triggers'])) {
    $result['triggers'] = array();
  }

  $result['roles'] = unserialize($result['roles']);
  if (empty($result['roles'])) {
    $result['roles'] = array();
  }

  return $result;
}

/**
 * Implements hook_theme().
 */
function login_destination_theme() {
  return array(
    'login_destination_destination' => array(
      'variables' => array('destination' => NULL),
      'file' => 'login_destination.admin.inc',
    ),
    'login_destination_pages' => array(
      'variables' => array('pages' => NULL, 'pages_type' => 0),
      'file' => 'login_destination.admin.inc',
    ),
    'login_destination_triggers' => array(
      'variables' => array('items' => NULL),
      'file' => 'login_destination.admin.inc',
    ),
    'login_destination_roles' => array(
      'variables' => array('items' => NULL),
      'file' => 'login_destination.admin.inc',
    ),
    'login_destination_overview_form' => array(
      'file' => 'login_destination.admin.inc',
      'render element' => 'form',
    ),
  );
}

/**
 * Implements hook_form_alter().
 */
function login_destination_form_alter(&$form, &$form_state, $form_id) {
  // We redirect by using the drupal_goto_alter hook. If we simply
  // call drupal_goto() it may break compability with other modules. If we set
  // the $_GET['destination'] variable we will loose the possibility to redirect
  // to an external URL.

  // Please note the the system_goto_action() calls drupal_goto()
  // More on this issue http://drupal.org/node/732542.

  // If we add the $form_state['redirect'] here it will be overriden by the
  // user_login_submit(). So we add a submit handler instead and will set the
  // redirect later. Our submit handler will be executed after the execution
  // of user_login_submit(). This is because form_submit() functions are
  // appended to form before hook_form_alter() is executed.

  // We will execute also after LoginToboggan's function as it replaces the
  // original submit function from user module.

  switch ($form_id) {
    // User register page and user login page.
    case 'user_register_form':
    case 'user_login':
      $form['#validate'][] = 'login_destination_validate';
      break;
  }

  switch ($form_id) {
    // One-time login, password reset.
    case 'user_profile_form':
      if (isset($_GET['pass-reset-token'])) {
        // Redirect only from user_pass_reset
        // You have to explicitally turn on the option to always redirect from
        // the profile page. This is for constistency.
        $form['#submit'][] = 'login_destination_submit';
        break;
      }
  }
}

/**
 * Helper submit function.
 */
function login_destination_validate($form, &$form_state) {
  // LoginToboggan's unified page is rendered dynamically. Fix it.
  switch ($form['#form_id']) {
    case 'user_register_form':
      if (drupal_match_path($_GET['q'], 'user')) {
        $_GET['q'] = 'user/register';
      }
      break;

    case 'user_login':
      if (drupal_match_path($_GET['q'], 'user/register')) {
        $_GET['q'] = 'user';
      }
      break;
  }

  // Fix the current page in case of 403 page.
  if ($form['#form_id'] == 'user_login') {
    if (drupal_get_http_header('Status') == '403 Forbidden') {
      $_GET['current'] = $_GET['destination'];
    }
  }

}

/**
 * Helper submit function.
 */
function login_destination_submit($form, &$form_state) {
  login_destination_perform_redirect('login');
}

/**
 * Implements hook_menu_link_alter().
 */
function login_destination_menu_link_alter(&$item) {
  // Flag a link to be altered by hook_translated_menu_link_alter().
  // This is called only on menu rebuild, so we have to add this information
  // manually to the database on install. Clearing caches also helps.
  $paths = array('user/logout', 'user/login', 'user');
  if (in_array($item['link_path'], $paths)) {
    $item['options']['alter'] = TRUE;
  }
}

/**
 * Implements hook_translated_menu_link_alter().
 */
function login_destination_translated_menu_link_alter(&$item, $map) {
  global $user;
  $paths = array('user/login', 'user');
  // Append the current path to URL.
  if ($item['link_path'] == 'user/logout' || (in_array($item['link_path'], $paths) && user_is_anonymous())) {
    $item['localized_options']['query'] = array('current' => $_GET['q']);
  }
}

/**
 * Implements hook_page_alter().
 */
function login_destination_page_alter(&$page) {
  // Substitute toolbar's pre_render function to change links.
  if (isset($page['page_top']['toolbar']['#pre_render'])) {
    $page['page_top']['toolbar']['#pre_render'][0] = 'login_destination_toolbar_pre_render';
  }
}

/**
 * Helper function to change toolbar's links.
 */
function login_destination_toolbar_pre_render($toolbar) {
  $toolbar = toolbar_pre_render($toolbar);
  // Add current param to be able to evaluate previous page.
  $toolbar['toolbar_user']['#links']['logout']['query'] = array('current' => $_GET['q']);
  return $toolbar;
}

/**
 * Implements hook_user_login().
 */
function login_destination_user_login(&$edit, $account) {
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset' || variable_get('login_destination_immediate_redirect', FALSE)) {
    login_destination_perform_redirect('login');
  }
}

/**
 * Implements hook_user_insert().
 */
function login_destination_user_insert(&$edit, $account, $category) {
  global $user;

  if (!$user->uid) {
    // If the user is already logged in, it means probably that they create a
    // user account and not the user registers themselves.
    login_destination_perform_redirect('login');
  }
}

/**
 * Implements hook_user_logout().
 */
function login_destination_user_logout($account) {
  login_destination_perform_redirect('logout', _login_destination_get_current('logout'));
}

/**
 * Implements hook_drupal_goto_alter().
 */
function login_destination_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  // Note that this functionality cannot be backported do 6.x as Drupal 6 does
  // not call drupal_alter for drupal_goto.

  // This actually may be used also by templates.
  if (isset($GLOBALS['destination'])) {
    $destination = $GLOBALS['destination'];

    // Alter drupal_goto.
    if (is_array($destination)) {
      $path = $destination[0];
      $options = array();
      if (count($destination) > 1) {
        $options = $destination[1];
      }
    }
    else {
      $path = $destination;
    }
  }
}

/**
 * Pass destination to drupal_goto.
 */
function login_destination_prepare_goto($destination) {
  // Check if $_GET['destination'] should overwrite us.
  if (!isset($_GET['destination']) || !variable_get('login_destination_preserve_destination', FALSE)) {
    $GLOBALS['destination'] = $destination;
  }
}

/**
 * Evaluate rules and perform redirect.
 *
 * This function is intended to be used by external modules.
 *
 * @param string $trigger
 *   Action of login destination rule.
 * @param string $current
 *   Path, if null $_GET['q'] is used.
 */
function login_destination_perform_redirect($trigger = '', $current = NULL) {
  $destination = login_destination_get_destination($trigger, $current);

  // Check if we redirect.
  if ($destination !== FALSE) {
    login_destination_prepare_goto($destination);
  }
}

/**
 * Process all destination rules and return destination path.
 *
 * This function is intended to be used by external modules.
 */
function login_destination_get_destination($trigger = '', $current = NULL) {
  // Get all the login destination rules from the database.
  $result = db_select('login_destination', 'l')
    ->fields('l', array(
      'triggers',
      'roles',
      'pages_type',
      'pages',
      'destination_type',
      'destination',
      'enabled',
      )
    )
    ->orderBy('weight')
    ->execute()
    ->fetchAll();

  if ($current == NULL) {
    $current = $_GET['q'];
  }

  // Examine path matches.
  foreach ($result as $data) {
    // Try to match the subsequent rule.
    if (_login_destination_match_rule($data, $trigger, $current)) {
      // Note: Matching rule with empty destination will cancel redirect.
      return _login_destination_evaluate_rule($data, $trigger);
    }
  }

  // No rule matched.
  return FALSE;
}

/**
 * Evaluate the code with forms context.
 *
 * This function hides the calling function's scope from eval().
 */
function _login_destination_eval($code) {
  // We could use the php_eval(), but would not be able get array return value.
  // We always check for the existance of PHP Filter module for security.
  return eval('?>' . $code);
}

/**
 * A helper function to provide role options.
 */
function _login_destination_role_options() {
  // User role selection, without anonymous user roles.
  $role_options = array_map('check_plain', user_roles(TRUE));
  return $role_options;
}

/**
 * Get the current path (before trigger was invoked).
 */
function _login_destination_get_current($trigger = '') {
  if (isset($_GET['current'])) {
    return check_plain($_GET['current']);
  }

  if ($trigger == 'login') {
    return $_GET['q'];
  }

  // Front by default.
  return '';
}

/**
 * A helper function to determine whether redirection should happen.
 *
 * @return bool
 *   TRUE - apply redirect, FALSE - not to apply redirect.
 */
function _login_destination_match_rule($rule, $trigger = '', $current = NULL) {
  global $user;

  // Check rule is enabled or not.
  if ($rule->enabled == 0) {
    return FALSE;
  }

  $type = $rule->pages_type;
  $pages = $rule->pages;

  $triggers = unserialize($rule->triggers);
  if (empty($triggers)) {
    $triggers = array();
  }

  $roles = unserialize($rule->roles);
  if (empty($roles)) {
    $roles = array();
  }

  // Remove non-existent roles.
  $roles = array_intersect_key(_login_destination_role_options(), $roles);

  // Examine trigger match.
  if (!(empty($triggers) || array_key_exists($trigger, $triggers))) {
    return FALSE;
  }

  // Examine role matches.
  $roles_intersect = array_intersect_key($roles, $user->roles);

  if (!empty($roles) && empty($roles_intersect)) {
    return FALSE;
  }

  if ($type < LOGIN_DESTINATION_REDIRECT_PHP) {
    $pages = drupal_strtolower($pages);
    $alias = drupal_strtolower(drupal_get_path_alias($current));

    $page_match = drupal_match_path($alias, $pages);

    if ($alias != $current) {
      $page_match = $page_match || drupal_match_path($current, $pages);
    }
    $page_match = !($type xor $page_match);
  }
  elseif (module_exists('php')) {
    // Do not execute php if the PHP Filter is off.
    $page_match = _login_destination_eval($pages);
  }
  else {
    $page_match = FALSE;
  }

  return $page_match;
}

/**
 * A helper function to evaluate destination path.
 */
function _login_destination_evaluate_rule($rule, $trigger = '') {
  if ($rule->destination_type == LOGIN_DESTINATION_STATIC) {
    // Take only 1st line.
    if (preg_match("!^(.*?)$!", $rule->destination, $matches) === 1) {
      $path = $matches[1];

      if (empty($path)) {
        return FALSE;
      }
      // Current path.
      elseif ($path == '<current>') {
        return _login_destination_get_current($trigger);
      }
      // External URL.
      elseif (strpos($path, '://') !== FALSE) {
        return $path;
      }
      // Internal URL.
      else {
        $destination = drupal_parse_url($path);
        $options = array();
        $options['query'] = $destination['query'];
        $options['fragment'] = $destination['fragment'];

        // Drupal api, drupal_goto cares about <front>.
        return array($destination['path'], $options);
      }
    }
    else {
      // Error - multiple lines.
      return '';
    }
  }
  elseif (module_exists('php')) {
    // We cannot use the php_eval because we expect array here, but for the
    // matter of consistent UI we don't do it with the PHP Filter module off.
    $result = _login_destination_eval($rule->destination);

    if (empty($result)) {
      return FALSE;
    }
    return $result;
  }
  else {
    // PHP code and PHP filter disabled.
    return FALSE;
  }
}
