masquerade.module

  1. cis7 sites/all/modules/ulmus/masquerade/masquerade.module
  2. cle7 sites/all/modules/ulmus/masquerade/masquerade.module
  3. ecd7 sites/all/modules/ulmus/masquerade/masquerade.module
  4. elmsmedia7 sites/all/modules/ulmus/masquerade/masquerade.module
  5. harmony7 sites/all/modules/ulmus/masquerade/masquerade.module
  6. icor7 sites/all/modules/ulmus/masquerade/masquerade.module
  7. meedjum_blog7 sites/all/modules/ulmus/masquerade/masquerade.module
  8. mooc7 sites/all/modules/ulmus/masquerade/masquerade.module

The masquerade module allows administrators to masquerade as other user.

Functions

Namesort descending Description
masquerade_admin_settings Admin settings form.
masquerade_admin_settings_submit
masquerade_admin_settings_validate
masquerade_autocomplete Returns JS array for Masquerade autocomplete fields.
masquerade_autocomplete_multiple Returns JS array for Masquerade autocomplete fields.
masquerade_block_1 Masquerade block form.
masquerade_block_1_submit Masquerade block form submission.
masquerade_block_1_validate Masquerade block form validation.
masquerade_block_info Implements hook_block_info().
masquerade_block_view Implements hook_block_view().
masquerade_cron Implements hook_cron().
masquerade_field_extra_fields Implements hook_field_extra_fields().
masquerade_form_user_profile_form_alter Implements hook_form_FORM_ID_alter().
masquerade_help Implements hook_help().
masquerade_init Implements hook_init().
masquerade_menu Implements hook_menu().
masquerade_menu_access
masquerade_menu_alter Implements hook_menu_alter().
masquerade_permission Implements hook_permission().
masquerade_switch_back Function for a masquerading user to switch back to the previous user.
masquerade_switch_back_page Allows a user who is currently masquerading to become a new user.
masquerade_switch_user Allows a user with the right permissions to become the selected user.
masquerade_switch_user_page Page callback to switch users.
masquerade_translated_menu_link_alter Implements hook_translated_menu_link_alter().
masquerade_user_delete Implements hook_user_delete().
masquerade_user_logout Implements hook_user_logout().
masquerade_user_operations Implements hook_user_operations().
masquerade_user_operations_masquerade Callback for user operation.
masquerade_user_submit Submit handler for masquerade users form element.
masquerade_user_update Implements hook_user_update().
masquerade_user_validate Validates user account form.
masquerade_user_view Implements hook_user_view().
_masquerade_user_load Wrapper around user_load() to allow the loading of anonymous users.

File

sites/all/modules/ulmus/masquerade/masquerade.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * The masquerade module allows administrators to masquerade as other user.
  5. */
  6. /**
  7. * Implements hook_help().
  8. */
  9. function masquerade_help($path, $arg) {
  10. switch ($path) {
  11. case 'admin/help#masquerade':
  12. 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>');
  13. case 'admin/settings/masquerade':
  14. 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.');
  15. }
  16. }
  17. /**
  18. * Implements hook_permission().
  19. *
  20. * @return array
  21. */
  22. function masquerade_permission() {
  23. return array(
  24. 'masquerade as user' => array(
  25. 'title' => t('Masquerade as user'),
  26. 'description' => t('Masquerade as another user.'),
  27. ),
  28. 'masquerade as any user' => array(
  29. 'title' => t('Masquerade as any user'),
  30. 'description' => t('Masquerade as any user.'),
  31. 'restrict access' => TRUE,
  32. ),
  33. 'masquerade as admin' => array(
  34. 'title' => t('Masquerade as admin'),
  35. 'description' => t('Masquerade as the site admin (UID 1).'),
  36. 'restrict access' => TRUE,
  37. ),
  38. 'administer masquerade' => array(
  39. 'title' => t('Administer Masquerade'),
  40. 'description' => t('Perform administration tasks and configure the Masquerade module.'),
  41. 'restrict access' => TRUE,
  42. ),
  43. );
  44. }
  45. /**
  46. * Implements hook_init().
  47. */
  48. function masquerade_init() {
  49. global $user;
  50. // Try to load masqing uid from masquerade table.
  51. $uid = db_query("SELECT uid_from FROM {masquerade} WHERE sid = :sid AND uid_as = :uid_as", array(
  52. ':sid' => session_id(),
  53. ':uid_as' => $user->uid,
  54. ))->fetchField();
  55. // We are using identical operator (===) instead of equal (==) because if
  56. // $uid === 0 we want to store the session variable. If there's no record in
  57. // masquerade table we clear the session variable.
  58. if ($uid === FALSE) {
  59. if (isset($_SESSION)) {
  60. unset($_SESSION['masquerading']);
  61. }
  62. }
  63. else {
  64. $_SESSION['masquerading'] = $uid;
  65. }
  66. }
  67. /**
  68. * Implements hook_cron().
  69. *
  70. * Cleanup masquerade records where people didn't use the switch back link
  71. * that would have cleanly removed the user switch record.
  72. */
  73. function masquerade_cron() {
  74. // see http://drupal.org/node/268487 before modifying this query
  75. $subquery = db_select('sessions', 's');
  76. $subquery->addField('s', 'sid');
  77. $query = db_delete('masquerade');
  78. $query->condition('sid', $subquery, 'NOT IN');
  79. $query->execute();
  80. }
  81. /**
  82. * Implements hook_menu().
  83. */
  84. function masquerade_menu() {
  85. $items = array();
  86. $default_test_user = _masquerade_user_load(variable_get('masquerade_test_user', ''));
  87. if ($default_test_user && ($default_test_user->uid || $default_test_user->name == variable_get('anonymous', t('Anonymous')))) {
  88. $items['masquerade/switch/' . $default_test_user->uid] = array(
  89. 'title' => 'Masquerade as @testuser',
  90. 'title arguments' => array('@testuser' => $default_test_user->name),
  91. 'page callback' => 'masquerade_switch_user_page',
  92. 'page arguments' => array(2),
  93. 'access callback' => 'masquerade_menu_access',
  94. 'access arguments' => array('switch'),
  95. 'type' => MENU_NORMAL_ITEM,
  96. );
  97. }
  98. $items['masquerade/switch/%'] = array(
  99. 'title' => 'Masquerading',
  100. 'page callback' => 'masquerade_switch_user_page',
  101. 'page arguments' => array(2),
  102. 'access callback' => 'masquerade_menu_access',
  103. 'access arguments' => array('switch', 2),
  104. 'type' => MENU_NORMAL_ITEM,
  105. );
  106. $items['masquerade/unswitch'] = array(
  107. 'title' => 'Switch back',
  108. 'page callback' => 'masquerade_switch_back_page',
  109. 'access callback' => 'masquerade_menu_access',
  110. 'access arguments' => array('unswitch'),
  111. 'type' => MENU_NORMAL_ITEM,
  112. );
  113. $items['masquerade/autocomplete'] = array(
  114. 'title' => '',
  115. 'page callback' => 'masquerade_autocomplete',
  116. 'access callback' => 'masquerade_menu_access',
  117. 'access arguments' => array('autocomplete'),
  118. 'type' => MENU_CALLBACK,
  119. );
  120. $items['masquerade/autocomplete-users'] = array(
  121. 'title' => '',
  122. 'page callback' => 'masquerade_autocomplete_multiple',
  123. 'access callback' => 'masquerade_menu_access',
  124. 'access arguments' => array('autocomplete'),
  125. 'type' => MENU_CALLBACK,
  126. );
  127. $items['masquerade/autocomplete-user'] = array(
  128. 'title' => 'Masquerade autocomplete',
  129. 'page callback' => 'masquerade_autocomplete_multiple',
  130. 'page arguments' => array(2, FALSE),
  131. 'access arguments' => array('access user profiles'),
  132. 'type' => MENU_CALLBACK,
  133. );
  134. $items['admin/config/people/masquerade'] = array(
  135. 'title' => 'Masquerade',
  136. 'description' => 'Masquerade module allows administrators to masquerade as other users.',
  137. 'page callback' => 'drupal_get_form',
  138. 'page arguments' => array('masquerade_admin_settings'),
  139. 'access callback' => 'user_access',
  140. 'access arguments' => array('administer masquerade'),
  141. 'type' => MENU_NORMAL_ITEM,
  142. );
  143. return $items;
  144. }
  145. /**
  146. * Implements hook_menu_alter().
  147. *
  148. * We need to add a token to the Masquerade paths to protect against CSRF
  149. * attacks. Since menu items in Drupal do not support dynamic elements these
  150. * tokens need to be added during rendering via masquerade_translated_menu_link_alter().
  151. * Set the 'alter'-option to TRUE to make sure
  152. * the links get passed through masquerade_translated_menu_link_alter.
  153. */
  154. function masquerade_menu_alter(&$items) {
  155. $default_test_user = _masquerade_user_load(variable_get('masquerade_test_user', ''));
  156. if (isset($default_test_user->uid)) {
  157. $items['masquerade/switch/' . $default_test_user->uid]['options']['alter'] = TRUE;
  158. }
  159. $items['masquerade/switch/%']['options']['alter'] = TRUE;
  160. $items['masquerade/unswitch']['options']['alter'] = TRUE;
  161. }
  162. /**
  163. * Implements hook_translated_menu_link_alter().
  164. *
  165. * Dynamically add the CSRF protection token to the Masquerade menu items.
  166. */
  167. function masquerade_translated_menu_link_alter(&$item, $map) {
  168. if (isset($item['page_callback'])) {
  169. if ($item['page_callback'] == 'masquerade_switch_user_page' && isset($map[2])) {
  170. $item['localized_options']['query']['token'] = drupal_get_token('masquerade/switch/' . $map[2]);
  171. }
  172. elseif ($item['page_callback'] == 'masquerade_switch_back_page') {
  173. $item['localized_options']['query']['token'] = drupal_get_token('masquerade/unswitch');
  174. }
  175. }
  176. }
  177. /**
  178. * Implements hook_user_operations().
  179. */
  180. function masquerade_user_operations() {
  181. return array(
  182. 'masquerade' => array(
  183. 'label' => t('Masquerade as user'),
  184. 'callback' => 'masquerade_user_operations_masquerade',
  185. ),
  186. );
  187. }
  188. /**
  189. * Callback for user operation.
  190. */
  191. function masquerade_user_operations_masquerade(array $accounts) {
  192. // Only process the first account since switching to multiple makes no sense.
  193. if (($uid = current($accounts)) && masquerade_menu_access('switch', $uid)) {
  194. masquerade_switch_user($uid);
  195. }
  196. }
  197. /**
  198. * Determine if the current user has permission to switch users.
  199. *
  200. * @param string $type
  201. * Either 'switch', 'unswitch', 'user', or 'autocomplete'.
  202. *
  203. * @param object $uid
  204. * An optional parameter indicating a specific uid to switch to.
  205. * Otherwise, return if the user can switch to any user account.
  206. *
  207. * @return
  208. * TRUE, if the user can perform the requested action, FALSE otherwise.
  209. */
  210. function masquerade_menu_access($type, $uid = NULL) {
  211. switch ($type) {
  212. case 'unswitch':
  213. return isset($_SESSION['masquerading']) || arg(2) == 'menu-customize' || arg(2) == 'menu';
  214. case 'autocomplete':
  215. return isset($_SESSION['masquerading']) || (user_access('masquerade as user') || user_access('masquerade as admin'));
  216. break;
  217. case 'user':
  218. global $user;
  219. return db_query("SELECT 1 FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))->fetchField();
  220. break;
  221. case 'switch':
  222. $switch_to_account = FALSE;
  223. global $user;
  224. if ($uid) {
  225. if (!is_numeric($uid)) {
  226. return FALSE;
  227. }
  228. if ($account = user_load($uid)) {
  229. $switch_to_account = db_query("SELECT 1 FROM {masquerade_users} WHERE uid_from = :uid_from AND uid_to = :uid_to", array(
  230. ':uid_from' => $user->uid,
  231. ':uid_to' => $account->uid
  232. ))->fetchField();
  233. }
  234. }
  235. return !isset($_SESSION['masquerading']) && (user_access('masquerade as user') || user_access('masquerade as admin') || $switch_to_account);
  236. break;
  237. }
  238. }
  239. /**
  240. * Admin settings form.
  241. */
  242. function masquerade_admin_settings() {
  243. // create a list of roles; all selected roles are considered administrative.
  244. $roles = user_roles();
  245. $form['masquerade_admin_roles'] = array(
  246. '#type' => 'checkboxes',
  247. '#title' => t('Roles that are considered "administrators" for masquerading'),
  248. '#options' => $roles,
  249. '#default_value' => variable_get('masquerade_admin_roles', array()),
  250. );
  251. $test_name = _masquerade_user_load(variable_get('masquerade_test_user', ''));
  252. $form['masquerade_test_user'] = array(
  253. '#type' => 'textfield',
  254. '#title' => t('Menu <em>Quick Switch</em> user'),
  255. '#autocomplete_path' => 'masquerade/autocomplete',
  256. '#default_value' => isset($test_name->name) ? check_plain($test_name->name) : '',
  257. '#description' => t('Enter the username of an account you wish to switch easily between via a menu item.'),
  258. '#maxlength' => NULL,
  259. );
  260. $quick_switch = user_load_multiple(variable_get('masquerade_quick_switches', array()));
  261. $quick_switch_users = array();
  262. foreach ($quick_switch as $uid => $account) {
  263. if ($uid == 0) {
  264. $account->name = variable_get('anonymous', t('Anonymous'));
  265. }
  266. $quick_switch_users[] = $account->name;
  267. }
  268. $form['masquerade_quick_switches'] = array(
  269. '#type' => 'textfield',
  270. '#title' => t('Masquerade Block <em>Quick Switch</em> users'),
  271. '#autocomplete_path' => 'masquerade/autocomplete-users',
  272. '#default_value' => drupal_implode_tags($quick_switch_users),
  273. '#description' => t('Enter the usernames, separated by commas, of accounts to show as quick switch links in the Masquerade block.'),
  274. '#maxlength' => NULL,
  275. );
  276. $form = system_settings_form($form);
  277. $form['#validate'][] = 'masquerade_admin_settings_validate';
  278. $form['#submit'][] = 'masquerade_admin_settings_submit';
  279. return $form;
  280. }
  281. function masquerade_admin_settings_validate($form, &$form_state) {
  282. if (!empty($form_state['values']['masquerade_test_user'])) {
  283. $test_user = _masquerade_user_load($form_state['values']['masquerade_test_user']);
  284. if (!$test_user) {
  285. form_set_error('masquerade_test_user', t('%user does not exist. Please enter a valid username.', array('%user' => $form_state['values']['masquerade_test_user'])));
  286. }
  287. }
  288. // Needs to rebuild menu in masquerade_admin_settings_submit().
  289. $form_state['masquerade_rebuild_menu'] = (variable_get('masquerade_test_user', '') != $form_state['values']['masquerade_test_user']);
  290. // A comma-separated list of users.
  291. $masquerade_switches = drupal_explode_tags($form_state['values']['masquerade_quick_switches']);
  292. // Change user names to user ID's for system_settings_form_submit() to save.
  293. $masquerade_uids = array();
  294. foreach ($masquerade_switches as $switch_user) {
  295. $test_user = _masquerade_user_load($switch_user);
  296. if (!$test_user) {
  297. form_set_error('masquerade_quick_switches', t('%user does not exist. Please enter a valid username.', array('%user' => $switch_user)));
  298. }
  299. else {
  300. $masquerade_uids[] = $test_user->uid;
  301. }
  302. }
  303. $form_state['values']['masquerade_quick_switches'] = $masquerade_uids;
  304. }
  305. function masquerade_admin_settings_submit($form, &$form_state) {
  306. // Rebuild the menu system so the menu "Quick Switch" user is updated.
  307. if ($form_state['masquerade_rebuild_menu']) {
  308. menu_rebuild();
  309. }
  310. }
  311. /**
  312. * Wrapper around user_load() to allow the loading of anonymous users.
  313. *
  314. * @param $username
  315. * The username of the user you wish to load (i.e. $user->name). To load the
  316. * anonymous user, pass the value of the 'anonymous' variable.
  317. *
  318. * @return
  319. * A fully-loaded $user object upon successful user load or FALSE if user
  320. * cannot be loaded.
  321. */
  322. function _masquerade_user_load($username) {
  323. $account = FALSE;
  324. if (!empty($username)) {
  325. $anon = variable_get('anonymous', t('Anonymous'));
  326. $account = user_load_by_name(($username == $anon ? '' : $username));
  327. if (isset($account->uid) && empty($account->uid)) {
  328. // Anonymous user should have a name.
  329. $account->name = $anon;
  330. }
  331. }
  332. return $account;
  333. }
  334. /**
  335. * Implements hook_user_logout().
  336. */
  337. function masquerade_user_logout($account) {
  338. if (!empty($account->masquerading)) {
  339. global $user;
  340. cache_clear_all($user->uid, 'cache_menu', TRUE);
  341. $real_user = user_load($user->masquerading);
  342. watchdog('masquerade', "User %user no longer masquerading as %masq_as.", array('%user' => $real_user->name, '%masq_as' => $user->name), WATCHDOG_INFO);
  343. $query = db_delete('masquerade');
  344. $query->condition('sid', session_id());
  345. $query->condition('uid_as', $account->uid);
  346. $query->execute();
  347. }
  348. }
  349. /**
  350. * Implements hook_field_extra_fields().
  351. */
  352. function masquerade_field_extra_fields() {
  353. $return['user']['user'] = array(
  354. 'form' => array(
  355. 'masquerade' => array(
  356. 'label' => t('Masquerade'),
  357. 'description' => t('User masquerade settings.'),
  358. 'weight' => 50,
  359. ),
  360. ),
  361. 'display' => array(
  362. 'masquerade' => array(
  363. 'label' => t('Masquerade'),
  364. 'description' => t('Masquerade as user link.'),
  365. 'weight' => 50,
  366. ),
  367. ),
  368. );
  369. return $return;
  370. }
  371. /**
  372. * Implements hook_user_view().
  373. */
  374. function masquerade_user_view($account, $view_mode, $langcode) {
  375. // check if user qualifies as admin
  376. $roles = array_keys(array_filter(variable_get('masquerade_admin_roles', array())));
  377. $perm = $account->uid == 1 || array_intersect(array_keys((array)$account->roles), $roles) ?
  378. 'masquerade as admin' :
  379. 'masquerade as user';
  380. global $user;
  381. // Query allowed uids so the "masquerade as <user>" link can be shown or
  382. // hidden.
  383. $allowed_uids = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))
  384. ->fetchCol();
  385. $can_masquerade_as_user = in_array($account->uid, $allowed_uids) || user_access('masquerade as any user');
  386. if (user_access($perm) && empty($account->masquerading) && $user->uid != $account->uid && $can_masquerade_as_user) {
  387. $account->content['masquerade'] = array(
  388. '#markup' => l(t('Masquerade as !user', array('!user' => $account->name)),
  389. 'masquerade/switch/' . $account->uid,
  390. array('query' => array(
  391. 'token' => drupal_get_token('masquerade/switch/' . $account->uid)),
  392. 'destination' => $_GET['q'],
  393. 'attributes' => array('class' => array('masquerade-switch')),
  394. )),
  395. '#weight' => 10,
  396. );
  397. }
  398. }
  399. /**
  400. * Implements hook_form_FORM_ID_alter().
  401. */
  402. function masquerade_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  403. if ($form['#user_category'] != 'account') {
  404. // Do not show this form for different categories.
  405. return;
  406. }
  407. $form['masquerade'] = array(
  408. '#type' => 'fieldset',
  409. '#title' => t('Masquerade settings'),
  410. '#access' => user_access('administer masquerade'),
  411. );
  412. $edit_user = $form['#user'];
  413. $uids = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $edit_user->uid))
  414. ->fetchCol();
  415. $users = user_load_multiple($uids);
  416. $masquerade_users = array();
  417. foreach ($users as $uid => $account) {
  418. if ($uid == 0) {
  419. $masquerade_users[] = variable_get('anonymous', t('Anonymous'));
  420. }
  421. else {
  422. $masquerade_users[] = $account->name;
  423. }
  424. }
  425. $form['masquerade']['masquerade_users'] = array(
  426. '#type' => 'textfield',
  427. '#title' => t('Enter the users this user is able to masquerade as'),
  428. '#description' => t('Enter a comma separated list of user names that this user can masquerade as.'),
  429. '#autocomplete_path' => 'masquerade/autocomplete-user',
  430. '#default_value' => drupal_implode_tags($masquerade_users),
  431. '#maxlength' => NULL,
  432. );
  433. $form['#validate'][] = 'masquerade_user_validate';
  434. $form['#submit'][] = 'masquerade_user_submit';
  435. }
  436. /**
  437. * Validates user account form.
  438. */
  439. function masquerade_user_validate(&$form, $form_state) {
  440. if (isset($form_state['values']['masquerade_users'])) {
  441. $users = drupal_explode_tags($form_state['values']['masquerade_users']);
  442. foreach ($users as $username) {
  443. if (!_masquerade_user_load($username)) {
  444. form_set_error('masquerade_users', t('%user is not a valid user name.', array('%user' => $username)));
  445. }
  446. }
  447. }
  448. }
  449. /**
  450. * Submit handler for masquerade users form element.
  451. */
  452. function masquerade_user_submit(&$form, $form_state) {
  453. global $_masquerade_old_session_id;
  454. $_masquerade_old_session_id = session_id();
  455. }
  456. /**
  457. * Implements hook_user_update().
  458. */
  459. function masquerade_user_update(&$edit, $account, $category) {
  460. global $_masquerade_old_session_id;
  461. if ($category == 'account' && isset($edit['masquerade_users'])) {
  462. $query = db_delete('masquerade_users');
  463. $query->condition('uid_from', $account->uid);
  464. $query->execute();
  465. // Save users from settings form.
  466. $users = drupal_explode_tags($edit['masquerade_users']);
  467. $query = db_insert('masquerade_users')->fields(array('uid_from', 'uid_to'));
  468. foreach ($users as $username) {
  469. if ($to_user = _masquerade_user_load($username)) {
  470. $query->values(array(
  471. 'uid_from' => $account->uid,
  472. 'uid_to' => $to_user->uid,
  473. ));
  474. }
  475. }
  476. $query->execute();
  477. $edit['masquerade_users'] = NULL;
  478. // Update user session...
  479. // @TODO check other way of session API.
  480. if (!empty($_masquerade_old_session_id)) {
  481. $query = db_update('masquerade');
  482. $query->fields(array(
  483. 'sid' => session_id(),
  484. ));
  485. $query->condition('sid', $_masquerade_old_session_id);
  486. $query->execute();
  487. }
  488. }
  489. }
  490. /**
  491. * Implements hook_user_delete().
  492. */
  493. function masquerade_user_delete($account) {
  494. // Cleanup tables.
  495. $query = db_delete('masquerade_users');
  496. $conditions = db_or();
  497. $conditions->condition('uid_from', $account->uid);
  498. $conditions->condition('uid_to', $account->uid);
  499. $query->condition($conditions);
  500. $query->execute();
  501. // Cleanup variables.
  502. $switches = variable_get('masquerade_quick_switches', array());
  503. $switches_new = array_diff($switches, array($account->uid));
  504. if ($switches != $switches_new) {
  505. variable_set('masquerade_quick_switches', $switches_new);
  506. // @TODO Implement block cache cleaning.
  507. menu_rebuild();
  508. }
  509. }
  510. /**
  511. * Implements hook_block_info().
  512. */
  513. function masquerade_block_info() {
  514. $blocks = array();
  515. $blocks['masquerade'] = array(
  516. 'info' => t('Masquerade'),
  517. 'cache' => DRUPAL_NO_CACHE,
  518. );
  519. return $blocks;
  520. }
  521. /**
  522. * Implements hook_block_view().
  523. */
  524. function masquerade_block_view($delta = '') {
  525. $block = array();
  526. switch ($delta) {
  527. case 'masquerade':
  528. if (isset($_SESSION['masquerading']) || (user_access('masquerade as user') || user_access('masquerade as admin'))) {
  529. $block['subject'] = t('Masquerade');
  530. $block['content'] = drupal_get_form('masquerade_block_1');
  531. }
  532. break;
  533. }
  534. return $block;
  535. }
  536. /**
  537. * Masquerade block form.
  538. */
  539. function masquerade_block_1() {
  540. global $user;
  541. $quick_switch_links = array();
  542. $markup_value = '';
  543. if (isset($_SESSION['masquerading'])) {
  544. $quick_switch_links[] = l(t('Switch back'), 'masquerade/unswitch', array('query' => array('token' => drupal_get_token('masquerade/unswitch'))));
  545. if ($user->uid > 0) {
  546. $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));
  547. }
  548. else {
  549. $markup_value = t('You are masquerading as %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous'))));
  550. }
  551. }
  552. else {
  553. $quick_switches = variable_get('masquerade_quick_switches', array());
  554. // Add in user-specific switches, and prevent duplicates.
  555. $user_switches = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))->fetchCol();
  556. $masquerade_switches = array_unique(array_merge($quick_switches, $user_switches));
  557. foreach ($masquerade_switches as $switch_user) {
  558. if (!isset($_SESSION['user']->uid) || $switch_user != $_SESSION['user']->uid) {
  559. $account = user_load($switch_user);
  560. if (isset($account->uid)) {
  561. $switch_link = 'masquerade/switch/' . $account->uid;
  562. if ($account->uid) {
  563. $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
  564. }
  565. if ($switch_user == 0) {
  566. $account->name = variable_get('anonymous', t('Anonymous'));
  567. $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
  568. }
  569. }
  570. }
  571. }
  572. if (masquerade_menu_access('autocomplete')) {
  573. $markup_value .= t('Enter the username to masquerade as.');
  574. $form['masquerade_user_field'] = array(
  575. '#prefix' => '<div class="container-inline">',
  576. '#type' => 'textfield',
  577. '#size' => '18',
  578. '#default_value' => '',
  579. '#autocomplete_path' => 'masquerade/autocomplete',
  580. '#required' => TRUE,
  581. );
  582. $form['submit'] = array(
  583. '#type' => 'submit',
  584. '#value' => t('Go'),
  585. '#suffix' => '</div>',
  586. );
  587. }
  588. }
  589. if ($quick_switch_links) {
  590. $markup_value .= '<div id="quick_switch_links">' . t('Quick switches:') . theme('item_list', array('items' => $quick_switch_links)) . '</div>';
  591. }
  592. $form['masquerade_desc'] = array(
  593. '#prefix' => '<div class="form-item"><div class="description">',
  594. '#markup' => $markup_value,
  595. '#suffix' => '</div></div>',
  596. );
  597. return $form;
  598. }
  599. /**
  600. * Masquerade block form validation.
  601. */
  602. function masquerade_block_1_validate($form, &$form_state) {
  603. global $user;
  604. //unset($form);
  605. $name = $form_state['values']['masquerade_user_field'];
  606. $allowed = FALSE;
  607. $to_uid = db_select('users', 'u')
  608. ->fields('u', array('uid'))
  609. ->condition('u.name', $name, '=')
  610. ->execute()
  611. ->fetchField();
  612. if ($to_uid !== FALSE) {
  613. $allowed = user_access('masquerade as any user') ||
  614. db_select('masquerade_users', 'm')
  615. ->fields('m', array('uid_to'))
  616. ->condition('m.uid_to', $to_uid, '=')
  617. ->condition('m.uid_from', $user->uid, '=')
  618. ->execute()
  619. ->fetchField();
  620. }
  621. if (isset($_SESSION['masquerading'])) {
  622. 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')))))));
  623. }
  624. if ($allowed === FALSE) {
  625. form_set_error('masquerade_user_field', t('You are not allowed to masquerade as the selected user.'));
  626. }
  627. if ($name != variable_get('anonymous', t('Anonymous')) && module_exists('alt_login')) {
  628. $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(
  629. ':alt_login' => $name
  630. ))->fetchObject();
  631. if (isset($alt_login->name)) {
  632. $name = $alt_login->name;
  633. }
  634. }
  635. $masq_user = _masquerade_user_load($name);
  636. if (!$masq_user) {
  637. 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'])));
  638. }
  639. elseif ($masq_user->uid == $user->uid) {
  640. form_set_error('masquerade_user_field', t('You cannot masquerade as yourself. Please choose a different user to masquerade as.'));
  641. }
  642. elseif (variable_get('maintenance_mode', 0) && !user_access('access site in maintenance mode', $masq_user)) {
  643. 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', array('account' => $masq_user)), '%config-perm' => 'use the site in maintenance mode', '@site-maintenance' => url('admin/settings/site-maintenance'))));
  644. }
  645. else {
  646. $form_state['values']['masquerade_user_field'] = $name;
  647. }
  648. }
  649. /**
  650. * Masquerade block form submission.
  651. */
  652. function masquerade_block_1_submit($form, &$form_state) {
  653. //unset($form);
  654. $masq_user = _masquerade_user_load($form_state['values']['masquerade_user_field']);
  655. if (!masquerade_switch_user($masq_user->uid)) {
  656. drupal_access_denied();
  657. }
  658. else {
  659. drupal_goto($_SERVER['HTTP_REFERER']);
  660. }
  661. }
  662. /**
  663. * Returns JS array for Masquerade autocomplete fields.
  664. */
  665. function masquerade_autocomplete($string) {
  666. $matches = array();
  667. // Anonymous user goes first to be visible for user.
  668. $anonymous = variable_get('anonymous', t('Anonymous'));
  669. if (stripos($anonymous, $string) === 0) {
  670. $matches[$anonymous] = $anonymous;
  671. }
  672. // Other suggestions.
  673. $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER(:string)", 0, 10, array(
  674. ':string' => $string . '%',
  675. ));
  676. foreach ($result as $user) {
  677. $matches[$user->name] = check_plain($user->name);
  678. }
  679. if (module_exists('devel')) {
  680. $GLOBALS['devel_shutdown'] = FALSE;
  681. }
  682. drupal_json_output($matches);
  683. }
  684. /**
  685. * Returns JS array for Masquerade autocomplete fields.
  686. *
  687. * Supports multiple entries separated by a comma.
  688. *
  689. * @param $string
  690. * The string of autocmplete value submitted by the user.
  691. * @param $add_anonymous
  692. * Flag to include Anonymous user into result.
  693. */
  694. function masquerade_autocomplete_multiple($string, $add_anonymous = TRUE) {
  695. $matches = array();
  696. // The user enters a comma-separated list of users. We only autocomplete the last user.
  697. $users_typed = drupal_explode_tags($string);
  698. // Fetch last string.
  699. $last_string = drupal_strtolower(array_pop($users_typed));
  700. if ($last_string) {
  701. $prefix = count($users_typed) ? implode(', ', $users_typed) . ', ' : '';
  702. if ($add_anonymous) {
  703. // Anonymous user goes first to be visible for user.
  704. $anonymous = variable_get('anonymous', t('Anonymous'));
  705. if (stripos($anonymous, $last_string) === 0) {
  706. $matches[$prefix . $anonymous] = $anonymous;
  707. }
  708. }
  709. // Other suggestions.
  710. $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE :string", 0, 10, array(
  711. ':string' => $last_string . '%',
  712. ));
  713. foreach ($result as $user) {
  714. $matches[$prefix . $user->name] = check_plain($user->name);
  715. }
  716. // Remove existing tags.
  717. $matches = array_diff($matches, $users_typed);
  718. // @todo Check compatibility for D7.
  719. if (module_exists('alt_login')) {
  720. $result = db_query_range("SELECT u.alt_login AS alt_login FROM {alt_login} u WHERE LOWER(u.alt_login) LIKE LOWER(:string)", 0, 10, array(
  721. ':string' => $last_string . '%',
  722. ));
  723. foreach ($result as $user) {
  724. $matches[$user->alt_login] = check_plain($user->alt_login);
  725. }
  726. }
  727. }
  728. if (module_exists('devel')) {
  729. $GLOBALS['devel_shutdown'] = FALSE;
  730. }
  731. drupal_json_output($matches);
  732. }
  733. /**
  734. * Page callback to switch users.
  735. */
  736. function masquerade_switch_user_page($uid) {
  737. if (isset($_GET['token']) && drupal_valid_token($_GET['token'], 'masquerade/switch/' . $uid) && masquerade_switch_user($uid)) {
  738. drupal_goto($_SERVER['HTTP_REFERER']);
  739. }
  740. else {
  741. drupal_access_denied();
  742. }
  743. }
  744. /**
  745. * Allows a user with the right permissions to become the selected user.
  746. *
  747. * @param $uid
  748. * The user ID to switch to.
  749. *
  750. * @return
  751. * TRUE if the user was sucessfully switched, or FALSE if there was an error.
  752. */
  753. function masquerade_switch_user($uid) {
  754. global $user;
  755. if (!is_numeric($uid)) {
  756. drupal_set_message(t('A user id was not correctly passed to the switching function.'));
  757. watchdog('masquerade', 'The user id provided to switch users was not numeric.', NULL, WATCHDOG_ERROR);
  758. return drupal_goto($_SERVER['HTTP_REFERER']);
  759. }
  760. $new_user = user_load($uid);
  761. $roles = array_keys(array_filter(variable_get('masquerade_admin_roles', array())));
  762. $perm = $uid == 1 || array_intersect(array_keys($new_user->roles), $roles) ?
  763. 'masquerade as admin' :
  764. 'masquerade as user';
  765. // Check to see if we need admin permission.
  766. $results = db_query_range('SELECT 1 FROM {masquerade_users} WHERE uid_from = :uid_from AND uid_to = :uid_to', 0, 1, array(
  767. ':uid_from' => $user->uid,
  768. ':uid_to' => $new_user->uid,
  769. ));
  770. if (!user_access($perm) && !isset($_SESSION['masquerading']) && !$results->fetchField()) {
  771. watchdog('masquerade', 'This user requires administrative permissions to switch to the user %user.', array('%user' => $new_user->name), WATCHDOG_ERROR);
  772. return FALSE;
  773. }
  774. if ($user->uid == $uid || isset($user->masquerading)) {
  775. watchdog('masquerade', 'This user is already %user.', array('%user' => $new_user->name), WATCHDOG_ERROR);
  776. return FALSE;
  777. }
  778. if (variable_get('maintenance_mode', 0) && !user_access('access site in maintenance mode', $new_user)) {
  779. 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' => 'use the site in maintenance mode', '@site-maintenance' => url('admin/settings/site-maintenance'))));
  780. return FALSE;
  781. }
  782. // Call logout hooks when switching from original user.
  783. module_invoke_all('user_logout', $user);
  784. drupal_session_regenerate();
  785. $query = db_insert('masquerade');
  786. $query->fields(array(
  787. 'uid_from' => $user->uid,
  788. 'uid_as' => $new_user->uid,
  789. 'sid' => session_id(),
  790. ));
  791. $query->execute();
  792. // switch user
  793. 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);
  794. drupal_set_message(t('You are now masquerading as !masq_as.', array('!masq_as' => theme('username', array('account' => $new_user)))));
  795. $user->masquerading = $new_user->uid;
  796. $user = $new_user;
  797. // Call all login hooks when switching to masquerading user.
  798. $edit = array(); // Passed by reference.
  799. user_module_invoke('login', $edit, $user);
  800. return TRUE;
  801. }
  802. /**
  803. * Allows a user who is currently masquerading to become a new user.
  804. */
  805. function masquerade_switch_back_page() {
  806. if (isset($_GET['token']) && drupal_valid_token($_GET['token'], 'masquerade/unswitch')) {
  807. global $user;
  808. $olduser = $user;
  809. masquerade_switch_back();
  810. 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)))));
  811. drupal_goto($_SERVER['HTTP_REFERER']);
  812. }
  813. else {
  814. drupal_access_denied();
  815. }
  816. }
  817. /**
  818. * Function for a masquerading user to switch back to the previous user.
  819. */
  820. function masquerade_switch_back() {
  821. // switch user
  822. global $user;
  823. cache_clear_all($user->uid, 'cache_menu', TRUE);
  824. $uid = db_query("SELECT m.uid_from FROM {masquerade} m WHERE m.sid = :sid AND m.uid_as = :uid_as ", array(
  825. ':sid' => session_id(),
  826. ':uid_as' => $user->uid,
  827. ))->fetchField();
  828. // erase record
  829. db_delete('masquerade')
  830. ->condition('sid', session_id())
  831. ->condition('uid_as', $user->uid)
  832. ->execute();
  833. $oldname = ($user->uid == 0 ? variable_get('anonymous', t('Anonymous')) : $user->name);
  834. // Call logout hooks when switching from masquerading user.
  835. module_invoke_all('user_logout', $user);
  836. drupal_session_regenerate();
  837. $user = user_load($uid);
  838. // Call all login hooks when switching back to original user.
  839. $edit = array(); // Passed by reference.
  840. user_module_invoke('login', $edit, $user);
  841. watchdog('masquerade', 'User %user no longer masquerading as %masq_as.', array('%user' => $user->name, '%masq_as' => $oldname), WATCHDOG_INFO);
  842. }