Wednesday, May 21, 2014

Drupal CMS - Creating sub-administrators that can view or edit a restricted set of users

I had the need to create a couple of sub-administrator roles on a Drupal web site.  These sub-administrators needed to be able to view and/or edit a restricted set of users (for example, for customer support purposes). However, these sub-admins could not have 'administrator' privileges at all beyond the limited access to some users. They also needed to be able to search for users (only users they were permitted to view).

I developed a Drupal extension (i.e. module) to implement this.  Thinking the implementation methods might be useful to others, I created this blog (I'll look into submitting it to the Drupal.org module repository at some point in the future if I get the time) .

Disclaimer:  This blog contains software (code), and instructions.  All information is provided "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.  In no event shall the author be liable for any indirect, special, incidental or consequential damages or lost profits arising out of the use or inability to use this information.

License: Any code in this publication is released to the public under the terms of the 'GNU General Public License', a copy of which is attached at the end of this blog.

Note: This is a long post.  Most likely you will need the click the 'Read More' link at the bottom of the page to see the complete post.

1         Overview



This module creates two user roles called 'subadmin-level-2' and 'subadmin-level-3'.  Users with these roles have some limited power to administer users (based on the settings of this module) but do not have other powers that administrators have.  These sub-admins may be non-technical people.

At present the administrative powers granted are as follows.  These are configurable except as noted:


  1. View regular (non-administrator, non-sub-administrator) user data  (if enabled in permissions)
  2. View user data of sub-administrators below their level (if enabled in permissions)
  3. View user data of sub-administrators at the same level (if enabled in permissions)
  4. View user data of blocked users  (if enabled in permissions)
  5. Search for users based on a pattern (searches username and email address). Search results are limited to those who they can view based on above permissions.
  6. Edit regular user (non-administrator, non-sub-administrator) user data (if enabled in permissions)
  7. Edit user data of sub-administrators below their level (if enabled in permissions). Editing of peers is not permitted.
  8. Edit user data of blocked users (if enabled in permissions)

Only the administrator should configure any permissions and settings for this module.  Permissions are set via [administration -> modules -> this module -> Permissions].   There are no settings to configure for this module - only permissions.


EXTRAS: If user accounts have ‘first name’ and ‘last name’ fields defined with the following machine-names (these can be added via [Administration -> Configuration -> Account Settings -> Manage Fields]), then this information is also displayed in user search results:

    field machine name (exact)                     Used for

    field_user_firstname                               First name of user

    field_user_lastname                                Last name of user


POWER LEVELS OF DIFFERENT ROLES: The power levels of different roles are in the following order, with 'administrator' being the highest:

   - administrator

   - subadmin-level-2

   - subadmin-level-3

   - ordinary users (i.e. other users)


This module does not modify or influence the permissions of any users other than sub-admins.


MULTIPLE SUB-ADMIN ROLES:  Assigning multiple sub-admin roles to a user is not recommended.  In case you need to do this, keep the following in mind: the module will use the highest power sub-admin role when determining permissions (both for the current user as well as the target user account being viewed / edited).


UNINSTALL NOTES: When this module is uninstalled, it removes the sub-admin roles from the site.  Any users who were assigned sub-admin roles will get 'demoted' to ordinary users but will remain in the system.

PHILOSOPHY: There are two ways to accomplish a sub-administrator type role:
  • place them in an administrator role (which gives them permission to do anything) and then take away permissions you do not want them to have,
  • place them in a non-administrator role, and then give them additional permissions to do certain things.

This module attempts to do the latter.  However, given that they do not have admin permissions to begin with, it is necessary to 'hook' into the core to do this.  By default, Drupal 7.X does not allow access to user data by anyone other than the administrator.  There is no 'hook' that can be used by a module to allow non-administrators to access user data (AFAIK).  Hence, minor (in terms of lines of change) modifications are necessary to the core to allow limited access in a controlled way to sub-admins.  Hence the warning:


CORE MODIFICATIONS:     This module requires some core modifications in order for it to work.  See INSTALL.txt file (shown at the end) for details.  Use it at your own discretion.   Specifically, the core function user_view_access() and user_edit_access() have to be modified to call similar functions in this module that will allow non-admins to view or edit user data (based on settings for this module).




If you upgrade the core, remember to re-apply the core modifications.  Make sure to backup the file before doing any modifications (copy file xxx.yyy to xxx.yyy.orig).


2         Design


The design notes assume that the reader is at least reasonably familiar with developing Drupal modules.

2.1      Database


A single database table is created called ‘subadmin_roles’.  The table is deleted when the module in uninstalled.  This table contains a list of sub-admins along with a weight assigned to each, starting with 2.  Roles with a lower weight number are considered to be at a higher level of authority.  

 function subadmin_schema() {
  $t = get_t();
        // Table for subadmin roles
  $schema['subadmin_roles'] = array(
    'description' => 'This table lists the submin roles.',
    'fields' => array(
        'subadmin_role' => array(
            'description' => 'name of subadmin role.',
            'type' => 'varchar',
            'length' => 128,
            'not null' => TRUE,
            'default' => '',
        ),
        'weight' => array(
            'description' => 'weight of the role.',
            'type' => 'int',
            'length' => 11,
            'not null' => TRUE,
            'default' => '2',
        ),
    ),
    'primary key' => array('subadmin_role'),
  );

  //drupal_flush_all_caches();

  return $schema;

}


2.2      Install/Uninstall


During install (actually the first time the module is enabled), the table is created and populated with the roles and weights.  ‘n’ roles are created with a ‘name prefix’ and a number suffix. The number of roles and the prefix can be changed in code only (file ‘subadmin.install’,  function subadmin_install()). Unless the code is modified, it creates two roles ‘subadmin-level-2’ and ‘subadmin-level-3’ with associated weights 2 and 3.  Then iteration is done through this table and these roles created on the site by calling user_role_save().  Caches are flushed at the end of this to be on the safe side.

During uninstall, the new roles created are removed from the site, and the database table ‘subadmin_roles’ is deleted from the database.


 function subadmin_install() {

    // Folowing two lines can be modified to customize the number of levels
    // and influence the names of the sub-admin roles
    $subadmin_role_prefix = 'subadmin-level-';
    $subadmin_role_num_levels = 2;
    // End of module customization section

    $t = get_t();
        // Insert default subadmin roles.  If a new role is required, add it
        // here.  Roles with higher power should have lower weights.
    $subAroles = array();
    for ($i = 1; $i <= $subadmin_role_num_levels; $i++) {
        $subAroles[] = array($subadmin_role_prefix . strval($i+1), ($i+1));  // array( 'subadmin-level-2', 2)
    }

        // Populate table 'subadmin_roles'
    foreach ($subAroles as $subArole) {
        db_insert('subadmin_roles')
            ->fields(array(
                'subadmin_role' => $subArole[0],
                'weight'        => $subArole[1],
            ))
            ->execute();
    }
    //drupal_set_message($t('SubAdmin: Populated subadmin database tables.'), 'status');

        // Now we need to add the subadmin roles to the site.
    $sa_roles = db_query("SELECT subadmin_role FROM {subadmin_roles} ORDER BY weight ASC");
    if (isset($sa_roles)) {
        $user_error = false;
        foreach ($sa_roles as $sa_role) {               // for each role in 'subadmin_roles' table, add role
            //$checkrole = user_role_load_by_name($sa_role->subadmin_role);
            //if (isset($checkrole->rid))
            if (user_role_load_by_name($sa_role->subadmin_role)) {
                drupal_set_message('SubAdmin: ' . $t('Error: ') . $t('User role ') . $sa_role->subadmin_role .
                        $t(' already exists. Please disable this module (if not already disabled).  ') .
                        $t('After that, remove this user role manually, then uninstall the module, and re-install it again.'), 'error');
                $user_error = true;
            }
            else {
                $newrole = new stdClass();
                $newrole->name = $sa_role->subadmin_role;
                $newrole->weight = 3;
                $newrole->rid = NULL;
                $rc = user_role_save($newrole);
                if ($rc == FALSE)
                    { drupal_set_message('SubAdmin: ' . $t('Error: Could not add sub-administrator role \'') . $sa_role->subadmin_role . '\'', 'status');}
                elseif ($rc == SAVED_NEW)
                    { drupal_set_message('SubAdmin: ' . $t('Added sub-administrator role \'') . $sa_role->subadmin_role . '\'', 'status');}
                elseif ($rc == SAVED_UPDATED)
                    { drupal_set_message('SubAdmin: ' . $t('Updated sub-administrator role \'') . $sa_role->subadmin_role . '\'', 'status');}
                unset($newrole);
            }
        }
        if ($user_error == true) {
            module_disable(array('subadmin'));
            return;
        }
    }
    else { drupal_set_message('SubAdmin: ' . $t('Internal error '), 'error'); }
    drupal_set_message($t('SubAdmin: This module requires core modifications for it to work.  See the INSTALL.txt file for details.'),'warning');

    drupal_set_message(  $t('SubAdmin: Make sure to <a href="!subadmin_permissions">review/modify ' .
                            'the permissions</a> for the SubAdmin module such as \'allow sub-admins to view non-sub-admins\'.',
                            //array('!subadmin_permissions' => url('/admin/people/permissions',array(),'module-subadmin'))
                            array('!subadmin_permissions' => url('/admin/people/permissions\#module-subadmin'))
                           ),
                         'warning'
                      );

    drupal_flush_all_caches();
}



function subadmin_uninstall() {
    $t = get_t();

        // Now we need to remove the subadmin roles to the site.
    $sa_roles = db_query("SELECT subadmin_role FROM {subadmin_roles}");
    if (isset($sa_roles)) {
        foreach ($sa_roles as $sa_role) {               // for each role in 'subadmin_roles' table, add role

            if (user_role_load_by_name($sa_role->subadmin_role)) {
                drupal_set_message('SubAdmin: ' . $t('Removing sub-administrator role \'') . $sa_role->subadmin_role . '\'', 'status');
                user_role_delete($sa_role->subadmin_role);              // no return code
                if (user_role_load_by_name($sa_role->subadmin_role)) {
                   drupal_set_message('SubAdmin: ' . $t('Warning: ') . $t('Role ') . $sa_role->subadmin_role . $t(' could not be deleted.'), 'warning');
                }
            }
            else {
                drupal_set_message('SubAdmin: ' . $t('Warning: ') . $t('Role ') . $sa_role->subadmin_role . $t(' not found.'), 'warning');
            }
        }
    }
    else { drupal_set_message('SubAdmin: ' . $t('Internal error '), 'error'); }

    drupal_set_message($t('SubAdmin: Deleting database schema.'), 'status');
    drupal_uninstall_schema('subadmin');

    drupal_set_message($t('SubAdmin: Deleting variables.'), 'status');
    db_query("DELETE FROM {variable} WHERE name LIKE 'subadmin_%'");
    cache_clear_all('variables', 'cache');

        // Determine location of this module's files
    $module_dir_fp = dirname(__FILE__);
    $site_dir = getcwd();
    $module_dir_rp = str_replace($site_dir, ' ' , $module_dir_fp);
    drupal_set_message($t('SubAdmin: You can now optionally remove the ') . $module_dir_rp . $t(' directory manually to remove the module from the modules list.'), 'status');

    drupal_flush_all_caches();
}

2.3      Upgrades


If an upgrade is needed, the administrator needs to a) first capture the list of users that are sub-admins along with their sub-admin roles, b) uninstall, c) replace the module files, d) re-enable the module to fully install it, and e) restore the sub-admin roles to the appropriate users.

2.4      Enable/Disable


This module does nothing when it is disabled, or enabled subsequently.

2.5      Operation


2.5.1    Permissions


The permissions that can be configured by the administrator for the module are specified by the function ‘subadmin_permission()’ which hooks into ‘hook_permission()’.  Each permission is an associative array of ‘permission id’ (as used in code) associated with a title and description that is shown on the permissions settings page.


function subadmin_permission() {
  return array(

        // view permissions

    'subadmin permissions - view user data of non-sub-admin users'  => array(
      'title' => t('View user data of non-sub-admin users'),
      'description' => t('Allow sub-admins to view user profile data of non-sub-amin users'),
    ),

    'subadmin permissions - view user data of lower level subadmins'  => array(
      'title' => t('View user data of lower level subadmins'),
      'description' => t('Allow sub-admins to view user profile data of other sub-admins who are at a lower level'),
    ),

    'subadmin permissions - view user data of peers'  => array(
      'title' => t('View user data of peers'),
      'description' => t('Allow sub-admins to view user profile data of other sub-admins who are at the same level'),
    ),

    'subadmin permissions - view user data of blocked users'  => array(
      'title' => t('View user data of blocked users'),
      'description' => t('Allow sub-admins to view user profile data of blocked users'),
    ),

        // edit permissions

    'subadmin permissions - edit user data of non-sub-admin users'  => array(
      'title' => t('Edit user data of non-sub-admin users'),
      'description' => t('Allow sub-admins to edit user profile data of non-sub-amin users') .
                         t(' - WARNING: Give to trusted users only - this permission has security implications'),
    ),

    'subadmin permissions - edit user data of lower level subadmins'  => array(
      'title' => t('Edit user data of lower level subadmins'),
      'description' => t('Allow sub-admins to edit user profile data of other sub-admins who are at a lower level') .
                         t(' - WARNING: Give to trusted users only - this permission has security implications'),
    ),

    'subadmin permissions - edit user data of blocked users'  => array(
      'title' => t('Edit user data of blocked users'),
      'description' => t('Allow sub-admins to edit user profile data of blocked users') .
                         t(' - WARNING: Give to trusted users only - this permission has security implications'),
    ),

  );
}

2.5.2    View and Edit access implementation


We provide two module functions - subadmin_user_view_access($target_account) and subadmin_user_edit_access($target_account) - that will allow the user to access the target account based on the permissions settings for the module.  The core function user_view_access($target_account) and user_edit_access($target_account) have to be modified to call these functions if the module exists.  If the module functions permit access by returning TRUE, then the user is allowed access; else normal processing occurs within the core functions.

With these two functions in place, a sub-admin can access a user’s page (if permitted) by going to ‘site/user/n’ or ‘site/user/n/edit’ where n is the users ‘uid’ number.


function subadmin_user_view_access($target_account) {

    $target_uid = is_object($target_account) ? $target_account->uid : (int) $target_account;

        // Anonymous user accounts do not exist
    if ($target_uid == 0) return FALSE;

        // At this point, load the complete account object.
    if (!is_object($target_account)) { $target_account = user_load($target_uid); }
    if (!is_object($target_account)) return FALSE;

        // Leave administrators permissions to the core function
    if (in_array('administrator', $target_account->roles)) return FALSE;

        // If viewing of blocked users is not enabled in subadmin module, leave it to the core function
    if ($target_account->status != 1) {
         if (!(user_access('subadmin permissions - view user data of blocked users')))  // I have permissions to view blocked users
                return FALSE;
    }

    $tgt_sa_role = subadmin_subadmin_role($target_account);
    $my_sa_role  = subadmin_subadmin_role();
    //drupal_set_message('tgt Status=' . $tgt_sa_role['status'] . ' role=' . $tgt_sa_role['role'] . ' weight=' . $tgt_sa_role['weight'] . '<br>' , 'status');

        // if the target is a non-subadmin, and the user is a subadmin, and user has the permissions to view non-subadmin users, allow
    if  (   ($tgt_sa_role['status'] != 1)                                                       // if target is a non-subadmin
         && ($my_sa_role ['status'] == 1)                                                       // && I am a sub-admin
         && (user_access('subadmin permissions - view user data of non-sub-admin users'))       // && I have permissions to view non-subadmins
        )  return TRUE;

        // if the target is a sub-admin at a lower level than me, allow me to view
    if  (   ($tgt_sa_role['status'] == 1)                                                       // if target is a subadmin
         && ($my_sa_role ['status'] == 1)                                                       // and I am a subadmin
         && ($my_sa_role ['weight'] < $tgt_sa_role ['weight'])                                  // && I am a higher level subadmin
         && (user_access('subadmin permissions - view user data of lower level subadmins'))     // && I have permissions to view lower level subadmins
        )  return TRUE;

        // if the target is a sub-admin at same level as me, allow me to view if I have permission to view peers
    if  (   ($tgt_sa_role['status'] == 1)                                                       // if target is a subadmin
         && ($my_sa_role ['status'] == 1)                                                       // and I am a subadmin
         && ($my_sa_role ['weight'] == $tgt_sa_role ['weight'])                                 // && I am a peer (at same level)
         && (user_access('subadmin permissions - view user data of peers'))                     // && I have permissions to view peers
        )  return TRUE;

    return FALSE;
}

function subadmin_user_edit_access($target_account) {

    $target_uid = is_object($target_account) ? $target_account->uid : (int) $target_account;

        // Anonymous user accounts do not exist
    if ($target_uid == 0) return FALSE;

        // At this point, load the complete account object.
    if (!is_object($target_account)) { $target_account = user_load($target_uid); }
    if (!is_object($target_account)) return FALSE;

        // Leave administrators permissions to the core function
    if (in_array('administrator', $target_account->roles)) return FALSE;

        // If viewing of blocked users is not enabled in subadmin module, leave it to the core function
    if ($target_account->status != 1) {
         if (!(user_access('subadmin permissions - edit user data of blocked users')))  // I have permissions to view blocked users
                return FALSE;
    }

    $tgt_sa_role = subadmin_subadmin_role($target_account);
    $my_sa_role  = subadmin_subadmin_role();
    //drupal_set_message('tgt Status=' . $tgt_sa_role['status'] . ' role=' . $tgt_sa_role['role'] . ' weight=' . $tgt_sa_role['weight'] . '<br>' , 'status');

        // if the target is a non-subadmin, and the user is a subadmin, and user has the permissions to edit non-subadmin users, allow
    if  (   ($tgt_sa_role['status'] != 1)                                                       // if target is a non-subadmin
         && ($my_sa_role ['status'] == 1)                                                       // && I am a sub-admin
         && (user_access('subadmin permissions - edit user data of non-sub-admin users'))       // && I have permissions to view non-subadmins
        )  return TRUE;

        // if the target is a sub-admin at a lower level than me, allow me to edit if I have the permissions to do so
    if  (   ($tgt_sa_role['status'] == 1)                                                       // if target is a subadmin
         && ($my_sa_role ['status'] == 1)                                                       // and I am a subadmin
         && ($my_sa_role ['weight'] < $tgt_sa_role ['weight'])                                  // && I am a higher level subadmin
         && (user_access('subadmin permissions - edit user data of lower level subadmins'))     // && I have permissions to view non-subadmins
        )  return TRUE;

    return FALSE;
}

2.5.3    API to check if a user has a sub-admin role


The module provides an API subadmin_subadmin_role($account = NULL) to check if a given user has a sub-admin role.  If the $account parameter is omitted, the function returns the information for the caller.  The return information indicates a) if the user is a sub-admin, and if yes, b) the highest sub-admin role for the user and c) the associated weight of that role.


 function subadmin_subadmin_role($account = NULL) {

    $AdmnUser = array('status' => 0, 'role' => 'administrator'     , 'weight' =>    1);
    $AuthUser = array('status' => 0, 'role' => 'authenticated user', 'weight' =>  999);
    $AnonUser = array('status' => 0, 'role' => 'anonymous user'    , 'weight' => 9999);

    if ($account == NULL) $account =  $GLOBALS['user'];
    if (!is_object($account)) return $AnonUser;
    if (!($account->uid)) return $AnonUser;

        // account exists
    $highest_role = $AuthUser;                  // init return value
        // load account
    $uid = $account->uid;
    $account = user_load($uid);
    $roles = $account->roles;

    if (in_array('administrator', $roles)) return $AdmnUser;    // admin special case

        // determine user's most powerful role
    $subadmin_rows = db_query("SELECT * FROM {subadmin_roles} ORDER BY weight ASC");
    foreach ($subadmin_rows as $this_subadmin_row) {
        if (in_array($this_subadmin_row->subadmin_role, $roles)) {
            if ($this_subadmin_row->weight <  $highest_role['weight']) {
                 $highest_role['status'] = 1;
                 $highest_role['role']   = $this_subadmin_row->subadmin_role;
                 $highest_role['weight'] = $this_subadmin_row->weight;
            }
        }
    }
    //print('status = ' . $highest_role['status'] . ' role  =  ' .  $highest_role['role'] .
    //   ' weight = ' . $highest_role['weight'] . '<br>');

    return $highest_role;
}



2.5.4    User Search page


We add a user search page and a menu item to go to that page for sub-admins and administrator by hooking on to ‘hook_menu’ using ‘subadmin_menu’.

The access to the user search page is limited via the function sa_user_search_page_access_control().

The page itself is rendered via the function sa_user_search_page() which outputs a string.  The output consists of a) preamble text, b) a rendered form, and c) the search results.   The search is done based on the pattern, sort-by field and sort-order specified in the form.   The pattern, sort-by field and sort-order are initially null on first entry into page.  After the user clicks on the ‘Search’ button, these values are stored in a session data structure, and the page is redisplayed using the stored values.


 function subadmin_menu() {
    $items['sa/user/search'] =
        array(
            'title'           => 'Users',
            'description'     => t('View/edit user profile data'),
            'menu_name'       => 'main-menu',
            'page callback'   => 'sa_user_search_page',
            'access callback' => 'sa_user_search_page_access_control',
            //'type'          => MENU_CALLBACK,
        );
    return $items;
}

 function sa_user_search_page_access_control() {

        // limit access to the sa_user_search_page to subadmins and administrator
    global $user;
    $my_sa_role  = subadmin_subadmin_role();
    if ($my_sa_role['status'] == 1)                             // if user is a subadmin, show in menu
        return TRUE;
    if ($user->uid) {                                           // let administrator also have this menu item
        $account = user_load($user->uid);
        if (in_array('administrator', $account->roles)) return TRUE;
    }
    return FALSE;
}


 function sa_user_search_page() {

    // drupal_set_title('Different_title_if_desired');
    $output  = sa_user_search_page_preamble();          // show any preamble text for page
    $form    = drupal_get_form('sa_user_search_form');
    $output .= drupal_render($form);                    // search show form

        // search results are displayed based on the settings on the form
        // when the form was submitted by pressing the Search button.
        // At form submission, the settings are stored in the $_SESSION global
        // at index ['subadmin] and the page is refetched. Retrieve them here.
    $spattern=''; $ssort_by = ''; $ssort_order = '';    // init
    $search_settings = isset($_SESSION['subadmin']) ? $_SESSION['subadmin'] : array();
    foreach ($search_settings as $index => $filter) {
        list($key, $value) = $filter;
        //print ($key . ' ' . $value . '<br>');
        switch ($key) {
                case 'search_pattern'   : $spattern = $value; break;
                case 'search_sort_by'   : $ssort_by = $value; break;
                case 'search_sort_order': $ssort_order = $value; break;
                default: break;
        }
    }
    //$_SESSION['subadmin'] = array();                  // reset since we retrieved settings
    unset($_SESSION['subadmin']);                       // reset since we retrieved settings

    //print ('pattern='.$spattern.' sortby='.$ssort_by.' sortorder='.$ssort_order.'<br>');
    if (($ssort_order != 'asc') && ($ssort_order != 'desc'))
        return $output;                                 // test to see if this was first entry on to page

    $output .= sa_user_search_form_results($spattern, $ssort_by, $ssort_order); // add results of search

    return $output;
}
function sa_user_search_page_preamble() {
    //return t('<p>Example <a href="@link1">Page1</a></p> <p>Example<a href="@link2">Page2</a></p>',
    //          array( '@link1' => url('example/page1'), '@link2' => url('example/page2')));
    //return 'Enter a pattern to search for in username or email address.';
    return '';
}

2.5.5    User Search page form


The search page form has the following fields: a) the search pattern, b) the sort-by field that specifies which column to sort by, and c) the sort-order (ascending or descending).

The sort-order drop-down needs to include the ‘first name’ and ‘last name’ attributes of the user if the site includes the fields for that user.  A check is done if these exist (by looking at the user’s own attributes) and these are included as appropriate.

The fields are initialized with values from the last search, except for the pattern field which is set to null string.

There is a function to validate the search form upon submittal, but no validation is done at present.

When the form is submitted, the values in the form are stored in a session data structure and the page is re-displayed.  The re-display uses the values stored in the session data structure to do the search and display the results.

function sa_user_search_form($form, $form_state) {
        // check if admin implemented the 'extras' fields - first, or last names; we add to 'Sort by' drop down list
    global $user;
    $myaccount = user_load($user->uid);
    $field_firstname_exists   = field_get_items('user',$myaccount,'field_user_firstname');      // check if field exists
    $field_lastname_exists    = field_get_items('user',$myaccount,'field_user_lastname');       // check if field exists

        // get the previous sort-by and sort-order used (we stored it in $_SESSION during submit)
    $default_pattern = '' ; $default_sort_by = 'name'; $default_sort_order = 'asc';     // init
    $search_settings = isset($_SESSION['subadmin']) ? $_SESSION['subadmin'] : array();
    foreach ($search_settings as $index => $filter) {
        list($key, $value) = $filter;
        //print ($key . ' ' . $value . '<br>');
        switch ($key) {
                case 'search_pattern'   : $default_pattern    = $value; break;
                case 'search_sort_by'   : $default_sort_by    = $value; break;
                case 'search_sort_order': $default_sort_order = $value; break;
                default: break;
        }
    }
        // Create a list of 'Sort by' fields; add first name / last name if admin added the fields
    $sort_by_fields = array('name' => 'Username', 'status' => 'Status', 'mail' => 'Email Address',);
    if ($field_firstname_exists) $sort_by_fields['firstname'] = 'First name';
    if ($field_lastname_exists ) $sort_by_fields['lastname' ] = 'Last name' ;
    $sort_by_fields['created'] = 'Creation date'; $sort_by_fields['login'  ] = 'Last login'   ;
    $sort_by_fields['access' ] = 'Last access'  ; $sort_by_fields['roles'  ] = 'Roles'        ;
        // Create form
    $form['pattern'] = array(
        '#type'          => 'textfield',
        '#id'            => 'sa-user-search-form-field-pattern',
        '#title'         => t('Pattern'),
        '#default_value' => '',                 // we don't try to remember this one
        //'#placeholder' => 'placeholder', // HTML5 not supported by 7.x core. Use 'elements' module to add support.
                                           // Else install 'plaeholder' module that will support this even for older browsers.
        '#description'   => '<small>' . t('search in username or email address') . '</small>',
        '#size'          => 30,
        '#maxlength'     => 40,
    );
   $form['sort_by'] = array(
        '#type'          => 'select',
        '#id'            => 'sa-user-search-form-field-sort-by',
        '#title'         => t('Sort by'),
        '#options'       => $sort_by_fields,
        '#default_value' => $default_sort_by,
        '#multiple'      => false,
    );
   $form['sort_order'] = array(
        '#type'          => 'select',
        '#id'            => 'sa-user-search-form-field-sort-order',
        '#title'         => t('Sort order'),
        '#options'       => array('asc' => 'Ascending', 'desc' => 'Descending', ),
        '#default_value' => $default_sort_order,
        '#multiple'      => false,
    );
   $form['submit'] = array(
        '#type'          => 'submit',
        '#id'            => 'sa-user-search-form-field-submit',
        '#name'          => 'op',       // same as default
        '#value'         => t('Search'),
    );

    return $form;
}


function sa_user_search_form_validate($form, $form_state) {
        // in case we want to add any validation to the pattern in the future
        // we can implement here
    $patt = $form_state['values']['pattern'];
    //if ($patt != 'xyz') {     // just an example
    //  form_set_error('pattern', t('Pattern invalid'));
    //}
}
 

2.5.6    User Search results


The actual search is performed by the function subadmin_user_search_execute($pattern), which is similar to the core function user_search_execute().   This function will return a list of user’s data.  The data will include ‘first name’ and ‘last name’ fields if they are present (and use the correct machine names for the fields).

The results are then sorted using our own function subadmin_sort_array_of_assoc_arrays_by_column(), which is a general purpose function used to sort an array of associative arrays.

The sorted results are then rendered into a table using the core function ‘theme_table’.   If ‘first name’ and/or ‘last name’ fields are present for users, this information is included in the results.