initial commit of starter install drupal 7

This commit is contained in:
Bachir Soussi Chiadmi
2015-02-21 17:21:40 +01:00
commit eeba51cea6
6113 changed files with 1249218 additions and 0 deletions
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
@@ -0,0 +1,38 @@
= Masquerade =
The Masquerade module allows users to temporarily switch to another user
account. It keeps a record of the original user account, so users can easily
switch back to the previous account.
== Installation and Configuration ==
To install the Masquerade module, extract the module to your modules folder,
such as sites/all/modules. After enabling the module, it can be configured
under Administer > Configuration > People > Masquerade. To enable users to
masquerade, assign the appropriate "masquerade module" permissions to the roles
available on your site. For example:
* To allow members of the 'customer support' role to masquerade as any
non-admin user, add the 'masquerade as user' permission to the role. In the
Masquerade configuration, set 'administrator' as an administrator role
to prevent customer support users from masquerading as those users.
* To allow members of the 'tech support' role to masquerade as 'administrator', add the 'masquerade as admin' permission to the role. Then,
in the Masquerade configuration, set 'administrator' as an
administrator role.
== Quick Switch Menu ==
By default, when a user is selected for the 'Menu Quick Switch user', the Masquerade module adds two menu items to the 'Navigation' menu:
* Masquerade as 'the user selected': When clicked, the user can quick switch to the user selected.
* Switch back: This menu item appears while masquerading so that you can switch back to your original user.
== Help and Support ==
This module was developed by a number of contributors. For more information
about this module, see:
Project Page: http://drupal.org/project/masquerade
Issue Queue: http://drupal.org/project/issues/masquerade
@@ -0,0 +1,12 @@
name = Masquerade
description = "This module allows permitted users to masquerade as other users."
core = 7.x
files[] = masquerade.test
configure = admin/config/people/masquerade
; Information added by Drupal.org packaging script on 2014-07-07
version = "7.x-1.0-rc7+1-dev"
core = "7.x"
project = "masquerade"
datestamp = "1404694728"
@@ -0,0 +1,183 @@
<?php
/**
* @file
* masquerade.install
*
* Install, uninstall and update hooks for the Masquarade module.
*/
/**
* Implements hook_schema().
*
* @return array
*/
function masquerade_schema() {
return array(
'masquerade' => array(
'description' => 'Each masquerading user has their session recorded into the masquerade table. Each record represents a masquerading user.',
'fields' => array(
'sid' => array(
'description' => 'The current session for this masquerading user corresponding to their {sessions}.sid.',
'type' => 'varchar',
'length' => '64',
'not null' => TRUE,
'default' => ''),
'uid_from' => array(
'description' => 'The {users}.uid corresponding to a session.',
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'disp-width' => '10'),
'uid_as' => array(
'description' => 'The {users}.uid this session is masquerading as.',
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'disp-width' => '10'),
),
'indexes' => array(
'sid' => array('sid', 'uid_from'),
'sid_2' => array('sid', 'uid_as'),
),
),
'masquerade_users' => array(
'description' => 'Per-user permission table granting permissions to switch as a specific user.',
'fields' => array(
'uid_from' => array(
'description' => 'The {users}.uid that can masquerade as {masquerade_users}.uid_to.',
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'disp-width' => 10,
),
'uid_to' => array(
'description' => 'The {users}.uid that {masquerade_users}.uid_from can masquerade as.',
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'disp-width' => 10,
),
),
'primary key' => array('uid_from', 'uid_to'),
),
);
}
/**
* Implements hook_install().
*/
function masquerade_install() {
db_update('system')
->fields(array('weight' => -10))
->condition('name', 'masquerade')
->execute();
}
/**
* Implements hook_uninstall().
*/
function masquerade_uninstall() {
variable_del('masquerade_test_user');
variable_del('masquerade_admin_roles');
variable_del('masquerade_quick_switches');
}
/**
* Reformat variable value.
*/
function masquerade_update_6001() {
variable_set('masquerade_quick_switches', implode(',', variable_get('masquerade_quick_switches', array())));
}
/**
* Make the sid column match the length of the core sessions table (64 characters).
*/
function masquerade_update_6002() {
db_drop_index('masquerade', 'sid');
db_drop_index('masquerade', 'sid_2');
db_change_field('masquerade', 'sid', 'sid', array(
'type' => 'varchar',
'length' => '64',
'not null' => TRUE,
'default' => '')
);
db_add_index('masquerade', 'sid', array('sid', 'uid_from'));
db_add_index('masquerade', 'sid_2', array('sid', 'uid_as'));
}
/**
* Change masquerade_quick_switches variable to store a serialized array of
* user ID's. Reverts update 6001.
*/
function masquerade_update_6003() {
$users = variable_get('masquerade_quick_switches', NULL);
if (!empty($users)) {
$user_ids = drupal_explode_tags($users);
if (!empty($user_ids)) {
variable_set('masquerade_quick_switches', $user_ids);
}
}
else {
variable_del('masquerade_quick_switches');
}
}
/**
* Set the weight of the masquerade module to -10, but only if it hasn't
* previously been changed.
*/
function masquerade_update_6004() {
db_update('system')
->fields(array('weight' => -10))
->condition('name', 'masquerade')
->execute();
}
/**
* Add a table storing specific user pairings a user can masquerade as.
*/
function masquerade_update_6005() {
$schema = array(
'masquerade_users' => array(
'fields' => array(
'uid_from' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'disp-width' => 10,
),
'uid_to' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'disp-width' => 10,
),
),
'primary key' => array('uid_from', 'uid_to'),
)
);
db_create_table('masquerade_users', $schema['masquerade_users']);
}
/**
* Update masquerade block delta.
*/
function masquerade_update_7000() {
db_update('block')
->fields(array('delta' => 'masquerade'))
->condition('module', 'masquerade')
->condition('delta', 0)
->execute();
}
/**
* Update masquerade block caching.
*/
function masquerade_update_7001() {
db_update('block')
->fields(array('cache' => DRUPAL_NO_CACHE))
->condition('module', 'masquerade')
->condition('delta', 'masquerade')
->execute();
}
@@ -0,0 +1,917 @@
<?php
/**
* @file
* The masquerade module allows administrators to masquerade as other user.
*/
/**
* Implements hook_help().
*/
function masquerade_help($path, $arg) {
switch ($path) {
case 'admin/help#masquerade':
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>');
case 'admin/settings/masquerade':
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.');
}
}
/**
* Implements hook_permission().
*
* @return array
*/
function masquerade_permission() {
return array(
'masquerade as user' => array(
'title' => t('Masquerade as user'),
'description' => t('Masquerade as another user.'),
),
'masquerade as any user' => array(
'title' => t('Masquerade as any user'),
'description' => t('Masquerade as any user.'),
'restrict access' => TRUE,
),
'masquerade as admin' => array(
'title' => t('Masquerade as admin'),
'description' => t('Masquerade as the site admin (UID 1).'),
'restrict access' => TRUE,
),
'administer masquerade' => array(
'title' => t('Administer Masquerade'),
'description' => t('Perform administration tasks and configure the Masquerade module.'),
'restrict access' => TRUE,
),
);
}
/**
* Implements hook_init().
*/
function masquerade_init() {
global $user;
// Try to load masqing uid from masquerade table.
$uid = db_query("SELECT uid_from FROM {masquerade} WHERE sid = :sid AND uid_as = :uid_as", array(
':sid' => session_id(),
':uid_as' => $user->uid,
))->fetchField();
// We are using identical operator (===) instead of equal (==) because if
// $uid === 0 we want to store the session variable. If there's no record in
// masquerade table we clear the session variable.
if ($uid === FALSE) {
if (isset($_SESSION)) {
unset($_SESSION['masquerading']);
}
}
else {
$_SESSION['masquerading'] = $uid;
}
}
/**
* Implements hook_cron().
*
* Cleanup masquerade records where people didn't use the switch back link
* that would have cleanly removed the user switch record.
*/
function masquerade_cron() {
// see http://drupal.org/node/268487 before modifying this query
$subquery = db_select('sessions', 's');
$subquery->addField('s', 'sid');
$query = db_delete('masquerade');
$query->condition('sid', $subquery, 'NOT IN');
$query->execute();
}
/**
* Implements hook_menu().
*/
function masquerade_menu() {
$items = array();
$default_test_user = _masquerade_user_load(variable_get('masquerade_test_user', ''));
if ($default_test_user && ($default_test_user->uid || $default_test_user->name == variable_get('anonymous', t('Anonymous')))) {
$items['masquerade/switch/' . $default_test_user->uid] = array(
'title' => 'Masquerade as @testuser',
'title arguments' => array('@testuser' => $default_test_user->name),
'page callback' => 'masquerade_switch_user_page',
'page arguments' => array(2),
'access callback' => 'masquerade_menu_access',
'access arguments' => array('switch'),
'type' => MENU_NORMAL_ITEM,
);
}
$items['masquerade/switch/%'] = 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/unswitch'] = array(
'title' => 'Switch back',
'page callback' => 'masquerade_switch_back_page',
'access callback' => 'masquerade_menu_access',
'access arguments' => array('unswitch'),
'type' => MENU_NORMAL_ITEM,
);
$items['masquerade/autocomplete'] = array(
'title' => '',
'page callback' => 'masquerade_autocomplete',
'access callback' => 'masquerade_menu_access',
'access arguments' => array('autocomplete'),
'type' => MENU_CALLBACK,
);
$items['masquerade/autocomplete-users'] = array(
'title' => '',
'page callback' => 'masquerade_autocomplete_multiple',
'access callback' => 'masquerade_menu_access',
'access arguments' => array('autocomplete'),
'type' => MENU_CALLBACK,
);
$items['masquerade/autocomplete-user'] = array(
'title' => 'Masquerade autocomplete',
'page callback' => 'masquerade_autocomplete_multiple',
'page arguments' => array(2, FALSE),
'access arguments' => array('access user profiles'),
'type' => MENU_CALLBACK,
);
$items['admin/config/people/masquerade'] = array(
'title' => 'Masquerade',
'description' => 'Masquerade module allows administrators to masquerade as other users.',
'page callback' => 'drupal_get_form',
'page arguments' => array('masquerade_admin_settings'),
'access callback' => 'user_access',
'access arguments' => array('administer masquerade'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
/**
* Implements hook_menu_alter().
*
* We need to add a token to the Masquerade paths to protect against CSRF
* attacks. Since menu items in Drupal do not support dynamic elements these
* tokens need to be added during rendering via masquerade_translated_menu_link_alter().
* Set the 'alter'-option to TRUE to make sure
* the links get passed through masquerade_translated_menu_link_alter.
*/
function masquerade_menu_alter(&$items) {
$default_test_user = _masquerade_user_load(variable_get('masquerade_test_user', ''));
if (isset($default_test_user->uid)) {
$items['masquerade/switch/' . $default_test_user->uid]['options']['alter'] = TRUE;
}
$items['masquerade/switch/%']['options']['alter'] = TRUE;
$items['masquerade/unswitch']['options']['alter'] = TRUE;
}
/**
* Implements hook_translated_menu_link_alter().
*
* Dynamically add the CSRF protection token to the Masquerade menu items.
*/
function masquerade_translated_menu_link_alter(&$item, $map) {
if (isset($item['page_callback'])) {
if ($item['page_callback'] == 'masquerade_switch_user_page' && isset($map[2])) {
$item['localized_options']['query']['token'] = drupal_get_token('masquerade/switch/' . $map[2]);
}
elseif ($item['page_callback'] == 'masquerade_switch_back_page') {
$item['localized_options']['query']['token'] = drupal_get_token('masquerade/unswitch');
}
}
}
/**
* Implements hook_user_operations().
*/
function masquerade_user_operations() {
return array(
'masquerade' => array(
'label' => t('Masquerade as user'),
'callback' => 'masquerade_user_operations_masquerade',
),
);
}
/**
* Callback for user operation.
*/
function masquerade_user_operations_masquerade(array $accounts) {
// Only process the first account since switching to multiple makes no sense.
if (($uid = current($accounts)) && masquerade_menu_access('switch', $uid)) {
masquerade_switch_user($uid);
}
}
/**
* Determine if the current user has permission to switch users.
*
* @param string $type
* Either 'switch', 'unswitch', 'user', or 'autocomplete'.
*
* @param object $uid
* An optional parameter indicating a specific uid to switch to.
* Otherwise, return if the user can switch to any user account.
*
* @return
* TRUE, if the user can perform the requested action, FALSE otherwise.
*/
function masquerade_menu_access($type, $uid = NULL) {
switch ($type) {
case 'unswitch':
return isset($_SESSION['masquerading']) || arg(2) == 'menu-customize' || arg(2) == 'menu';
case 'autocomplete':
return isset($_SESSION['masquerading']) || (user_access('masquerade as user') || user_access('masquerade as admin'));
break;
case 'user':
global $user;
return db_query("SELECT 1 FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))->fetchField();
break;
case 'switch':
$switch_to_account = FALSE;
global $user;
if ($uid) {
if (!is_numeric($uid)) {
return FALSE;
}
if ($account = user_load($uid)) {
$switch_to_account = db_query("SELECT 1 FROM {masquerade_users} WHERE uid_from = :uid_from AND uid_to = :uid_to", array(
':uid_from' => $user->uid,
':uid_to' => $account->uid
))->fetchField();
}
}
return !isset($_SESSION['masquerading']) && (user_access('masquerade as user') || user_access('masquerade as admin') || $switch_to_account);
break;
}
}
/**
* Admin settings form.
*/
function masquerade_admin_settings() {
// create a list of roles; all selected roles are considered administrative.
$roles = user_roles();
$form['masquerade_admin_roles'] = array(
'#type' => 'checkboxes',
'#title' => t('Roles that are considered "administrators" for masquerading'),
'#options' => $roles,
'#default_value' => variable_get('masquerade_admin_roles', array()),
);
$test_name = _masquerade_user_load(variable_get('masquerade_test_user', ''));
$form['masquerade_test_user'] = array(
'#type' => 'textfield',
'#title' => t('Menu <em>Quick Switch</em> user'),
'#autocomplete_path' => 'masquerade/autocomplete',
'#default_value' => isset($test_name->name) ? check_plain($test_name->name) : '',
'#description' => t('Enter the username of an account you wish to switch easily between via a menu item.'),
'#maxlength' => NULL,
);
$quick_switch = user_load_multiple(variable_get('masquerade_quick_switches', array()));
$quick_switch_users = array();
foreach ($quick_switch as $uid => $account) {
if ($uid == 0) {
$account->name = variable_get('anonymous', t('Anonymous'));
}
$quick_switch_users[] = $account->name;
}
$form['masquerade_quick_switches'] = array(
'#type' => 'textfield',
'#title' => t('Masquerade Block <em>Quick Switch</em> users'),
'#autocomplete_path' => 'masquerade/autocomplete-users',
'#default_value' => drupal_implode_tags($quick_switch_users),
'#description' => t('Enter the usernames, separated by commas, of accounts to show as quick switch links in the Masquerade block.'),
'#maxlength' => NULL,
);
$form = system_settings_form($form);
$form['#validate'][] = 'masquerade_admin_settings_validate';
$form['#submit'][] = 'masquerade_admin_settings_submit';
return $form;
}
function masquerade_admin_settings_validate($form, &$form_state) {
if (!empty($form_state['values']['masquerade_test_user'])) {
$test_user = _masquerade_user_load($form_state['values']['masquerade_test_user']);
if (!$test_user) {
form_set_error('masquerade_test_user', t('%user does not exist. Please enter a valid username.', array('%user' => $form_state['values']['masquerade_test_user'])));
}
}
// Needs to rebuild menu in masquerade_admin_settings_submit().
$form_state['masquerade_rebuild_menu'] = (variable_get('masquerade_test_user', '') != $form_state['values']['masquerade_test_user']);
// A comma-separated list of users.
$masquerade_switches = drupal_explode_tags($form_state['values']['masquerade_quick_switches']);
// Change user names to user ID's for system_settings_form_submit() to save.
$masquerade_uids = array();
foreach ($masquerade_switches as $switch_user) {
$test_user = _masquerade_user_load($switch_user);
if (!$test_user) {
form_set_error('masquerade_quick_switches', t('%user does not exist. Please enter a valid username.', array('%user' => $switch_user)));
}
else {
$masquerade_uids[] = $test_user->uid;
}
}
$form_state['values']['masquerade_quick_switches'] = $masquerade_uids;
}
function masquerade_admin_settings_submit($form, &$form_state) {
// Rebuild the menu system so the menu "Quick Switch" user is updated.
if ($form_state['masquerade_rebuild_menu']) {
menu_rebuild();
}
}
/**
* Wrapper around user_load() to allow the loading of anonymous users.
*
* @param $username
* The username of the user you wish to load (i.e. $user->name). To load the
* anonymous user, pass the value of the 'anonymous' variable.
*
* @return
* A fully-loaded $user object upon successful user load or FALSE if user
* cannot be loaded.
*/
function _masquerade_user_load($username) {
$account = FALSE;
if (!empty($username)) {
$anon = variable_get('anonymous', t('Anonymous'));
$account = user_load_by_name(($username == $anon ? '' : $username));
if (isset($account->uid) && empty($account->uid)) {
// Anonymous user should have a name.
$account->name = $anon;
}
}
return $account;
}
/**
* Implements hook_user_logout().
*/
function masquerade_user_logout($account) {
if (!empty($account->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);
$query = db_delete('masquerade');
$query->condition('sid', session_id());
$query->condition('uid_as', $account->uid);
$query->execute();
}
}
/**
* Implements hook_field_extra_fields().
*/
function masquerade_field_extra_fields() {
$return['user']['user'] = array(
'form' => array(
'masquerade' => array(
'label' => t('Masquerade'),
'description' => t('User masquerade settings.'),
'weight' => 50,
),
),
'display' => array(
'masquerade' => array(
'label' => t('Masquerade'),
'description' => t('Masquerade as user link.'),
'weight' => 50,
),
),
);
return $return;
}
/**
* Implements hook_user_view().
*/
function masquerade_user_view($account, $view_mode, $langcode) {
// check if user qualifies as admin
$roles = array_keys(array_filter(variable_get('masquerade_admin_roles', array())));
$perm = $account->uid == 1 || array_intersect(array_keys((array)$account->roles), $roles) ?
'masquerade as admin' :
'masquerade as user';
global $user;
// Query allowed uids so the "masquerade as <user>" link can be shown or
// hidden.
$allowed_uids = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))
->fetchCol();
$can_masquerade_as_user = in_array($account->uid, $allowed_uids) || user_access('masquerade as any user');
if (user_access($perm) && empty($account->masquerading) && $user->uid != $account->uid && $can_masquerade_as_user) {
$account->content['masquerade'] = array(
'#markup' => l(t('Masquerade as !user', array('!user' => $account->name)),
'masquerade/switch/' . $account->uid,
array('query' => array(
'token' => drupal_get_token('masquerade/switch/' . $account->uid)),
'destination' => $_GET['q'],
'attributes' => array('class' => array('masquerade-switch')),
)),
'#weight' => 10,
);
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function masquerade_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
if ($form['#user_category'] != 'account') {
// Do not show this form for different categories.
return;
}
$form['masquerade'] = array(
'#type' => 'fieldset',
'#title' => t('Masquerade settings'),
'#access' => user_access('administer masquerade'),
);
$edit_user = $form['#user'];
$uids = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $edit_user->uid))
->fetchCol();
$users = user_load_multiple($uids);
$masquerade_users = array();
foreach ($users as $uid => $account) {
if ($uid == 0) {
$masquerade_users[] = variable_get('anonymous', t('Anonymous'));
}
else {
$masquerade_users[] = $account->name;
}
}
$form['masquerade']['masquerade_users'] = array(
'#type' => 'textfield',
'#title' => t('Enter the users this user is able to masquerade as'),
'#description' => t('Enter a comma separated list of user names that this user can masquerade as.'),
'#autocomplete_path' => 'masquerade/autocomplete-user',
'#default_value' => drupal_implode_tags($masquerade_users),
'#maxlength' => NULL,
);
$form['#validate'][] = 'masquerade_user_validate';
$form['#submit'][] = 'masquerade_user_submit';
}
/**
* Validates user account form.
*/
function masquerade_user_validate(&$form, $form_state) {
if (isset($form_state['values']['masquerade_users'])) {
$users = drupal_explode_tags($form_state['values']['masquerade_users']);
foreach ($users as $username) {
if (!_masquerade_user_load($username)) {
form_set_error('masquerade_users', t('%user is not a valid user name.', array('%user' => $username)));
}
}
}
}
/**
* Submit handler for masquerade users form element.
*/
function masquerade_user_submit(&$form, $form_state) {
global $_masquerade_old_session_id;
$_masquerade_old_session_id = session_id();
}
/**
* Implements hook_user_update().
*/
function masquerade_user_update(&$edit, $account, $category) {
global $_masquerade_old_session_id;
if ($category == 'account' && isset($edit['masquerade_users'])) {
$query = db_delete('masquerade_users');
$query->condition('uid_from', $account->uid);
$query->execute();
// Save users from settings form.
$users = drupal_explode_tags($edit['masquerade_users']);
$query = db_insert('masquerade_users')->fields(array('uid_from', 'uid_to'));
foreach ($users as $username) {
if ($to_user = _masquerade_user_load($username)) {
$query->values(array(
'uid_from' => $account->uid,
'uid_to' => $to_user->uid,
));
}
}
$query->execute();
$edit['masquerade_users'] = NULL;
// Update user session...
// @TODO check other way of session API.
if (!empty($_masquerade_old_session_id)) {
$query = db_update('masquerade');
$query->fields(array(
'sid' => session_id(),
));
$query->condition('sid', $_masquerade_old_session_id);
$query->execute();
}
}
}
/**
* Implements hook_user_delete().
*/
function masquerade_user_delete($account) {
// Cleanup tables.
$query = db_delete('masquerade_users');
$conditions = db_or();
$conditions->condition('uid_from', $account->uid);
$conditions->condition('uid_to', $account->uid);
$query->condition($conditions);
$query->execute();
// Cleanup variables.
$switches = variable_get('masquerade_quick_switches', array());
$switches_new = array_diff($switches, array($account->uid));
if ($switches != $switches_new) {
variable_set('masquerade_quick_switches', $switches_new);
// @TODO Implement block cache cleaning.
menu_rebuild();
}
}
/**
* Implements hook_block_info().
*/
function masquerade_block_info() {
$blocks = array();
$blocks['masquerade'] = array(
'info' => t('Masquerade'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function masquerade_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'masquerade':
if (isset($_SESSION['masquerading']) || (user_access('masquerade as user') || user_access('masquerade as admin'))) {
$block['subject'] = t('Masquerade');
$block['content'] = drupal_get_form('masquerade_block_1');
}
break;
}
return $block;
}
/**
* Masquerade block form.
*/
function masquerade_block_1() {
global $user;
$quick_switch_links = array();
$markup_value = '';
if (isset($_SESSION['masquerading'])) {
$quick_switch_links[] = l(t('Switch back'), '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('Enter the username to masquerade as.');
$form['masquerade_user_field'] = array(
'#prefix' => '<div class="container-inline">',
'#type' => 'textfield',
'#size' => '18',
'#default_value' => '',
'#autocomplete_path' => 'masquerade/autocomplete',
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Go'),
'#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;
}
/**
* Masquerade block form validation.
*/
function masquerade_block_1_validate($form, &$form_state) {
global $user;
//unset($form);
$name = $form_state['values']['masquerade_user_field'];
$allowed = FALSE;
$to_uid = db_select('users', 'u')
->fields('u', array('uid'))
->condition('u.name', $name, '=')
->execute()
->fetchField();
if ($to_uid !== FALSE) {
$allowed = user_access('masquerade as any user') ||
db_select('masquerade_users', 'm')
->fields('m', array('uid_to'))
->condition('m.uid_to', $to_uid, '=')
->condition('m.uid_from', $user->uid, '=')
->execute()
->fetchField();
}
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')))))));
}
if ($to_uid && $allowed === FALSE) {
form_set_error('masquerade_user_field', t('You are not allowed to masquerade as the selected user.'));
}
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
))->fetchObject();
if (isset($alt_login->name)) {
$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'])));
}
elseif ($masq_user->uid == $user->uid) {
form_set_error('masquerade_user_field', t('You cannot masquerade as yourself. Please choose a different user to masquerade as.'));
}
elseif (variable_get('maintenance_mode', 0) && !user_access('access site in maintenance mode', $masq_user)) {
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'))));
}
else {
$form_state['values']['masquerade_user_field'] = $name;
}
}
/**
* Masquerade block form submission.
*/
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();
}
else {
drupal_goto($_SERVER['HTTP_REFERER']);
}
}
/**
* Returns JS array for Masquerade autocomplete fields.
*/
function masquerade_autocomplete($string) {
$matches = array();
// Anonymous user goes first to be visible for user.
$anonymous = variable_get('anonymous', t('Anonymous'));
if (stripos($anonymous, $string) === 0) {
$matches[$anonymous] = $anonymous;
}
// Other suggestions.
$result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER(:string)", 0, 10, array(
':string' => $string . '%',
));
foreach ($result as $user) {
$matches[$user->name] = check_plain($user->name);
}
if (module_exists('devel')) {
$GLOBALS['devel_shutdown'] = FALSE;
}
drupal_json_output($matches);
}
/**
* Returns JS array for Masquerade autocomplete fields.
*
* Supports multiple entries separated by a comma.
*
* @param $string
* 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.
$users_typed = drupal_explode_tags($string);
// Fetch last string.
$last_string = drupal_strtolower(array_pop($users_typed));
if ($last_string) {
$prefix = count($users_typed) ? implode(', ', $users_typed) . ', ' : '';
if ($add_anonymous) {
// Anonymous user goes first to be visible for user.
$anonymous = variable_get('anonymous', t('Anonymous'));
if (stripos($anonymous, $last_string) === 0) {
$matches[$prefix . $anonymous] = $anonymous;
}
}
// Other suggestions.
$result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE :string", 0, 10, array(
':string' => $last_string . '%',
));
foreach ($result as $user) {
$matches[$prefix . $user->name] = check_plain($user->name);
}
// Remove existing tags.
$matches = array_diff($matches, $users_typed);
// @todo Check compatibility for D7.
if (module_exists('alt_login')) {
$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(
':string' => $last_string . '%',
));
foreach ($result as $user) {
$matches[$user->alt_login] = check_plain($user->alt_login);
}
}
}
if (module_exists('devel')) {
$GLOBALS['devel_shutdown'] = FALSE;
}
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_goto($_SERVER['HTTP_REFERER']);
}
else {
drupal_access_denied();
}
}
/**
* Allows a user with the right permissions to become the selected user.
*
* @param $uid
* The user ID to switch to.
*
* @return
* TRUE if the user was sucessfully switched, or FALSE if there was an error.
*/
function masquerade_switch_user($uid) {
global $user;
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);
return drupal_goto($_SERVER['HTTP_REFERER']);
}
$new_user = user_load($uid);
$roles = array_keys(array_filter(variable_get('masquerade_admin_roles', array())));
$perm = $uid == 1 || array_intersect(array_keys($new_user->roles), $roles) ?
'masquerade as admin' :
'masquerade as user';
// Check to see if we need admin permission.
$results = db_query_range('SELECT 1 FROM {masquerade_users} WHERE uid_from = :uid_from AND uid_to = :uid_to', 0, 1, array(
':uid_from' => $user->uid,
':uid_to' => $new_user->uid,
));
if (!user_access($perm) && !isset($_SESSION['masquerading']) && !$results->fetchField()) {
watchdog('masquerade', 'This user requires administrative permissions to switch to the user %user.', array('%user' => $new_user->name), WATCHDOG_ERROR);
return FALSE;
}
if ($user->uid == $uid || isset($user->masquerading)) {
watchdog('masquerade', 'This user is already %user.', array('%user' => $new_user->name), WATCHDOG_ERROR);
return FALSE;
}
if (variable_get('maintenance_mode', 0) && !user_access('access site in maintenance mode', $new_user)) {
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'))));
return FALSE;
}
// Call logout hooks when switching from original user.
module_invoke_all('user_logout', $user);
drupal_session_regenerate();
$query = db_insert('masquerade');
$query->fields(array(
'uid_from' => $user->uid,
'uid_as' => $new_user->uid,
'sid' => session_id(),
));
$query->execute();
// switch 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;
// Call all login hooks when switching to masquerading user.
$edit = array(); // Passed by reference.
user_module_invoke('login', $edit, $user);
return TRUE;
}
/**
* Allows a user who is currently masquerading to become a new user.
*/
function masquerade_switch_back_page() {
if (isset($_GET['token']) && drupal_valid_token($_GET['token'], 'masquerade/unswitch')) {
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_goto($_SERVER['HTTP_REFERER']);
}
else {
drupal_access_denied();
}
}
/**
* Function for a masquerading user to switch back to the previous user.
*/
function masquerade_switch_back() {
// switch user
global $user;
cache_clear_all($user->uid, 'cache_menu', TRUE);
$uid = db_query("SELECT m.uid_from FROM {masquerade} m WHERE m.sid = :sid AND m.uid_as = :uid_as ", array(
':sid' => session_id(),
':uid_as' => $user->uid,
))->fetchField();
// erase record
db_delete('masquerade')
->condition('sid', session_id())
->condition('uid_as', $user->uid)
->execute();
$oldname = ($user->uid == 0 ? variable_get('anonymous', t('Anonymous')) : $user->name);
// Call logout hooks when switching from masquerading user.
module_invoke_all('user_logout', $user);
drupal_session_regenerate();
$user = user_load($uid);
// Call all login hooks when switching back to original user.
$edit = array(); // Passed by reference.
user_module_invoke('login', $edit, $user);
watchdog('masquerade', 'User %user no longer masquerading as %masq_as.', array('%user' => $user->name, '%masq_as' => $oldname), WATCHDOG_INFO);
}
@@ -0,0 +1,73 @@
<?php
/**
* @file
* masquerade.test
*
* Test the form permissions and switch ability of the Masquarade module.
*/
class MasqueradeTestCase extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'Masquerade tests',
'description' => 'Tests user switching with the Masquerade module.',
'group' => 'Masquerade',
);
}
public function setUp() {
parent::setUp('masquerade');
}
public function testMasquerade() {
$admin_perms = array(
'administer site configuration',
'administer permissions',
'administer blocks',
'administer masquerade',
'administer users',
'access user profiles',
'masquerade as user',
'masquerade as any user',
);
$admin = $this->drupalCreateUser($admin_perms);
$user = $this->drupalCreateUser();
$this->drupalLogin($admin);
// Test accessing the admin form
$this->drupalGet('admin/config/people/masquerade');
$this->assertText(t('Roles that are considered "administrators" for masquerading'));
// Test enabling the Masquerade block
$this->drupalGet('admin/structure/block/manage/masquerade/masquerade/configure');
$this->assertText(t("'@module' block", array('@module' => 'Masquerade')));
$edit = array(
'regions[bartik]' => 'content',
'regions[seven]' => 'content',
);
$this->drupalPost('admin/structure/block/manage/masquerade/masquerade/configure', $edit, t('Save block'));
$this->assertText(t('The block configuration has been saved.'));
// Test switch from user profile
$this->drupalGet("user/{$user->uid}");
$this->clickLink(t('Masquerade as @name', array('@name' => $user->name)));
$this->assertText(t('You are now masquerading as @name.', array('@name' => $user->name)));
// Test unswitch
$this->drupalGet('');
$this->clickLink(t('Switch back'));
$this->assertText(t('You are no longer masquerading as @name and are now logged in as @admin.',
array('@name' => $user->name, '@admin' => $admin->name)));
// Test switch from masquerade block
$edit = array(
'masquerade_user_field' => $user->name,
);
$this->drupalPost('', $edit, t('Go'));
$this->assertText(t('You are now masquerading as @name.', array('@name' => $user->name)));
}
}