masquerade.module

Tracking 6.x-1.x branch
  1. drupal
    1. 6 contributions/masquerade/masquerade.module

masquerade.module

The masquerade module allows administrators to masquerade as other user.

Functions & methods

NameDescription
masquerade_accessDetermine if the current user has permission to switch users.
masquerade_admin_settings
masquerade_admin_settings_submit
masquerade_admin_settings_validate
masquerade_autocompleteReturns JS array for Masquerade autocomplete fields.
masquerade_autocomplete_multipleReturns JS array for Masquerade autocomplete fields. Supports multiple entries separated by a comma.
masquerade_autocomplete_userReplacement function for user_autocomplete which allows the use of a comma separated list of user names.
masquerade_blockImplementation of hook_block().
masquerade_block_1Masquerade block form.
masquerade_block_1_submitMasquerade block form submission.
masquerade_block_1_validateMasquerade block form validation.
masquerade_cronImplementation of hook_cron()
masquerade_helpImplementation of hook_help().
masquerade_initImplementation of hook_init().
masquerade_menuImplementation of hook_menu().
masquerade_menu_alterImplementation of hook_menu_alter().
masquerade_permImplementation of hook_perm().
masquerade_switch_backFunction for a masquerading user to switch back to the previous user.
masquerade_switch_back_pagePage callback that allows a user who is currently masquerading to become a new user.
masquerade_switch_userFunction that allows a user with the right permissions to become the selected user.
masquerade_switch_user_pagePage callback to switch users.
masquerade_translated_menu_link_alterImplementation of hook_translated_menu_link_alter().
masquerade_userImplementation of hook_user().
_masquerade_user_loadWrapper around user_load() to allow the loading of anonymous users.

File

View source
  1. <?php
  2. /**
  3. * @file masquerade.module
  4. *
  5. * The masquerade module allows administrators to masquerade as other user.
  6. */
  7. /**
  8. * Implementation of hook_help().
  9. */
  10. function masquerade_help($path, $arg) {
  11. switch ($path) {
  12. case 'admin/help#masquerade':
  13. return t('<p>The masquerade module adds a link on a user\'s profile page that allows permitted users to masquerade as that user. Upon masquerading, a link to "switch back" to the original user will appear in the menu. While masquerading, the option to masquerade as another user will not appear. All masquerading transactions are logged, and $user->masquerading will be set; this could be displayed via theme.</p><p>In the masquerade settings a list of roles are presented; any checked role is considered an "administrator" and requires the second level "masquerade as admin" permission to masquerade as. User #1 is automatically considered an administrator, regardless of roles.</p>');
  14. case 'admin/settings/masquerade':
  15. return t('Only the users with <strong>masquerade as admin</strong> permission, will be able to masquerade as the users who belong to the roles selected below. User #1 is automatically considered an administrator, regardless of roles.');
  16. }
  17. }
  18. /**
  19. * Implementation of hook_perm().
  20. *
  21. * @return array
  22. */
  23. function masquerade_perm() {
  24. return array('masquerade as user', 'masquerade as admin', 'administer masquerade');
  25. }
  26. /**
  27. * Implementation of hook_init().
  28. */
  29. function masquerade_init() {
  30. global $user;
  31. // Try to load masqing uid from masquerade table.
  32. $uid = db_result(db_query("SELECT uid_from FROM {masquerade} WHERE sid = '%s' AND uid_as = %d", session_id(), $user->uid));
  33. // We are using identical operator (===) instead of equal (==) because if
  34. // $uid === 0 we want to store the session variable. If there's no record in
  35. // masquerade table we clear the session variable.
  36. if ($uid === FALSE) {
  37. if (isset($_SESSION)) {
  38. unset($_SESSION['masquerading']);
  39. }
  40. }
  41. else {
  42. $_SESSION['masquerading'] = $uid;
  43. }
  44. }
  45. /**
  46. * Implementation of hook_cron()
  47. *
  48. * Cleanup masquerade records where people didn't use the switch back link
  49. * that would have cleanly removed the user switch record.
  50. */
  51. function masquerade_cron() {
  52. // see http://drupal.org/node/268487 before modifying this query
  53. db_query('DELETE FROM {masquerade} WHERE sid NOT IN (SELECT s.sid FROM {sessions} AS s)');
  54. }
  55. /**
  56. * Implementation of hook_menu().
  57. */
  58. function masquerade_menu() {
  59. $items = array();
  60. $default_test_user = _masquerade_user_load(variable_get('masquerade_test_user', ''));
  61. if ($default_test_user && ($default_test_user->uid || $default_test_user->name == variable_get('anonymous', t('Anonymous')))) {
  62. $items['masquerade/switch/' . $default_test_user->uid] = array(
  63. 'title' => 'Masquerade as @testuser',
  64. 'title arguments' => array('@testuser' => $default_test_user->name),
  65. 'page callback' => 'masquerade_switch_user_page',
  66. 'page arguments' => array(2),
  67. 'access callback' => 'masquerade_access',
  68. 'access arguments' => array('switch'),
  69. 'type' => MENU_NORMAL_ITEM,
  70. );
  71. }
  72. $items['masquerade/switch/%'] = array(
  73. 'title' => 'Masquerading',
  74. 'page callback' => 'masquerade_switch_user_page',
  75. 'page arguments' => array(2),
  76. 'access callback' => 'masquerade_access',
  77. 'access arguments' => array('switch', 2),
  78. 'type' => MENU_NORMAL_ITEM,
  79. );
  80. $items['masquerade/unswitch'] = array(
  81. 'title' => 'Switch back',
  82. 'page callback' => 'masquerade_switch_back_page',
  83. 'access callback' => 'masquerade_access',
  84. 'access arguments' => array('unswitch'),
  85. 'type' => MENU_NORMAL_ITEM,
  86. );
  87. $items['masquerade/autocomplete'] = array(
  88. 'title' => '',
  89. 'page callback' => 'masquerade_autocomplete',
  90. 'access callback' => 'masquerade_access',
  91. 'access arguments' => array('autocomplete'),
  92. 'type' => MENU_CALLBACK,
  93. );
  94. $items['masquerade/autocomplete/multiple'] = array(
  95. 'title' => '',
  96. 'page callback' => 'masquerade_autocomplete_multiple',
  97. 'access callback' => 'masquerade_access',
  98. 'access arguments' => array('autocomplete'),
  99. 'type' => MENU_CALLBACK,
  100. );
  101. $items['masquerade/autocomplete-user'] = array(
  102. 'title' => 'Masquerade autocomplete',
  103. 'page callback' => 'masquerade_autocomplete_user',
  104. 'access arguments' => array('access user profiles'),
  105. 'type' => MENU_CALLBACK,
  106. );
  107. $items['admin/settings/masquerade'] = array(
  108. 'title' => 'Masquerade',
  109. 'description' => 'Masquerade module allows administrators to masquerade as other users.',
  110. 'page callback' => 'drupal_get_form',
  111. 'page arguments' => array('masquerade_admin_settings'),
  112. 'access callback' => 'user_access',
  113. 'access arguments' => array('administer masquerade'),
  114. 'type' => MENU_NORMAL_ITEM,
  115. );
  116. return $items;
  117. }
  118. /**
  119. * Implementation of hook_menu_alter().
  120. *
  121. * We need to add a token to the Masquerade paths to protect against CSRF
  122. * attacks. Since menu items in Drupal do not support dynamic elements these
  123. * tokens need to be added during rendering via an implementation of
  124. * hook_translated_menu_link_alter. Set the 'alter'-option to TRUE to make sure
  125. * the links get passed through hook_translated_menu_link_alter.
  126. */
  127. function masquerade_menu_alter(&$items) {
  128. $items['masquerade/unswitch']['options']['alter'] = TRUE;
  129. $items['masquerade/switch/%']['options']['alter'] = TRUE;
  130. $default_test_user = _masquerade_user_load(variable_get('masquerade_test_user', ''));
  131. if (isset($default_test_user->uid)) {
  132. $items['masquerade/switch/' . $default_test_user->uid]['options']['alter'] = TRUE;
  133. }
  134. }
  135. /**
  136. * Implementation of hook_translated_menu_link_alter().
  137. *
  138. * Dynamically add the CSRF protection token to the Masquerade menu items.
  139. */
  140. function masquerade_translated_menu_link_alter(&$item, $map) {
  141. if (isset($item['page_callback'])) {
  142. if ($item['page_callback'] == 'masquerade_switch_user_page' && isset($map[2])) {
  143. $item['localized_options']['query']['token'] = drupal_get_token('masquerade/switch/' . $map[2]);
  144. }
  145. elseif ($item['page_callback'] == 'masquerade_switch_back_page') {
  146. $item['localized_options']['query']['token'] = drupal_get_token('masquerade/unswitch');
  147. }
  148. }
  149. }
  150. /**
  151. * Determine if the current user has permission to switch users.
  152. *
  153. * @param string $type
  154. * Either 'switch', 'unswitch', 'user', or 'autocomplete'.
  155. *
  156. * @param object $uid
  157. * An optional parameter indicating a specific uid to switch to.
  158. * Otherwise, return if the user can switch to any user account.
  159. *
  160. * @return
  161. * TRUE, if the user can perform the requested action, FALSE otherwise.
  162. */
  163. function masquerade_access($type, $uid = NULL) {
  164. switch ($type) {
  165. case 'unswitch':
  166. return isset($_SESSION['masquerading']) || arg(2) == 'menu-customize' || arg(2) == 'menu';
  167. case 'autocomplete':
  168. return isset($_SESSION['masquerading']) || (user_access('masquerade as user') || user_access('masquerade as admin'));
  169. break;
  170. case 'user':
  171. global $user;
  172. return db_result(db_query("SELECT TRUE FROM {masquerade_users} WHERE uid_from = %d", $user->uid));
  173. break;
  174. case 'switch':
  175. global $user;
  176. $switch_to_account = FALSE;
  177. if ($uid) {
  178. if (!is_numeric($uid)) {
  179. return FALSE;
  180. }
  181. if ($account = user_load(array('uid' => $uid))) {
  182. $switch_to_account = db_result(db_query("SELECT TRUE FROM {masquerade_users} WHERE uid_from = %d AND uid_to = %d", $user->uid, $account->uid));
  183. }
  184. }
  185. return !isset($_SESSION['masquerading']) && (user_access('masquerade as user') || user_access('masquerade as admin') || $switch_to_account);
  186. break;
  187. }
  188. }
  189. function masquerade_admin_settings() {
  190. // create a list of roles; all selected roles are considered administrative.
  191. $rids = array();
  192. $result = db_query("SELECT r.rid, r.name FROM {role} r ORDER BY r.name");
  193. while ($obj = db_fetch_object($result)) {
  194. $rids[$obj->rid] = $obj->name;
  195. }
  196. $form['masquerade_admin_roles'] = array(
  197. '#type' => 'checkboxes',
  198. '#title' => t('Roles that are considered "administrators" for masquerading'),
  199. '#options' => $rids,
  200. '#default_value' => variable_get('masquerade_admin_roles', array()),
  201. );
  202. $test_name = _masquerade_user_load(variable_get('masquerade_test_user', ''));
  203. $form['masquerade_test_user'] = array(
  204. '#type' => 'textfield',
  205. '#title' => t('Menu <em>Quick Switch</em> user'),
  206. '#autocomplete_path' => 'masquerade/autocomplete',
  207. '#default_value' => isset($test_name->name) ? check_plain($test_name->name) : '',
  208. '#description' => t('Enter the username of an account you wish to switch easily between via a menu item.'),
  209. '#maxlength' => NULL,
  210. );
  211. $quick_switch_users = array();
  212. foreach ((variable_get('masquerade_quick_switches', array())) as $uid) {
  213. $u = user_load(array('uid' => $uid));
  214. if ($uid == 0) {
  215. $u->name = variable_get('anonymous', t('Anonymous'));
  216. }
  217. $quick_switch_users[] = $u->name;
  218. }
  219. $form['masquerade_quick_switches'] = array(
  220. '#type' => 'textfield',
  221. '#title' => t('Masquerade Block <em>Quick Switch</em> users'),
  222. '#autocomplete_path' => 'masquerade/autocomplete/multiple',
  223. '#default_value' => !empty($quick_switch_users) ? implode(', ', $quick_switch_users) : '',
  224. '#description' => t('Enter the usernames, separated by commas, of accounts to show as quick switch links in the Masquerade block.'),
  225. '#maxlength' => NULL,
  226. );
  227. $form = system_settings_form($form);
  228. $form['#validate'][] = 'masquerade_admin_settings_validate';
  229. $form['#submit'][] = 'masquerade_admin_settings_submit';
  230. return $form;
  231. }
  232. function masquerade_admin_settings_validate($form, &$form_state) {
  233. if (!empty($form_state['values']['masquerade_test_user'])) {
  234. $test_user = _masquerade_user_load($form_state['values']['masquerade_test_user']);
  235. if (!$test_user) {
  236. form_set_error('masquerade_test_user', t('%user does not exist. Please enter a valid username.', array('%user' => $form_state['values']['masquerade_test_user'])));
  237. }
  238. }
  239. // Needs to rebuild menu in masquerade_admin_settings_submit().
  240. $form_state['masquerade_rebuild_menu'] = (variable_get('masquerade_test_user', '') != $form_state['values']['masquerade_test_user']);
  241. // A comma-separated list of users.
  242. $masquerade_switches = drupal_explode_tags($form_state['values']['masquerade_quick_switches']);
  243. // Change user names to user ID's for system_settings_form_submit() to save.
  244. $masquerade_uids = array();
  245. foreach ($masquerade_switches as $switch_user) {
  246. $test_user = _masquerade_user_load($switch_user);
  247. if (!$test_user) {
  248. form_set_error('masquerade_quick_switches', t('%user does not exist. Please enter a valid username.', array('%user' => $switch_user)));
  249. }
  250. else {
  251. $masquerade_uids[] = $test_user->uid;
  252. }
  253. }
  254. $form_state['values']['masquerade_quick_switches'] = $masquerade_uids;
  255. }
  256. function masquerade_admin_settings_submit($form, &$form_state) {
  257. // Rebuild the menu system so the menu "Quick Switch" user is updated.
  258. if ($form_state['masquerade_rebuild_menu']) {
  259. menu_rebuild();
  260. }
  261. }
  262. /**
  263. * Wrapper around user_load() to allow the loading of anonymous users.
  264. *
  265. * @param $username
  266. * The username of the user you wish to load (i.e. $user->name). To load the
  267. * anonymous user, pass the value of the 'anonymous' variable.
  268. *
  269. * @return
  270. * A fully-loaded $user object upon successful user load or FALSE if user
  271. * cannot be loaded.
  272. */
  273. function _masquerade_user_load($username) {
  274. if (!empty($username)) {
  275. $user = '';
  276. $anon = variable_get('anonymous', t('Anonymous'));
  277. if ($username == $anon) {
  278. $user = user_load(array('name' => ''));
  279. $user->name = $anon;
  280. }
  281. else {
  282. $user = user_load(array('name' => $username));
  283. }
  284. return $user;
  285. }
  286. return FALSE;
  287. }
  288. /**
  289. * Implementation of hook_user().
  290. */
  291. function masquerade_user($op, &$edit, &$edit_user, $category = NULL) {
  292. static $old_session_id;
  293. switch ($op) {
  294. case 'logout':
  295. if (!empty($edit_user->masquerading)) {
  296. global $user;
  297. cache_clear_all($user->uid, 'cache_menu', true);
  298. $real_user = user_load(array('uid' => $user->masquerading));
  299. watchdog('masquerade', "User %user no longer masquerading as %masq_as.", array('%user' => $real_user->name, '%masq_as' => $user->name), WATCHDOG_INFO);
  300. db_query("DELETE FROM {masquerade} WHERE sid = '%s' AND uid_as = %d", session_id(), $edit_user->uid);
  301. }
  302. break;
  303. case 'view':
  304. // check if user qualifies as admin
  305. $roles = array_keys(array_filter(variable_get('masquerade_admin_roles', array())));
  306. $perm = $edit_user->uid == 1 || array_intersect(array_keys((array)$edit_user->roles), $roles) ?
  307. 'masquerade as admin' :
  308. 'masquerade as user';
  309. global $user;
  310. if (user_access($perm) && empty($edit_user->masquerading) && $user->uid != $edit_user->uid) {
  311. $edit_user->content['Masquerade'] = array('#value' => l(t('Masquerade as !user', array('!user' => $edit_user->name)), 'masquerade/switch/'. $edit_user->uid, array('query' => array('token' => drupal_get_token('masquerade/switch/'. $edit_user->uid)), 'destination' => $_GET['q'], 'attributes' => array('class' => 'masquerade-switch'))),
  312. '#weight' => 10
  313. );
  314. }
  315. break;
  316. case 'form':
  317. $form = array();
  318. if ($category == 'account') {
  319. $form['masquerade'] = array(
  320. '#type' => 'fieldset',
  321. '#title' => t('Masquerade settings'),
  322. '#access' => user_access('administer masquerade'),
  323. );
  324. $result = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = %d", $edit_user->uid);
  325. $masquerade_users = array();
  326. while ($uid_to = db_result($result)) {
  327. $u = user_load($uid_to);
  328. $masquerade_users[] = $u->name;
  329. }
  330. $form['masquerade']['masquerade_users'] = array(
  331. '#type' => 'textfield',
  332. '#title' => t('Enter the users this user is able to masquerade as'),
  333. '#description' => t('Enter a comma separated list of user names that this user can masquerade as.'),
  334. '#autocomplete_path' => 'masquerade/autocomplete-user',
  335. '#default_value' => implode(", ", $masquerade_users),
  336. '#maxlength' => NULL,
  337. );
  338. }
  339. return $form;
  340. break;
  341. case 'validate':
  342. if ($category == 'account' && isset($edit['masquerade_users'])) {
  343. $users = drupal_explode_tags($edit['masquerade_users']);
  344. foreach ($users as $user) {
  345. if (!user_load(array('name' => $user))) {
  346. form_set_error('masquerade_users', t('%user is not a valid user name.', array('%user' => $user)));
  347. }
  348. }
  349. }
  350. break;
  351. case 'submit':
  352. $old_session_id = session_id();
  353. break;
  354. case 'update':
  355. if ($category == 'account' && isset($edit['masquerade_users'])) {
  356. $users = drupal_explode_tags($edit['masquerade_users']);
  357. db_query("DELETE FROM {masquerade_users} WHERE uid_from = %d", $edit_user->uid);
  358. foreach ($users as $user) {
  359. $u = user_load(array('name' => $user));
  360. db_query("INSERT INTO {masquerade_users} VALUES (%d, %d)", $edit_user->uid, $u->uid);
  361. }
  362. $edit['masquerade_users'] = NULL;
  363. }
  364. break;
  365. case 'delete':
  366. db_query("DELETE FROM {masquerade_users} WHERE uid_from = %d OR uid_to = %d", $edit_user->uid, $edit_user->uid);
  367. break;
  368. case 'after_update':
  369. if (isset($old_session_id) && session_id() != $old_session_id) {
  370. db_query("UPDATE {masquerade} SET sid = '%s' WHERE sid = '%s'", session_id(), $old_session_id);
  371. }
  372. break;
  373. }
  374. }
  375. /**
  376. * Implementation of hook_block().
  377. */
  378. function masquerade_block($op = 'list', $delta = 0, $edit = array()) {
  379. switch ($op) {
  380. case 'list':
  381. $blocks[0]['info'] = t('Masquerade');
  382. $blocks[0]['cache'] = BLOCK_NO_CACHE;
  383. return $blocks;
  384. case 'view':
  385. switch ($delta) {
  386. case 0:
  387. if (masquerade_access('autocomplete') || masquerade_access('user')) {
  388. $block['subject'] = t('Masquerade');
  389. $block['content'] = drupal_get_form('masquerade_block_1');
  390. return $block;
  391. }
  392. break;
  393. }
  394. break;
  395. }
  396. }
  397. /**
  398. * Masquerade block form.
  399. */
  400. function masquerade_block_1($record) {
  401. global $user;
  402. $markup_value = '';
  403. if (isset($_SESSION['masquerading'])) {
  404. $quick_switch_link[] = l(t('Switch back'), 'masquerade/unswitch', array('query' => array('token' => drupal_get_token('masquerade/unswitch'))));
  405. if ($user->uid > 0) {
  406. $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)) . theme('item_list', $quick_switch_link);
  407. }
  408. else {
  409. $markup_value = t('You are masquerading as %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous')))) . theme('item_list', $quick_switch_link);
  410. }
  411. }
  412. else {
  413. $masquerade_switches = variable_get('masquerade_quick_switches', array());
  414. // Add in user-specific switches.
  415. $result = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = %d", $user->uid);
  416. while ($uid_to = db_result($result)) {
  417. $masquerade_switches[] = $uid_to;
  418. }
  419. foreach ($masquerade_switches as $switch_user) {
  420. if (!isset($_SESSION['user']->uid) || $switch_user != $_SESSION['user']->uid) {
  421. $account = user_load(array('uid' => $switch_user));
  422. if (isset($account->uid)) {
  423. $switch_link = 'masquerade/switch/'. $account->uid;
  424. if ($account->uid) {
  425. $quick_switch_link[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
  426. }
  427. if ($switch_user == 0) {
  428. $account->name = variable_get('anonymous', t('Anonymous'));
  429. $quick_switch_link[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
  430. }
  431. }
  432. }
  433. }
  434. if (masquerade_access('autocomplete')) {
  435. $markup_value .= t('Enter the username to masquerade as.');
  436. $form['masquerade_user_field'] = array(
  437. '#prefix' => '<div class="container-inline">',
  438. '#type' => 'textfield',
  439. '#size' => '18',
  440. '#default_value' => '',
  441. '#autocomplete_path' => 'masquerade/autocomplete',
  442. '#required' => TRUE,
  443. );
  444. $form['submit'] = array(
  445. '#type' => 'submit',
  446. '#value' => t('Go'),
  447. '#suffix' => '</div>',
  448. );
  449. }
  450. if (isset($quick_switch_link) && count($quick_switch_link)) {
  451. $markup_value .= '<div id="quick_switch_links">'. t('Quick switches:') . theme('item_list', $quick_switch_link) .'</div>';
  452. }
  453. }
  454. $form['masquerade_desc'] = array(
  455. '#prefix' => '<div class="form-item"><div class="description">',
  456. '#type' => 'markup',
  457. '#value' => $markup_value,
  458. '#suffix' => '</div></div>',
  459. );
  460. return $form;
  461. }
  462. /**
  463. * Masquerade block form validation.
  464. */
  465. function masquerade_block_1_validate($form, &$form_state) {
  466. global $user;
  467. unset($form);
  468. $name = $form_state['values']['masquerade_user_field'];
  469. if ($name == variable_get('anonymous', t('Anonymous'))) {
  470. $name = '';
  471. }
  472. if (isset($_SESSION['masquerading'])) {
  473. 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')))))));
  474. }
  475. if (!empty($name) && module_exists('alt_login')) {
  476. $alt_login = db_fetch_object(db_query("SELECT u.name FROM {users} u INNER JOIN {alt_login} al ON u.uid = al.uid WHERE al.alt_login = '%s'", $name));
  477. if ($alt_login->name) {
  478. $name = $alt_login->name;
  479. }
  480. }
  481. $masq_user = user_load(array('name' => $name));
  482. if (!$masq_user) {
  483. 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'])));
  484. }
  485. else if ($masq_user->uid == $user->uid) {
  486. form_set_error('masquerade_user_field', t('You cannot masquerade as yourself. Please choose a different user to masquerade as.'));
  487. }
  488. else if (variable_get('site_offline', 0) && !user_access('administer site configuration', $masq_user)) {
  489. form_set_error('masquerade_user_field', t('It is not possible to masquerade in off-line mode as !user does not have the %config-perm permission. Please <a href="@site-maintenance">set the site status</a> to "online" to masquerade as !user.', array('!user' => theme('username', $masq_user), '%config-perm' => 'administer site configuration', '@site-maintenance' => url('admin/settings/site-maintenance'))));
  490. }
  491. else {
  492. $form_state['values']['masquerade_user_field'] = $name;
  493. }
  494. }
  495. /**
  496. * Masquerade block form submission.
  497. */
  498. function masquerade_block_1_submit($form, &$form_state) {
  499. unset($form);
  500. $masq_user = user_load(array('name' => $form_state['values']['masquerade_user_field']));
  501. if (!masquerade_switch_user($masq_user->uid)) {
  502. drupal_access_denied();
  503. }
  504. else {
  505. drupal_goto(referer_uri());
  506. }
  507. }
  508. /**
  509. * Returns JS array for Masquerade autocomplete fields.
  510. */
  511. function masquerade_autocomplete($string) {
  512. $matches = array();
  513. $result = db_query_range("SELECT u.name FROM {users} u WHERE LOWER(u.name) LIKE LOWER('%s%%')", $string, 0, 10);
  514. while ($user = db_fetch_object($result)) {
  515. $matches[$user->name] = check_plain($user->name);
  516. }
  517. if (stripos(variable_get('anonymous', t('Anonymous')), $string) === 0) {
  518. $matches[variable_get('anonymous', t('Anonymous'))] = variable_get('anonymous', t('Anonymous'));
  519. }
  520. if (module_exists('devel')) {
  521. $GLOBALS['devel_shutdown'] = FALSE;
  522. }
  523. exit(drupal_json($matches));
  524. }
  525. /**
  526. * Returns JS array for Masquerade autocomplete fields. Supports multiple entries separated by a comma.
  527. */
  528. function masquerade_autocomplete_multiple($string) {
  529. // The user enters a comma-separated list of users. We only autocomplete the last user.
  530. $array = drupal_explode_tags($string);
  531. // Fetch last tag
  532. $last_string = trim(array_pop($array));
  533. $matches = array();
  534. $result = db_query_range("SELECT u.name FROM {users} u WHERE LOWER(u.name) LIKE LOWER('%s%%')", $last_string, 0, 10);
  535. $prefix = count($array) ? implode(', ', $array) .', ' : '';
  536. while ($user = db_fetch_object($result)) {
  537. $matches[$prefix . $user->name] = check_plain($user->name);
  538. }
  539. // This will add anonymous to the list, but not sorted.
  540. if (stripos(variable_get('anonymous', t('Anonymous')), $last_string) === 0) {
  541. $matches[$prefix . variable_get('anonymous', t('Anonymous'))] = variable_get('anonymous', t('Anonymous'));
  542. }
  543. if (module_exists('alt_login')) {
  544. $result = db_query_range("SELECT alt_login FROM {alt_login} u WHERE LOWER(alt_login) LIKE LOWER('%s%%')", $string, 0, 10);
  545. while ($user = db_fetch_object($result)) {
  546. $matches[$user->alt_login] = check_plain($user->alt_login);
  547. }
  548. }
  549. if (module_exists('devel')) {
  550. $GLOBALS['devel_shutdown'] = FALSE;
  551. }
  552. exit(drupal_json($matches));
  553. }
  554. /**
  555. * Replacement function for user_autocomplete which allows the use of a comma
  556. * separated list of user names.
  557. */
  558. function masquerade_autocomplete_user($string) {
  559. $array = drupal_explode_tags($string);
  560. $search = trim(array_pop($array));
  561. $matches = array();
  562. if ($search) {
  563. $prefix = count($array) ? implode(', ', $array) .', ' : '';
  564. $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $search, 0, 10);
  565. while ($user = db_fetch_object($result)) {
  566. $matches[$prefix . $user->name] = check_plain($user->name);
  567. }
  568. }
  569. drupal_json($matches);
  570. }
  571. /**
  572. * Page callback to switch users.
  573. */
  574. function masquerade_switch_user_page($uid) {
  575. if (isset($_GET['token']) && drupal_valid_token($_GET['token'], 'masquerade/switch/' . $uid) && masquerade_switch_user($uid)) {
  576. drupal_goto(referer_uri());
  577. }
  578. else {
  579. drupal_access_denied();
  580. }
  581. }
  582. /**
  583. * Function that allows a user with the right permissions to become
  584. * the selected user.
  585. *
  586. * @param $uid
  587. * The user ID to switch to.
  588. *
  589. * @return
  590. * TRUE if the user was sucessfully switched, or FALSE if there was an error.
  591. */
  592. function masquerade_switch_user($uid) {
  593. global $user;
  594. if (!is_numeric($uid)) {
  595. drupal_set_message(t('A user id was not correctly passed to the switching function.'));
  596. watchdog('masquerade', 'The user id provided to switch users was not numeric.', NULL, WATCHDOG_ERROR);
  597. return drupal_goto(referer_uri());
  598. }
  599. $new_user = user_load(array('uid' => $uid));
  600. $roles = array_keys(array_filter(variable_get('masquerade_admin_roles', array())));
  601. $perm = $uid == 1 || array_intersect(array_keys($new_user->roles), $roles) ?
  602. 'masquerade as admin' :
  603. 'masquerade as user';
  604. // Check to see if we need admin permission.
  605. if (!user_access($perm) && !isset($_SESSION['masquerading']) && !db_result(db_query("SELECT TRUE FROM {masquerade_users} WHERE uid_from = %d AND uid_to = %d", $user->uid, $new_user->uid))) {
  606. watchdog('masquerade', 'This user requires administrative permissions to switch to the user %user.', array('%user' => $new_user->name), WATCHDOG_ERROR);
  607. return FALSE;
  608. }
  609. if ($user->uid == $uid || isset($user->masquerading)) {
  610. watchdog('masquerade', 'This user is already %user.', array('%user' => $new_user->name), WATCHDOG_ERROR);
  611. return FALSE;
  612. }
  613. if (variable_get('site_offline', 0) && !user_access('administer site configuration', $new_user)) {
  614. drupal_set_message(t('It is not possible to masquerade in off-line mode as %user does not have the %config-perm permission. Please <a href="@site-maintenance">set the site status</a> to "online" to masquerade as %user.', array('%user' => $new_user->name, '%config-perm' => 'administer site configuration', '@site-maintenance' => url('admin/settings/site-maintenance'))));
  615. return FALSE;
  616. }
  617. db_query("INSERT INTO {masquerade} (uid_from, uid_as, sid) VALUES (%d, %d, '%s')",
  618. $user->uid, $new_user->uid, session_id());
  619. // switch user
  620. 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);
  621. drupal_set_message(t('You are now masquerading as !masq_as.', array('!masq_as' => theme('username', $new_user))));
  622. $user->masquerading = $new_user->uid;
  623. $user = $new_user;
  624. return TRUE;
  625. }
  626. /**
  627. * Page callback that allows a user who is currently masquerading to become
  628. * a new user.
  629. */
  630. function masquerade_switch_back_page() {
  631. if (isset($_GET['token']) && drupal_valid_token($_GET['token'], 'masquerade/unswitch')) {
  632. global $user;
  633. $olduser = $user;
  634. masquerade_switch_back();
  635. drupal_set_message(t('You are no longer masquerading as !masq_as and are now logged in as !user.', array('!user' => theme('username', $user), '!masq_as' => theme('username', $olduser))));
  636. drupal_goto(referer_uri());
  637. }
  638. else {
  639. drupal_access_denied();
  640. }
  641. }
  642. /**
  643. * Function for a masquerading user to switch back to the previous user.
  644. */
  645. function masquerade_switch_back() {
  646. // switch user
  647. global $user;
  648. cache_clear_all($user->uid, 'cache_menu', true);
  649. $uid = db_result(db_query("SELECT m.uid_from FROM {masquerade} m WHERE m.sid = '%s' AND m.uid_as = %d ", session_id(), $user->uid));
  650. // erase record
  651. db_query("DELETE FROM {masquerade} WHERE sid = '%s' AND uid_as = %d ", session_id(), $user->uid);
  652. $oldname = ($user->uid == 0 ? variable_get('anonymous', t('Anonymous')) : $user->name);
  653. $user = user_load(array('uid' => $uid));
  654. watchdog('masquerade', 'User %user no longer masquerading as %masq_as.', array('%user' => $user->name, '%masq_as' => $oldname), WATCHDOG_INFO);
  655. }