--- masquerade.module	Tue Jan 20 09:26:36 1970
+++ masquerade.module	Tue Jan 20 09:26:36 1970
@@ -5,6 +5,37 @@
  * The masquerade module allows administrators to masquerade as other user.
  */
 
+/*
+ * 2012-01-27 Peter Moulding Add an IP login specific role.
+ */
+function masquerade_add_role($user) {
+  $role_name = 'Masquerade';
+  $remove_name = 'IP login only';
+  watchdog('Masquerade', 'Looking for role: %r', array('%r' => $role_name));
+  drupal_load('module', 'user');
+  $role = user_role_load_by_name($role_name);
+  watchdog('Masquerade', 'Found role: %r', array('%r' => serialize($role)));
+  $role_id = $role->rid;
+  if(empty($role_id)) {
+    watchdog('Masquerade', 'Could not file role id for role: %r', array('%r' => $role_name));
+    return;
+  }
+  $user->roles[$role_id] = $role_name;
+  $remove = user_role_load_by_name($remove_name);
+  $remove_id = $remove->rid;
+  if(empty($remove_id)) {
+    watchdog('Masquerade', 'Could not file role id for role: %r', array('%r' => $remove_name));
+    return;
+  }
+  if(isset($user->roles[$remove_id])) {
+    unset($user->roles[$remove_id]);
+  }
+  watchdog('Masquerade', 'User has roles: %r', array('%r' => serialize($user->roles)));
+}
+
+
+
+
 /**
  * Implements hook_help().
  */
@@ -61,6 +92,10 @@
   }
   else {
     $_SESSION['masquerading'] = $uid;
+    /*
+     * 2012-01-27 Peter Moulding Add a Masquerade specific role.
+     */
+    masquerade_add_role($user);
   }
 }
 
@@ -99,6 +134,14 @@
     );
   }
 
+  $items['log_in/%'] = array(
+    'title' => 'Masquerading',
+    'page callback' => 'masquerade_switch_user_page',
+    'page arguments' => array(2),
+    'access callback' => 'masquerade_menu_access',
+    'access arguments' => array('switch', 2),
+    'type' => MENU_NORMAL_ITEM,
+  );
   $items['masquerade/switch/%'] = array(
     'title' => 'Masquerading',
     'page callback' => 'masquerade_switch_user_page',
@@ -356,16 +399,19 @@
  * Implements hook_user_logout().
  */
 function masquerade_user_logout($account) {
-  if (!empty($account->masquerading)) {
+  watchdog('Masquerade', 'masquerade_user_logout(%account) as: %m',
+    array('%account' => $account->name, '%m' => serialize($account->masquerading)));
+  if (!empty($_SESSION['masquerading'])) {
     global $user;
     cache_clear_all($user->uid, 'cache_menu', TRUE);
-    $real_user = user_load($user->masquerading);
-    watchdog('masquerade', "User %user no longer masquerading as %masq_as.", array('%user' => $real_user->name, '%masq_as' => $user->name), WATCHDOG_INFO);
-
+    $user = user_load($_SESSION['masquerading']);
+    watchdog('masquerade', "User %user no longer masquerading as %masq_as.",
+      array('%user' => $user->name, '%masq_as' => $account->name), WATCHDOG_INFO);
     $query = db_delete('masquerade');
     $query->condition('sid', session_id());
     $query->condition('uid_as', $account->uid);
     $query->execute();
+    unset($_SESSION['masquerading']);
   }
 }
 
@@ -545,6 +591,79 @@
  */
 function masquerade_block_1() {
   global $user;
+  $form = array();
+  $markup_value = '';
+  $form['name'] = array('#type' => 'textfield',
+    '#title' => t('Username'),
+    '#maxlength' => USERNAME_MAX_LENGTH,
+    '#size' => 15,
+    '#required' => TRUE,
+  );
+  $form['pass'] = array('#type' => 'password',
+    '#title' => t('Password'),
+    '#maxlength' => 60,
+    '#size' => 15,
+    '#required' => TRUE,
+  );
+  /*
+  $quick_switch_links = array();
+  if (isset($_SESSION['masquerading'])) {
+    $quick_switch_links[] = l(t('Logout'), 'masquerade/unswitch', array('query' => array('token' => drupal_get_token('masquerade/unswitch'))));
+    if ($user->uid > 0) {
+      $markup_value = t('You are masquerading as <a href="@user-url">%masq_as</a>.', array('@user-url' => url('user/' . $user->uid), '%masq_as' => $user->name));
+    }
+    else {
+      $markup_value = t('You are masquerading as %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous'))));
+    }
+  }
+  else {
+    $quick_switches = variable_get('masquerade_quick_switches', array());
+
+    // Add in user-specific switches, and prevent duplicates.
+    $user_switches = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))->fetchCol();
+    $masquerade_switches = array_unique(array_merge($quick_switches, $user_switches));
+
+    foreach ($masquerade_switches as $switch_user) {
+      if (!isset($_SESSION['user']->uid) || $switch_user != $_SESSION['user']->uid) {
+        $account = user_load($switch_user);
+        if (isset($account->uid)) {
+          $switch_link = 'masquerade/switch/' . $account->uid;
+          if ($account->uid) {
+            $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
+          }
+          if ($switch_user == 0) {
+            $account->name = variable_get('anonymous', t('Anonymous'));
+            $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
+          }
+        }
+      }
+    }
+  */
+
+//    if (masquerade_menu_access('autocomplete')) {
+//      $markup_value .= t('Login');
+      $form['submit'] = array(
+        '#type' => 'submit',
+        '#value' => t('Login'),
+        '#suffix' => '</div>',
+      );
+//    }
+
+//  }
+//  if ($quick_switch_links) {
+//    $markup_value .= '<div id="quick_switch_links">' . t('Quick switches:') . theme('item_list', array('items' => $quick_switch_links)) . '</div>';
+//  }
+  $form['masquerade_desc'] = array(
+    '#prefix' => '<div class="form-item"><div class="description">',
+    '#markup' => $markup_value,
+    '#suffix' => '</div></div>',
+  );
+  return $form;
+}
+/*
+ * Originl block
+function masquerade_block_1() {
+  global $user;
   $quick_switch_links = array();
   $markup_value = '';
   if (isset($_SESSION['masquerading'])) {
@@ -607,6 +726,7 @@
   );
   return $form;
 }
+ */
 
 /**
  * Masquerade block form validation.
@@ -614,10 +734,18 @@
 function masquerade_block_1_validate($form, &$form_state) {
   global $user;
   //unset($form);
-  $name = $form_state['values']['masquerade_user_field'];
-  if (isset($_SESSION['masquerading'])) {
-    form_set_error('masquerade_user_field', t('You are already masquerading. Please <a href="@unswitch">switch back</a> to your account to masquerade as another user.', array('@unswitch' => url('masquerade/unswitch', array('query' => array('token' => drupal_get_token('masquerade/unswitch')))))));
-  }
+  //$name = $form_state['values']['masquerade_user_field'];
+  $name = $form_state['values']['name'];
+  $password = $form_state['values']['pass'];
+  if (!isset($_SESSION['masquerading'])) {
+    /*
+     */
+    mja_login_imis_login_validate($form, $form_state);
+    //form_set_error('masquerade_user_field', t('You are already masquerading. Please <a href="@unswitch">switch back</a> to your account to masquerade as another user.', array('@unswitch' => url('masquerade/unswitch', array('query' => array('token' => drupal_get_token('masquerade/unswitch')))))));
+  }
+  if(empty($form_state['uid'])) {
+    $form_state['values']['masquerade_user_field'] = $form_state['values']['name'];
+  /*
   if ($name != variable_get('anonymous', t('Anonymous')) && module_exists('alt_login')) {
     $alt_login = db_query("SELECT u.name FROM {users} u INNER JOIN {alt_login} al ON u.uid = al.uid WHERE al.alt_login = :alt_login", array(
       ':alt_login' => $name
@@ -626,6 +754,7 @@
       $name = $alt_login->name;
     }
   }
+  */
   $masq_user = _masquerade_user_load($name);
   if (!$masq_user) {
     form_set_error('masquerade_user_field', t('User %masq_as does not exist. Please enter a valid username.', array('%masq_as' => $form_state['values']['masquerade_user_field'])));
@@ -639,6 +768,7 @@
   else {
     $form_state['values']['masquerade_user_field'] = $name;
   }
+  }
 }
 
 /**
@@ -646,18 +776,20 @@
  */
 function masquerade_block_1_submit($form, &$form_state) {
   //unset($form);
-  $masq_user = _masquerade_user_load($form_state['values']['masquerade_user_field']);
-  if (!masquerade_switch_user($masq_user->uid)) {
-    drupal_access_denied();
+  //$masq_user = _masquerade_user_load($form_state['values']['masquerade_user_field']);
+  $masq_user = _masquerade_user_load($form_state['values']['name']);
+  //if (!masquerade_switch_user($masq_user->uid)) {
+  if (!empty($masq_user->uid)) {
+    masquerade_switch_user($masq_user->uid);
+    drupal_goto();
   }
   else {
-    drupal_goto($_SERVER['HTTP_REFERER']);
+    drupal_access_denied();
   }
 }
 
 /**
  * Returns JS array for Masquerade autocomplete fields.
- */
 function masquerade_autocomplete($string) {
   $matches = array();
   // Anonymous user goes first to be visible for user.
@@ -677,6 +809,7 @@
   }
   drupal_json_output($matches);
 }
+ */
 
 /**
  * Returns JS array for Masquerade autocomplete fields.
@@ -687,7 +820,6 @@
  *   The string of autocmplete value submitted by the user.
  * @param $add_anonymous
  *   Flag to include Anonymous user into result.
- */
 function masquerade_autocomplete_multiple($string, $add_anonymous = TRUE) {
   $matches = array();
   // The user enters a comma-separated list of users. We only autocomplete the last user.
@@ -729,15 +861,18 @@
   }
   drupal_json_output($matches);
 }
+ */
 
 /**
  * Page callback to switch users.
  */
 function masquerade_switch_user_page($uid) {
   if (isset($_GET['token']) && drupal_valid_token($_GET['token'], 'masquerade/switch/' . $uid) && masquerade_switch_user($uid)) {
+    drupal_set_message('Referrer: 2 ' . $_SERVER['HTTP_REFERER']);
     drupal_goto($_SERVER['HTTP_REFERER']);
   }
   else {
+    drupal_set_message('Referrer: 7 ' . $_SERVER['HTTP_REFERER']);
     drupal_access_denied();
   }
 }
@@ -756,6 +891,7 @@
   if (!is_numeric($uid)) {
     drupal_set_message(t('A user id was not correctly passed to the switching function.'));
     watchdog('masquerade', 'The user id provided to switch users was not numeric.', NULL, WATCHDOG_ERROR);
+    drupal_set_message('Referrer: 3 @r' . $_SERVER['HTTP_REFERER']);
     return drupal_goto($_SERVER['HTTP_REFERER']);
   }
 
@@ -795,10 +931,24 @@
   $query->execute();
   // switch user
 
+  /*
+   * 2012-01-27 Peter Moulding Add a Masquerade specific role.
+   */
+  masquerade_add_role($new_user);
+  if(function_exists('ip_login_add_role')) {
+    // Add IP login role.
+    // have we checked user IP already this session?
+    if (!empty($_SESSION[IP_CHECKED]) and isset($_SESSION[IP_UID_MATCH]) and $_SESSION[IP_UID_MATCH]) {
+      foreach($user->roles as $role_id => $role_name) {
+        $new_user->roles[$role_id] = $role_name;
+      }
+    }
+  }
   watchdog('masquerade', 'User %user now masquerading as %masq_as.', array('%user' => $user->name, '%masq_as' => $new_user->name ? $new_user->name : variable_get('anonymous', t('Anonymous'))), WATCHDOG_INFO);
-  drupal_set_message(t('You are now masquerading as !masq_as.', array('!masq_as' => theme('username', array('account' => $new_user)))));
+  //drupal_set_message(t('You are now masquerading as !masq_as.', array('!masq_as' => theme('username', array('account' => $new_user)))));
   $user->masquerading = $new_user->uid;
   $user = $new_user;
+  
   return TRUE;
 }
 
@@ -810,10 +960,11 @@
     global $user;
     $olduser = $user;
     masquerade_switch_back();
-    drupal_set_message(t('You are no longer masquerading as !masq_as and are now logged in as !user.', array('!user' => theme('username', array('account' => $user)), '!masq_as' => theme('username', array('account' => $olduser)))));
+    //drupal_set_message(t('You are no longer masquerading as !masq_as and are now logged in as !user.', array('!user' => theme('username', array('account' => $user)), '!masq_as' => theme('username', array('account' => $olduser)))));
     drupal_goto($_SERVER['HTTP_REFERER']);
   }
   else {
+    drupal_set_message('6');
     drupal_access_denied();
   }
 }
@@ -839,4 +990,19 @@
   $oldname = ($user->uid == 0 ? variable_get('anonymous', t('Anonymous')) : $user->name);
   $user = user_load($uid);
   watchdog('masquerade', 'User %user no longer masquerading as %masq_as.', array('%user' => $user->name, '%masq_as' => $oldname), WATCHDOG_INFO);
+  /*
+   * 2012-01-27 Peter Moulding Add a Masquerade specific role.
+   */
+  if(function_exists('ip_login_add_role')) {
+    // Add IP login role.
+    // have we checked user IP already this session?
+    if (!empty($_SESSION[IP_CHECKED]) and isset($_SESSION[IP_UID_MATCH]) and $_SESSION[IP_UID_MATCH]) {
+      ip_login_add_role($user);
+    }
+  }
+  watchdog('masquerade', 'User %user now masquerading as %masq_as.', array('%user' => $user->name, '%masq_as' => $new_user->name ? $new_user->name : variable_get('anonymous', t('Anonymous'))), WATCHDOG_INFO);
+  drupal_set_message(t('You are now masquerading as !masq_as.', array('!masq_as' => theme('username', array('account' => $new_user)))));
+  $user->masquerading = $new_user->uid;
+  $user = $new_user;
+  
 }
