Skip to main content

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 to 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. 
function sa_user_search_form_submit($form, $form_state) {
        // we store the pattern, sortby and sort_order in $_SESSION
        // for re-use when the page is refreshed via submit
    $_SESSION['subadmin'][] = array ('search_pattern', $form_state['values']['pattern']);
    $_SESSION['subadmin'][] = array ('search_sort_by', $form_state['values']['sort_by']);
    $_SESSION['subadmin'][] = array ('search_sort_order', $form_state['values']['sort_order']);

}

function sa_user_search_form_results($pattern, $sort_by, $sort_order) {
        // check if admin implemented the 'extras' fields - first, or last names
    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

    $output = '<div style="clear:both;"><br>';  // end any floats

    $results = subadmin_user_search_execute($pattern);
    $resultscount = count($results);
    $countmsg = strval($resultscount);
    if ($resultscount == 1) { $countmsg .= ' ' . t('user matches your search.'); }
    else { $countmsg .= ' ' . t('users match your search.'); }
    $output .= $countmsg;
    if ($resultscount == 0) return $resultscount;

    $maxrows=50;            // we don't want to get extended data for too many users, plus then sort it, display it etc.
    if ($resultscount > $maxrows) {
        $output .= '<br><br>' . t('There are too many matching users.') . '&nbsp;&nbsp;' . t('Please narrow your search.');
        $output .= '<br>&nbsp;<br>&nbsp;<br>&nbsp;<br>&nbsp;<br>&nbsp;';
        return $output;
    }
        // sort the results (an array of assocative arrays by the values of the given key)
    subadmin_sort_array_of_assoc_arrays_by_column($results, $sort_by, $sort_order);

    $theme_table_header = array ( t('Username'), t('Status'), t('Email'), );
    if ($field_firstname_exists) $theme_table_header[] = t('First name');
    if ($field_lastname_exists ) $theme_table_header[] = t('Last  name');
    $theme_table_header[] = t('Created'    ); $theme_table_header[] = t('Last Login');
    $theme_table_header[] = t('Last Access'); $theme_table_header[] = t('Roles'     );

    $theme_table_rows = array();
    foreach($results as $auser) {
        if ($auser['status'] == 0) $status_str = 'blocked'; else $status_str = 'active';
        if ($auser['created']>1) $date_created = date("Y-m-d H:i:s",$auser['created']); else $date_created = '-';
        if ($auser['login'  ]>1) $date_login   = date("Y-m-d H:i:s",$auser['login'  ]); else $date_login   = '-';
        if ($auser['access' ]>1) $date_access  = date("Y-m-d H:i:s",$auser['access' ]); else $date_access  = '-';
        $roles_str = ''; foreach ($auser['roles'] as $role) { $roles_str .= '[' . $role . ']'; }
        $name_with_link = '<a href="' . $auser['link'] . '">' . $auser['name'] . '</a>';
        $newrow = array( $name_with_link, $status_str, $auser['mail'],);
        if ($field_firstname_exists) $newrow[] =  $auser['firstname'];
        if ($field_lastname_exists ) $newrow[] =  $auser['lastname' ];
        $newrow[] = $date_created;  $newrow[] = $date_login; $newrow[] = $date_access;  $newrow[] =  $roles_str;

        $theme_table_rows[] = $newrow;
    }
    $output .= theme_table( array('header' => $theme_table_header, 'rows' => $theme_table_rows,
                'attributes' => array('class'=>'table sa-user-search-results-table'), 'caption' => '',
                'colgroups' => array(), 'sticky' => false, 'empty' => '', ));

    return $output;
}

function subadmin_user_search_execute($keys = NULL, $conditions = NULL) {
        // allow only admin and subadmins to use this function
        // also check if the caller is a blocked user
  global $user;
  if ($user->status != 1) { return NULL; }      // if blocked user

  $find = array();
        // Replace wildcards with MySQL/PostgreSQL wildcards.
  $keys = preg_replace('!\*+!', '%', $keys);
  $query = db_select('users')->extend('PagerDefault');
  $query->fields('users', array('uid'));

  //if (user_access('administer users')) {
        // Administrators can also search in the otherwise private email field,
        // and they don't need to be restricted to only active users.
    $query->fields('users', array('mail'));
    $query->condition(db_or()->
      condition('name', '%' . db_like($keys) . '%', 'LIKE')->
      condition('mail', '%' . db_like($keys) . '%', 'LIKE'));
  $uids = $query
    ->limit(15)
    ->execute()
    ->fetchCol();
  $accounts = user_load_multiple($uids);

  $results = array();
  foreach ($accounts as $account) {
    $result = array(
      'title'    => format_username($account),
      'link'     => url('user/' . $account->uid, array('absolute' => TRUE)),
      'name'     => format_username($account),
      'status'   => $account->status,
      'mail'     => $account->mail,
      'created'  => $account->created,
      'login'    => $account->login,
      'access'   => $account->access,
      'roles'    => $account->roles,
    );
    $addl_field_firstname  = field_get_items('user',$account,'field_user_firstname');
        if ($addl_field_firstname) { $result['firstname'] = $addl_field_firstname [0]['value']; }
    $addl_field_middlename  = field_get_items('user',$account,'field_user_middlename');
        if ($addl_field_middlename) { $result['middlename'] = $addl_field_middlename [0]['value']; }
    $addl_field_lastname  = field_get_items('user',$account,'field_user_lastname');
        if ($addl_field_lastname) { $result['lastname'] = $addl_field_lastname [0]['value']; }
    $result['title'] .= ' (' . $account->mail . ')';
        // add only if this user in not anonymous, admin or admin-level-2
    if (user_view_access($account)) {           // is the used can view this account, then add to list
        $results[] = $result;   // add to results set if not one of above
    }
  }

  return $results;
}

function subadmin_sort_array_of_assoc_arrays_by_column(&$origarray, $key, $dir = 'asc') {
        // first build a new assoc array that looks like this (assuming key k2):
        //    colarr = ('0'=>v2, '1'=>v12, '2'=>v22..)
    $index = 0;
    foreach ($origarray as $origarrayrow) {
        $ckey = '\'' . $index . '\'';
        $colarr[$ckey] = $origarrayrow[$key];
        $index++;
    }
    //reset($colarr); while (list($ckey, $cval) = each ($colarr)) { echo "$ckey => $cval <br>"; }

        // Now we sort the array by value
    asort($colarr);     // ascending sort by value
    //reset($colarr); while (list($ckey, $cval) = each ($colarr)) { echo "$ckey => $cval <br>"; }

        // Then we create a new array and place the items in the new order
    $newarrindex = 0;
    reset($colarr); while (list($ckey, $cval) = each ($colarr)) {
            // strip the leading and trailing quotes
        $intckey = (int) substr($ckey,1,strlen($ckey)-2);
        $newarr[$newarrindex] = $origarray[$intckey];
        $newarrindex++;
    }
    if($dir=='desc') $origarray = array_reverse($newarr);
    else $origarray = $newarr;
}

3   INSTALL.txt file

This files describes the core modifications in addition to install / uninstall instructions.
INSTALL.txt file
================
$Id: INSTALL.txt,v 1.2 2014/05/11 09:45:01 gpvdo Exp $

This module requires core modifications that are trivial to do but
that need to be understood well.  Please see the 'Core Modifications'
section at the end.

1. Place this module folder in your DRUPALSITE/sites/all/modules if you want it for all
   the sites in your Drupal installation, or in DRUPALSITE/sites/www.THISSITE.com/modules
   if you want it for a specific site of your multisite installation.

2. Enable this module via [administer > modules].

3. ENSURE THE PERMISSIONS ARE SET PROPERLY!!, usually via:

   [administration -> modules -> this module -> Permissions]

4. Note: There are no module config settings to configure at the present time.

5. This module creates sub-administrator roles that have some powers
   of the 'administrator' role.  After installation, create
   user(s) with these roles.

6. Uninstall

   - Disable the module via [administration -> modules -> this module]
     Uncheck the Enabled checkbox and save configuration.

   - Uninstall the module via [administration -> modules -> Uinstall Tab]
     Click Uinstall checkbox next to this module, click "uninstall" button.

   - Optionally manually remove the module directory if module is to be
     completely removed from the modules list.


CORE MODIFICATIONS
------------------

There are two ways to accomplish a sub-administrator type role:

    a) 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,

    b) 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.  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.

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).

Modification 1 of 2:
   File     : MYSITE/modules/user/user.module
   Function : function user_view_access($account)
   Change   : At the very beginning of the function, add the lines

/**************************************************************************/
/* Modifications that let the subadmin module allow view permissions
 * based on user's role and target account's role. Implemented as a
 * core modification since there is no hook_ capability for this.
 */
if (module_exists('subadmin')) {
  if (subadmin_user_view_access($account))
    return TRUE;
}
/* End of core modification */
/**************************************************************************/


Modification 2 of 2:
   File     : MYSITE/modules/user/user.module
   Function : function user_edit_access($account)
   Change   : At the very beginning of the function, add the lines

/**************************************************************************/
/* Modifications that let the subadmin module allow view permissions
 * based on user's role and target account's role. Implemented as a
 * core modification since there is no hook_ capablity for this.
 */
if (module_exists('subadmin')) {
  if (subadmin_user_edit_access($account))
    return TRUE;
}
/* End of core modification */
/**************************************************************************/
 


4   Donations to Author

If you find this publication useful to you, please feel free to make a donation to the author (amount proportional to the value to you or your organization).



Flattr this


5   GNU Public License


                    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.



Other software blogs from Venu P Gopal






Comments

Popular posts from this blog

Lightweight C++ class library to store program settings (configuration) with Unicode (UTF-8) support

Excel/VBA Example - Sudoku Teaching Assistant