/[drupal]/contributions/modules/advuser/advuser.module
ViewVC logotype

Diff of /contributions/modules/advuser/advuser.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph | View Patch Patch

revision 1.13 by earnie, Sun Sep 30 07:34:57 2007 UTC revision 1.14 by earnie, Mon Jun 9 20:18:56 2008 UTC
# Line 1  Line 1 
1  <?php  <?php
2    /**
3     * @file
4     * Advanced user module allows you to select users based on an advanced set of
5     * filtering and apply actions to block, unblock, delete or email the selected
6     * users.
7     *
8     * $Id: advuser.module,v 1.13.2.11 2008/06/08 17:46:49 earnie Exp $
9     **/
10    
11    // $Id: advuser.module,v 1.12.4.2 2007/06/02 22:45:47 earnie Exp $  /**
12  define('ADVUSER_MODULE_VERSION', '$Id: advuser.module,v 1.12.4.2 2007/06/02 22:45:47 earnie Exp $' );   * @constants
13     */
14  define('ADVUSER_DEFAULT_NEW_MAIL', "User email: %user_email\n\nIf you want to check and edit the account go to %uri.\n\nInvestigate User:\nYahoo search  %user_email: %yahoo_user \nGoogle search %user_email: %google_user\n\n--\n%site");  define('ADVUSER_SUBSTITUTION_TEXT', t('<strong>Substitution variables</strong> available in subject and email body<br/><em> %user_name, %user_email, %user_status, %user_created, %user_theme, %user_timezone, %user_language, %user_signature, %site, %uri, %google_user (search google for user email), %yahoo_user (search yahoo for user email)</em>'));
 define('ADVUSER_DEFAULT_MODIFY_MAIL', ADVUSER_DEFAULT_NEW_MAIL); // "User email: %user_email\n\nIf you want to check and edit the account go to %uri.\n\nYahoo search %user_email: %yahoo_user \nGoogle search %user_email: %google_user\n\n--\n%site");  
 define('ADVUSER_DEFAULT_NEW_ROLES', NULL);  
 define('ADVUSER_DEFAULT_NEW_SUBJECT', 'A new user (%username) has just registered on %site.');  
 define('ADVUSER_DEFAULT_MODIFY_SUBJECT', 'A user (%username) has just modified their account on %site.');  
 define('ADVUSER_DEFAULT_NEW_NOTIFY', 1);  
 define('ADVUSER_DEFAULT_MODIFY_NOTIFY', 1);  
 define('ADVUSER_DEFAULT_LISTNO', 200);  
 define('ADVUSER_DEFAULT_PROFILE_FIELDS', NULL);  
   
 //define('ADVUSER_MAIL_MESSAGE_TEMPLATE', "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");  
15    
16  /**  /**
17   * hook_perm() implementation   * Implementation of hook_perm().
  *  
  * @return array of permissions  
18   */   */
19    function advuser_perm() {
20      return array(
21        t('administer advuser'),
22        t('access advuser'),
23        t('send email advuser'),
24        t('receive email advuser'),
25      );
26    }
27    
28  /**  /**
29   * Implementation of hook_menu().   * Implementation of hook_menu().
30   */   */
31  function advuser_menu($may_cache) {  function advuser_menu($may_cache) {
32    // code which should run exactly once per page view    // Include filters
33    if (!$may_cache) {    include_once(drupal_get_path('module','advuser').'/advuser_filters.inc');
34      drupal_add_css(drupal_get_path('module', 'advuser') .'/advuser.css');  
35    }    $admin_access = user_access('administer advuser');
36    $items = array();    $access_access = user_access('access advuser');
37    
38    if ($may_cache) {    if ($may_cache) {
39      $items[] = array(      $items[] = array(
40        'path' => 'admin/settings/advuser',        'path' => 'admin/settings/advuser',
# Line 36  function advuser_menu($may_cache) { Line 42  function advuser_menu($may_cache) {
42        'description' => t('Advanced User Settings'),        'description' => t('Advanced User Settings'),
43        'callback' => 'drupal_get_form',        'callback' => 'drupal_get_form',
44        'callback arguments' => array('advuser_settings'),        'callback arguments' => array('advuser_settings'),
45        'access' => user_access('administer site configuration'),        'access' =>  $admin_access,
46        'type' => MENU_NORMAL_ITEM,        'type' => MENU_NORMAL_ITEM,
47      );      );
48    
49      $items[] = array(      $items[] = array(
50              'path' => 'admin/user/advuser',        'path' => 'admin/user/user/advuser',
51              'title' => t('Advanced managment'),        'title' => t('Advanced'),
52              'callback' => 'advuser_admin_users',        'description' => t('List, add, edit and email users.'),
53              'type' => MENU_NORMAL_ITEM,        'callback' => 'advuser_admin',
54  //            'weight' => 7,        'callback arguments' => array('list'),
55              'access' => user_access('administer users'),        'access' => $access_access,
56              );        'type' => MENU_LOCAL_TASK,
   }  
   
   return $items;  
 }  
   
 /**  
  * hook_help implementation  
  */  
 function advuser_help($section) {  
   
   switch ($section) {  
     case 'admin/modules#description':  
       return t('Advanced user management module. Filter users and mass actions based on their filters.');  
   }  
 }  
   
 /*  
 ** Filters  
 */  
 function advuser_admin_filters() {  
   
   $filters = array();  
   
   // Regular filters  
   $filters['email'] = array(  
       'title' => t('E-mail'),  
       'where' => "u.mail = '%s'",  
     );  
   
    $filters['uid'] = array(  
       'title' => t('User Id'),  
       'where' => "u.uid = '%s'",  
     );  
   
     $filters['access'] = array(  
       'title' => t('Last Access'),  
       'where' => "u.access = '%s'",  
57      );      );
     $filters['status'] = array(  
       'title' => t('Status'),  
       'type'  => t('selection'),  
       'options' => array(0 => t('Blocked'), 1 => ('Active')),  
       'where' => 'u.status = %s',  
     );  
   
   $fields = variable_get('advuser_profile_fields', ADVUSER_DEFAULT_PROFILE_FIELDS);  
   if ( is_array($fields) ) {  
     foreach ( $fields as $fid => $value) {  
       if ( $value ) {  
         $field = db_fetch_object(db_query('SELECT * FROM {profile_fields} WHERE fid = %d', $fid));  
         $options = array();  
         if ( $field->type == 'selection' ) {  
           $result_v = db_query('SELECT DISTINCT * FROM {profile_values} WHERE fid = %d', $field->fid);  
           while ( $value = db_fetch_object($result_v)) {  
             $options[$value->value] = $value->value;  
           }  
         }  
   
         // Regular filters  
         $filters[$field->fid] = array(  
             'title' => $field->title,  
             'type' => $field->type,  
             'options' => $options,  
             'field_where' => 'pf.fid = '. $field->fid .' AND pv.value = '."'%s'",  
           );  
       }  
     }  
   }  
   
   advuser_module_invoke('filter', $filters);  
   return $filters;  
 }  
   
 function advuser_admin_filter_form_validate($form_id, $form) {  
   $op = $form_values['op'];  
   if ( $op == 'Filter' || $op == 'Refine' ) {  
     if ( ! isset($form[$form['filter']]) || $form[$form['filter']] == '' ) {  
       form_set_error($form['filter'], t('Please fill some value to correctely set up the filter'));  
     }  
58    }    }
59      return $items;
60  }  }
61    
62    function advuser_admin($callback_arg = '') {
63      $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg;
64    
 function advuser_admin_filter_form_submit() {  
   global $form_values;  
   $op = $form_values['op'];  
   $filters = advuser_admin_filters();  
65    switch ($op) {    switch ($op) {
66      case t('Filter'): case t('Refine'):      default: {
67        if (isset($form_values['filter'])) {        if ($_POST['accounts'] && $_POST['operation'] == 'delete') {
68          $filter = $form_values['filter'];          $output = drupal_get_form('advuser_multiple_delete_confirm');
69          if ( $filters[$filter]['type']  == 'selection' ) {        }
70            if (isset($filters[$filter]['options'][$form_values[$filter]])) {        elseif ($_POST['accounts'] && $_POST['operation'] == 'email') {
71              $_SESSION['advuser_user_filter'][] = array($filter, $form_values[$filter]);          $output = drupal_get_form('advuser_multiple_email_confirm');
72            }        }
73          }        else {
74           else {          $output = drupal_get_form('advuser_filter_form');
75            $_SESSION['advuser_user_filter'][] = array($filter, $form_values[$filter]);          $output .= drupal_get_form('advuser_admin_account');
         }  
76        }        }
77        break;      } break;
     case t('Undo'):  
       array_pop($_SESSION['advuser_user_filter']);  
       break;  
     case t('Reset'):  
       $_SESSION['advuser_user_filter'] = array();  
       break;  
     case t('Update'):  
       return;  
   }  
   if ($op != '') {  
     drupal_goto('admin/user/advuser');  
   }  
 }  
   
   
 function advuser_admin_filter_form() {  
   //print_r($_SESSION['advuser_user_filter']);  
   
   $sess = &$_SESSION['advuser_user_filter'];  
   $sess = is_array($sess) ? $sess : array();  
   $session = $sess;  
   asort($session);  
   $filters = advuser_admin_filters();  
   
   $i = 0;  
   $form['filters'] = array('#type' => 'fieldset', '#title' => t('Show only items where'), '#theme' => 'advuser_filters');  
   
   $types_used = array();  
   foreach ($session as $filter) {  
     list($type, $value) = $filter;  
     $original = $filters[$type];  
     $em = 'and';  
     if ( array_search($type, $types_used) !== FALSE ) {  
       $em = 'or';  
     }  
     $string = ($i++ ? '<em>'. $em .'</em> where <strong>%a</strong> is <strong>%b</strong>' : '<strong>%a</strong> is <strong>%b</strong>');  
     $txt_value = $value;  
     if ($original['type'] == 'selection') {  
       $txt_value = $original['options'][$value];  
     }  
     $form['filters']['current'][] = array('#value' => t($string, array('%a' => $filters[$type]['title'] , '%b' => $txt_value)));  
     $types_used[] = $type;  
   }  
   
   foreach ($filters as $key => $filter) {  
     $names[$key] = $filter['title'];  
     if ( $filter['type'] == 'selection' ) {  
       $form['filters']['status'][$key] = array('#type' => 'select', '#options' => $filter['options']);  
     }  
      else {  
       $form['filters']['status'][$key] = array('#type' => 'textfield');  
     }  
   }  
   
   $names_keys = array_keys($names);  
   $form['filters']['filter'] = array('#type' => 'radios', '#options' => $names , '#default_value' => $names_keys[0] );  
   $form['filters']['buttons']['submit'] = array('#type' => 'submit', '#value' => (count($session) ? t('Refine') : t('Filter')));  
   if (count($session)) {  
     $form['filters']['buttons']['undo'] = array('#type' => 'submit', '#value' => t('Undo'));  
     $form['filters']['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));  
78    }    }
79      return $output;
 //  return drupal_get_form('advuser_admin_filter_form', $form);  
   return $form;  
80  }  }
81    
82    function advuser_admin_account() {
83  /*    $filter = advuser_build_filter_query();
84  ** AdvUser operations    $header = array(
85  */      array(),
86  function advuser_admin_users_operations() {      array('data' => t('Username'), 'field' => 'u.name'),
87    $external = array();      array('data' => t('Status'), 'field' => 'u.status'),
   $operations = array(  
     'email' => array(t('Email users'), 'advuser_multiple_email_confirm_page', 'confirm'),  
     'delete' =>    array(t('Delete users'), 'advuser_multiple_delete_confirm' , 'confirm')  
88    );    );
89      $roles = advuser_user_roles();
90    advuser_module_invoke('actions', $external);    if (count($roles)) {
91        $header[] = t('Roles');
   foreach ($external as $k => $v ) {  
     $operations['external_'. $k] = $v;  
   }  
   
   return $operations;  
 }  
   
 function advuser_admin_user_build_filter_query() {  
   $filters = advuser_admin_filters();  
   
   // Build query  
   $field_where = $where = $where_args = $having_args = array();  
   $join = '';  
   
   $cnt = 0;  
   $session = $_SESSION['advuser_user_filter'];  
   asort($session);  
   foreach ($session as $filter) {  
     list($key, $value) = $filter;  
   
     // Check if process the filter an how  
     $where_key = TRUE ;  
     $where_keys = array_keys($where, $filters[$key]['where']);  
     if ( count((array) $where_keys) > 0 ) {  
       // check for same value to on arg array, should have the same key  
       foreach ( $where_keys as $k => $v ) {  
         if ( $where_args[$v] == $value ) {  
           $where_key = FALSE;  
         }  
       }//foreach;  
     }  
   
     if ( isset($filters[$key]['where']) && $where_key )  {  
       $where[] = $filters[$key]['where'];  
       $where_args[] = $value;  
     }  
   
     // Check if process the filter an how  
     $field_where_key = TRUE;  
     $field_where_keys = array_keys($field_where, $filters[$key]['field_where']);  
     if ( count((array) $field_where_keys) > 0 ) {  
       // check for same value to on arg array, should have the same key  
       foreach ( $field_where_keys as $k => $v ) {  
         if ( $having_args[$v] == $value ) {  
           $field_where_key = FALSE;  
         }  
       }//foreach;  
     }  
      else {  
       if (  isset($filters[$key]['field_where']) ) {  
         $cnt++;  
       }  
     }  
   
     if ( isset($filters[$key]['field_where']) && $field_where_key )  {  
       $field_where[] = $filters[$key]['field_where'];  
       $having_args[] = $value;  
     }  
   
     // Proces join just once  
     if ( ! strstr($join, $filters[$key]['join'] .' ') ) {  
       $join .= $filters[$key]['join'] .' ';  
     }  
   }  
   
   //print_r($field_where);  
   
   // build query smartly  
   $where_sql = 'WHERE u.uid > 1 AND ';  
   foreach ( (array) $where as $w ) {  
     if ( $lastwhere ) {  
       if ( $lastwhere == $w ) {  
         $where_sql .= ' OR '. $w ;  
       }  
        else {  
         $where_sql .= ') AND ('. $w ;  
       }  
     }  
      else {  
       $where_sql .= '('. $w ;  
     }  
     $lastwhere = $w;  
   }  
   if ( $lastwhere ) {  
     $where_sql .= ') AND ';  
   }  
   $where_sql .= '1';  
   
   $where = count($where) ? 'WHERE u.uid > 1 AND '. implode(' AND ', $where) : '';  
   $field_where_cnt = count($field_where);  
   $field_where = $field_where_cnt ? implode(' OR ', $field_where) : '0';  
   $having[] = 'SUM(IF('. $field_where .',1,0)) = '. $cnt;  
   $having = count($having) ? 'HAVING '. implode(' AND ', $having) : '';  
   
   $args = array_merge($where_args, $having_args);  
   
   return array( 'where' => $where_sql, 'join' => $join, 'args' => $args, 'having' => $having);  
 }  
   
 function advuser_multiple_email_confirm_page($all, $form) {  
   return drupal_get_form('advuser_multiple_email_confirm', $all, $form);  
 }  
   
 function advuser_multiple_email_confirm($all, $form) {  
   $form['mailsubject'] = array(  
       '#type' => 'textfield',  
       '#title' => t('Subject'),  
       '#required' => TRUE,  
     );  
   $form['mailbody'] = array(  
       '#type' => 'textarea',  
       '#title' => t('Mail body'),  
       '#required' => TRUE,  
     );  
   
   return confirm_form($form,  
                       t('Are you sure you want to mail these users?'),  
                       'admin/user/advuser', t('This action cannot be undone.'),  
                       t('Mail all'), t('Cancel'));  
 }  
   
   
 function advuser_multiple_email_confirm_submit($form_id, $edit) {  
   if ($edit['confirm']) {  
     foreach ($edit['users'] as $uid => $value) {  
       $account = user_load(array('uid' => $uid));  
       if ( module_exists('lightcrm') ) {  
         _lightcrm_comment_add($uid, $edit['mailsubject'], $edit['mailbody']);  
       }  
        else {  
         $from = variable_get("site_mail", ini_get("sendmail_from")); // http://drupal.org/node/77689  
         drupal_mail('advance-user-mail', $account->mail, $edit['mailsubject'], $edit['mailbody'], $from);  
       }  
     }  
     drupal_set_message(t('The users have been mailed.'));  
   }  
   drupal_goto('admin/user/advuser');  
 }  
   
 function advuser_multiple_delete_confirm_submit($form_id, $edit) {  
   if ($edit['confirm']) {  
     foreach ($edit['users'] as $uid => $value) {  
       $account = user_load(array('uid' => $uid));  
       db_query('DELETE FROM {users} WHERE uid = %d', $account->uid);  
       db_query('DELETE FROM {sessions} WHERE uid = %d', $account->uid);  
       db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);  
       db_query('DELETE FROM {authmap} WHERE uid = %d', $account->uid);  
       watchdog('user', t('Deleted user: %name %email.', array('%name' => theme('placeholder', $account->name), '%email' => theme('placeholder', '<'. $account->mail .'>'))), WATCHDOG_NOTICE);  
       drupal_set_message(t('The account has been deleted.'));  
       module_invoke_all('user', 'delete', $edit, $account);  
     }  
     drupal_set_message(t('The items have been deleted.'));  
   }  
   drupal_goto('admin/user/advuser');  
 }  
   
 function advuser_multiple_confirm($all, $action, $user_func) {  
   $edit = $_POST['edit'];  
   
   $form = array();  
   $form['users'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);  
   // array filter returns only elements with true values  
   if ( $all ) {  
     $filter = advuser_admin_user_build_filter_query();  
     $result = db_query('SELECT u.* FROM {users} u '. $filter['join'] .' LEFT JOIN {profile_values} pv ON u.uid = pv.uid LEFT JOIN {profile_fields} pf on pv.fid = pf.fid '. $filter['where'] .' GROUP BY u.uid '. $filter['having'] .' ORDER BY u.login DESC', $filter['args']);  
     while ( $usr = db_fetch_object($result)) {  
       $user_array[$usr->uid] = '';  
     }  
   }  
    else {  
     $user_array = array_filter($edit['users']);  
   }  
   
   foreach ($user_array as $uid => $value) {  
     $name = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));  
     $form['users'][$uid] = array('#type' => 'hidden', '#value' => $uid, '#prefix' => '<li>', '#suffix' => check_plain($name) ."</li>\n");  
92    }    }
93    $form['operation'] = array('#type' => 'hidden', '#value' => $action);    $header = array_merge($header, array(
94        array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
95    if ( function_exists($user_func) ) {      array('data' => t('Last access'), 'field' => 'u.access'),
96      $user_func($all, $form);    ));
   }  
   
   $operations = advuser_admin_users_operations();  
   return confirm_form($user_func, $form,  
                       t('Are you sure you want to update these items?'),  
                       'admin/user/advuser', t('This action cannot be undone.'),  
                       $operations[$action][0], t('Cancel'));  
 }  
   
 function advuser_admin_users() {  
   $output = drupal_get_form('advuser_admin_filter_form');  
   
   // Call the form first, to allow for the form_values array to be populated.  
 //  $output .= drupal_get_form('user_admin_account');  
   $output .= drupal_get_form('advuser_admin_users_form');  
   
   return $output;  
 }  
   
 function advuser_admin_users_form() {  
   global $form_values;  
97    
98    $op = $form_values['op'];    $query = '';
99    if ( $op == 'Update all' ) {    $ff = array();
100      $all = TRUE;    $pf = array();
101    }    foreach (advuser_profile_fields() as $field) {
102        $ff[] = array('data'=>t($field->title), 'field'=>"$field->name.value");
103    foreach (advuser_admin_users_operations() as $key => $value) {      $pf[] = "LEFT JOIN {profile_values} $field->name ON $field->name.fid = $field->fid AND $field->name.uid = u.uid";
104      if ( $value[2] == 'confirm' ) {    }
105        if (    $header = array_merge($header, $ff);
106            $_POST['edit']['options_all']['operation'] == $key && $all ||    $header[] = t('Operations');
107            ( $_POST['edit']['options_sel']['operation'] == $key && (count($_POST['edit']['users']) > 0) ) ||  
108            $_POST['edit']['operation'] == $key    $filter['join'] .= count($pf) ? ' ' . implode(' ', array_unique($pf)) : NULL;
109          ) {  
110      $sql = 'SELECT DISTINCT u.uid, u.name, u.status, u.created, u.access '.$pquery.' FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid '. $filter['join'] .' WHERE u.uid != 0 '. $filter['where'];
111          return advuser_multiple_confirm($all, $key, $value[1]);  
112          //return call_user_func($value[1], $all);    $sql .= tablesort_sql($header);
113          //return advuser_multiple_delete_confirm($all);    $query_count = 'SELECT COUNT(DISTINCT u.uid) FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid '. $filter['join'] .' WHERE u.uid != 0 '. $filter['where'];
114        }    $result = pager_query($sql, variable_get('advuser_listno', 50), 0, $query_count, $filter['args']);
115      }  
116    }    $form['options'] = array(
117        '#type' => 'fieldset',
118    $filter = advuser_admin_user_build_filter_query();      '#title' => t('Update options'),
119    $listno = variable_get('advuser_listno', ADVUSER_DEFAULT_LISTNO);      '#prefix' => '<div class="container-inline">',
120    $result = pager_query('SELECT u.* FROM {users} u '. $filter['join'] .' LEFT JOIN {profile_values} pv ON u.uid = pv.uid LEFT JOIN {profile_fields} pf on pv.fid = pf.fid '. $filter['where'] .' GROUP BY u.uid '. $filter['having'] .' ORDER BY u.login DESC', $listno, 0, NULL, $filter['args']);      '#suffix' => '</div>',
   //$result = 'SELECT u.* FROM {users} u '. $filter['join'] .' LEFT JOIN {profile_values} pv ON u.uid = pv.uid LEFT JOIN {profile_fields} pf on pv.fid = pf.fid '. $filter['where'] .' GROUP BY u.uid ' . $filter['having'] . ' ORDER BY u.login DESC', $listno, 0, $filter['args'];  
   //$result .= tablesort_sql($header);  
   
   $form['options_all'] = array(  
     '#type' => 'fieldset', '#title' => t('Mass update on every record'),  
     '#prefix' => "<div class=\"container-inline\">" , '#suffix' => "</div>",  
     '#tree' => TRUE,  
121    );    );
122    $options = array();    $options = array();
123    foreach (advuser_admin_users_operations() as $key => $value) {  
124      $options[$key] = $value[0];    $operations = module_invoke_all('user_operations');
125      $operations = array_merge($operations,module_invoke_all('advuser_operations'));
126      foreach ($operations as $operation => $array) {
127        $options[$operation] = $array['label'];
128    }    }
129    $form['options_all']['operation'] = array(    $form['options']['operation'] = array(
130      '#type' => 'select',      '#type' => 'select',
131      '#options' => $options,      '#options' => $options,
132        '#default_value' => 'unblock',
133    );    );
134    $form['options_all']['submit'] = array(    $form['options']['submit'] = array(
135      '#type' => 'submit',      '#type' => 'submit',
136      '#value' => t('Update all')      '#value' => t('Update'),
   );  
   
   $form['options_sel'] = array(  
     '#type' => 'fieldset', '#title' => t('Update on selected records only'),  
     '#prefix' => "<div class=\"container-inline\">" , '#suffix' => "</div>",  
     '#tree' => TRUE,  
137    );    );
   $options = array();  
   foreach (advuser_admin_users_operations() as $key => $value) {  
     $options[$key] = $value[0];  
   }  
   $form['options_sel']['operation'] = array(  
     '#type' => 'select',  
     '#options' => $options,  
    );  
   $form['options_sel']['submit'] = array(  
     '#type' => 'submit',  
     '#value' => t('Update')  
    );  
138    
139      $destination = drupal_get_destination();    $destination = drupal_get_destination();
140    
141      $status = array(t('blocked'), t('active'));    $status = array(t('blocked'), t('active'));
142      $roles = advuser_user_roles();
   while ($usr = db_fetch_object($result)) {  
     $users[$usr->uid] = '';  
     $form['name'][$usr->uid] = array('#value' => theme('username', $usr));  
143    
144      while ($account = db_fetch_object($result)) {
145        $accounts[$account->uid] = '';
146        $form['name'][$account->uid] = array('#value' => theme('username', $account));
147      $form['status'][$account->uid] =  array('#value' => $status[$account->status]);      $form['status'][$account->uid] =  array('#value' => $status[$account->status]);
148      $form['access'][$usr->uid] = array('#value' => $usr->access ? t('%time ago', array('%time' => format_interval(time() - $usr->access))) : t('never'));      $users_roles = array();
149      //$form['access'][$usr->access] = array('#value' => ($usr->access ? format_interval(time() - $usr->access)));      $roles_result = db_query('SELECT rid FROM {users_roles} WHERE uid = %d', $account->uid);
150      $form['operations'][$usr->uid] = array('#value' => l(t('edit'), 'user/'. $usr->uid .'/edit', array(), $destination));      while ($user_role = db_fetch_object($roles_result)) {
151      $form['refcode'][$usr->uid] = array('#value' => $usr->uid);        $users_roles[] = $roles[$user_role->rid];
152        }
153        asort($users_roles);
154        $form['roles'][$account->uid][0] = array('#value' => theme('item_list', $users_roles));
155        $form['member_for'][$account->uid] = array('#value' => format_interval(time() - $account->created));
156        $form['last_access'][$account->uid] =  array('#value' => $account->access ? t('@time ago', array('@time' => format_interval(time() - $account->access))) : t('never'));
157        profile_load_profile($account);
158        foreach(advuser_profile_fields() as $field) {
159          $form[$field->name][$account->uid] = array('#value' => profile_view_field($account, $field));
160        }
161        $fv = l(t('edit'), "user/$account->uid/edit", array(), $destination);
162        if ($account->uid != 1) {
163          $fv .= ' | ' . l(t('delete'), "user/$account->uid/delete", array(), $destination);
164        }
165        $form['operations'][$account->uid] = array('#value' => $fv);
166    }    }
167      $form['accounts'] = array(
   $form['users'] = array(  
168      '#type' => 'checkboxes',      '#type' => 'checkboxes',
169      '#options' => $users      '#options' => $accounts
170     );    );
   
171    $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));    $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
172    
   $form['#method'] = 'post';  
   $form['#action'] =  url('admin/user/advuser/action');  
   
173    return $form;    return $form;
174  }  }
175    
176    /**
177  function theme_advuser_admin_users_form($form) {   * Theme user administration overview.
178     */
179    function theme_advuser_admin_account($form) {
180      static $profile_fields = array();
181    // Overview table:    // Overview table:
182    $header = array(    $header = array(
183      theme('table_select_header_cell'),      theme('table_select_header_cell'),
184      array('data' => t('Username'), 'field' => 'u.name'),      array('data' => t('Username'), 'field' => 'u.name'),
185      array('data' => t('Status'), 'field' => 'u.status'),      array('data' => t('Status'), 'field' => 'u.status'),
     array('data' => t('Last access'), 'field' => 'u.access'),  
     array('data' => t('User ID'), 'field' => 'u.uid'),  
     t('Operations')  
186    );    );
187      $roles = advuser_user_roles();
188      if (count($roles)) {
189        $header[] = t('Roles');
190      }
191      $header = array_merge($header, array(
192        array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
193        array('data' => t('Last access'), 'field' => 'u.access'),
194      ));
195    
196      $ff = array();
197      foreach (advuser_profile_fields() as $field) {
198        $ff[] = array('data'=>t($field->title), 'field'=>$field->name);
199      }
200      $header = array_merge($header, $ff);
201      $header[] = t('Operations');
202    
203    $output .= drupal_render($form['options_all']);    $output = drupal_render($form['options']);
   $output .= drupal_render($form['options_sel']);  
204    if (isset($form['name']) && is_array($form['name'])) {    if (isset($form['name']) && is_array($form['name'])) {
205      foreach (element_children($form['name']) as $key) {      foreach (element_children($form['name']) as $key) {
206        $rows[] = array(        $row = array(
207        drupal_render($form['users'][$key]),          drupal_render($form['accounts'][$key]),
208        drupal_render($form['name'][$key]),          drupal_render($form['name'][$key]),
209        drupal_render($form['status'][$key]),          drupal_render($form['status'][$key]),
       drupal_render($form['access'][$key]),  
       drupal_render($form['refcode'][$key]),  
       drupal_render($form['operations'][$key]),  
210        );        );
211          $roles = advuser_user_roles();
212          if (count($roles)) {
213            $row[] = drupal_render($form['roles'][$key]);
214          }
215          $row = array_merge($row, array(
216            drupal_render($form['member_for'][$key]),
217            drupal_render($form['last_access'][$key]),
218          ));
219    
220          if (module_exists('profile')) {
221            $fields = variable_get('advuser_profile_fields', NULL);
222    
223            if (is_array($fields)) {
224              foreach ( $fields as $fid => $value) {
225                if ( $value ) {
226                  if (empty($profile_fields[$fid])) {
227    
228                    $field = db_fetch_object(db_query('SELECT * FROM {profile_fields} WHERE fid = %d', $fid));
229                    $profile_fields[$fid] = $field;
230                  }
231                  else {
232                    $field = $profile_fields[$fid];
233                  }
234                  $row[] = drupal_render($form[$field->name][$key]);
235                }
236              }
237            }
238          }
239          $row[] = drupal_render($form['operations'][$key]);
240          $rows[] = $row;
241      }      }
   
242    }    }
243    else  {    else  {
244      $rows[] = array(array('data' => t('No posts available.'), 'colspan' => '4'));      $rows[] = array(array('data' => t('No users available.'), 'colspan' => '7'));
245    }    }
246    
247    $output .= theme('table', $header, $rows);    $output .= theme('table', $header, $rows);
# Line 559  function theme_advuser_admin_users_form( Line 250  function theme_advuser_admin_users_form(
250    }    }
251    
252    $output .= drupal_render($form);    $output .= drupal_render($form);
   $output .= theme('pager', NULL, 50, 0);  
   return $output;  
 }  
253    
 function theme_advuser_admin_filter_form(&$form) {  
   $output .= '<div id="advuser-admin-filter">';  
   $output .= drupal_render($form['filters']);  
   $output .= '</div>';  
   $output .= drupal_render($form);  
254    return $output;    return $output;
255  }  }
256    
 function advuser_admin_users_validate($form_id, $edit) {  
   $op = $form_values['op'];  
   if ( $op == 'Update' ) {  
     $edit['users'] = array_diff($edit['users'], array(0));  
     if (count($edit['users']) == 0) {  
       form_set_error('', t('Please select some items to perform the update on.'));  
     }  
   }  
 }  
   
257  /**  /**
258   * Perform actions on users   * Submit the user administration update form.
259   */   */
260  function advuser_admin_users_submit($form_id, $edit) {  function advuser_admin_account_submit($form_id, $form_values) {
261    $operations = advuser_admin_users_operations();    $operations = module_invoke_all('user_operations');
262    if ($operations[$edit['operation']][1]) {    $operations = array_merge($operations,module_invoke_all('advuser_operations'));
263      // Execute sql    $operation = $operations[$form_values['operation']];
264      $operation = $operations[$edit['operation']][1];    // Filter out unchecked accounts.
265      foreach ($edit['users'] as $uid => $value) {    $accounts = array_filter($form_values['accounts']);
266        if ($value) {    if ($function = $operation['callback']) {
267          db_query($operation, $uid);      // Add in callback arguments if present.
268        }      if (isset($operation['callback arguments'])) {
269          $args = array_merge(array($accounts), $operation['callback arguments']);
270        }
271        else {
272          $args = array($accounts);
273      }      }
274        call_user_func_array($function, $args);
275    
276        cache_clear_all('*', 'cache_menu', TRUE);
277      drupal_set_message(t('The update has been performed.'));      drupal_set_message(t('The update has been performed.'));
     drupal_goto('admin/user/advuser');  
278    }    }
279  }  }
280    
281  /**  function advuser_admin_account_validate($form_id, $form_values) {
282   * Invokes hook_advuser() in every module.    $form_values['accounts'] = array_filter($form_values['accounts']);
283   *    if (count($form_values['accounts']) == 0) {
284   * We cannot use module_invoke() for this, because the arguments need to      form_set_error('', t('No users selected.'));
  * be passed by reference.  
  */  
 function advuser_module_invoke($type, &$array) {  
   foreach (module_list() as $module) {  
     $function = $module .'_advuser';  
     if (function_exists($function)) {  
       $function($type, $array);  
     }  
285    }    }
286  }  }
287    
288  function theme_advuser_filters(&$form) {  function advuser_multiple_delete_confirm() {
289    $output .= '<ul>';    $edit = $_POST;
290    if (sizeof($form['current'])) {  
291      foreach (element_children($form['current']) as $key) {    $form['accounts'] = array(
292        $output .= '<li>'. drupal_render($form['current'][$key]) .'</li>';      '#prefix' => '<ul>',
293        '#suffix' => '</ul>',
294        '#tree' => TRUE
295      );
296      // array_filter returns only elements with TRUE values
297      foreach (array_filter($edit['accounts']) as $uid => $value) {
298        $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));
299        $form['accounts'][$uid] = array(
300          '#type' => 'hidden',
301          '#value' => $uid,
302          '#prefix' => '<li>',
303          '#suffix' => check_plain($user) ."</li>\n"
304        );
305      }
306      $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
307    
308      return confirm_form(
309        $form,
310        t('Are you sure you want to delete these users?'),
311        'admin/user/user/advuser', t('This action cannot be undone.'),
312        t('Delete all'),
313        t('Cancel')
314      );
315    }
316    
317    function advuser_multiple_delete_confirm_submit($form_id, $form_values) {
318      if ($form_values['confirm']) {
319        foreach ($form_values['accounts'] as $uid => $value) {
320          user_delete($form_values, $uid);
321      }      }
322        drupal_set_message(t('The users have been deleted.'));
323    }    }
324      return 'admin/user/user/advuser';
325    }
326    
327    $output .= '<li><dl class="multiselect">'. (sizeof($form['current']) ? '<dt><em>'. t('and/or') .'</em> '. t('where') .'</dt>' : '') .'<dd class="a">';  /**
328    foreach (element_children($form['filter']) as $key) {   * Email functionality
329      $output .= drupal_render($form['filter'][$key]);   */
330    }  function advuser_advuser_operations() {
331    $output .= '</dd>';    $operations = array(
332        'email' => array(
333        'label' => t('Email selected users')
334        )
335      );
336      return $operations;
337    }
338    
339    $output .= '<dt>'. t('is') .'</dt><dd class="b">';  function advuser_multiple_email_confirm() {
340      $edit = $_POST;
341    
342    foreach (element_children($form['status']) as $key) {    $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
343      $output .= drupal_render($form['status'][$key]);    // array_filter returns only elements with TRUE values
344    }    foreach (array_filter($edit['accounts']) as $uid => $value) {
345    $output .= '</dd>';      $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));
346        $form['accounts'][$uid] = array(
347          '#type' => 'hidden',
348          '#value' => $uid,
349          '#prefix' => '<li>',
350          '#suffix' => check_plain($user) ."</li>\n"
351        );
352      }
353      $form['operation'] = array(
354        '#type' => 'hidden',
355        '#value' => 'email'
356      );
357    
358    $output .= '</dl>';    $form['variables'] = array(
359    $output .= '<div class="container-inline" id="advuser-admin-buttons">'. drupal_render($form['buttons']) .'</div>';      '#type' => 'markup',
360    $output .= '</li></ul><br class="clear" />';      '#prefix' => '<div class="advuser-inset-panel">',
361        '#value' => ADVUSER_SUBSTITUTION_TEXT,
362        '#suffix' => '</div>'
363      );
364    
365    return $output;    $form['mailsubject'] = array(
366        '#type' => 'textfield',
367        '#title' => t('Subject'),
368        '#required' => TRUE,
369      );
370    
371      $form['mailbody'] = array(
372        '#type' => 'textarea',
373        '#title' => t('Mail body'),
374        '#required' => TRUE,
375      );
376    
377      return confirm_form(
378        $form,
379        t('Are you sure you want to email these users?'),
380        'admin/user/user/advuser',
381        t('This action cannot be undone.'),
382        t('Email'),
383        t('Cancel')
384      );
385  }  }
386    
387  function advuser_settings() {  function advuser_multiple_email_confirm_submit($form_id, $form_values) {
388    $form['module_banner'] = array(    if ($form_values['confirm']) {
389        '#type' => 'markup',      foreach ($form_values['accounts'] as $uid => $value) {
390        '#value' => '<div style="border: solid 1px #eee; margin: .5em; padding: .5em;" <strong>Module maintenance and development sponsored by <a href="http://exodusdev.com">Exodus Development</a></strong><br/>'        $account = user_load(array('uid' => $uid));
391      );        $from = variable_get("site_mail", ini_get("sendmail_from"));
392          // these are invariant for all sent emails
393          $variables = _advuser_get_variables($account);
394          $mail_subject = strtr($form_values['mailsubject'], $variables);
395          $mail_body = strtr($form_values['mailbody'], $variables);
396          drupal_mail('advance-user-mail', $account->mail, $mail_subject, $mail_body, $from);
397        }
398        drupal_set_message(t('The users have been mailed.'));
399      }
400      return 'admin/user/user/advuser';
401    }
402    
403    $form['module_id'] = array(  /**
404        '#type' => 'markup',   * advuser settings page
405        '#value' =>  ADVUSER_MODULE_VERSION .'<br/></div>'   */
406      );  function advuser_settings() {
407    
408    $form['advuser_mail'] = array(    $form['advuser_mail'] = array(
409        '#type' => 'fieldset',      '#type' => 'fieldset',
410        '#title' => t('Mail notifications on user account activity.'),      '#title' => t('Mail notifications on user account activity.'),
411        '#collapsible' => FALSE,      '#collapsible' => FALSE,
412        '#collapsed' => FALSE,      '#collapsed' => FALSE,
413      );    );
414    
415    $form['advuser_mail']['variables'] = array(    $form['advuser_mail']['variables'] = array(
416        '#type' => 'markup',      '#type' => 'markup',
417        '#value' => '<div class="advuser-inset-panel"><strong>Substitution variables</strong> available in subject and email body<br/><em> %username, %site, %uri, %user_email, %google_user (search google for user email), %yahoo_user (search yahoo for user email)</em></div>'      '#prefix' => '<div class="advuser-inset-panel">',
418      );      '#value' => ADVUSER_SUBSTITUTION_TEXT,
419        '#suffix' => '</div>',
420      );
421    
422    //New User Notification    //New User Notification
423    $form['advuser_mail']['advuser_new_notify'] = array(    $form['advuser_mail']['advuser_new_notify'] = array(
424        '#type' => 'checkbox',      '#type' => 'checkbox',
425        '#title' => t('Send notifications on new user registration'),      '#title' => t('Send notifications on new user registration'),
426        '#description' => t('Notify selected roles when new users register.'),      '#description' => t('Notify selected roles when new users register.'),
427        '#default_value' => variable_get('advuser_new_notify', ADVUSER_DEFAULT_NEW_NOTIFY),      '#default_value' => variable_get('advuser_new_notify', FALSE),
428      );    );
429    
430    $form['advuser_mail']['advuser_new_subject'] = array(    $form['advuser_mail']['advuser_new_subject'] = array(
431        '#type' => 'textfield',      '#type' => 'textfield',
432        '#title' => t('Mail subject'),      '#title' => t('Mail subject'),
433        '#description' => t('The subject of the mail that is going to be sent to the user.  You may insert substitution variables within this item.'),      '#description' => t('The subject of the mail that is going to be sent to the user.  You may insert substitution variables within this item.'),
434        '#default_value' => variable_get('advuser_new_subject', ADVUSER_DEFAULT_NEW_SUBJECT),      '#default_value' => variable_get('advuser_new_subject', NULL),
435      );    );
436    
437    $form['advuser_mail']['advuser_new_mail'] = array(    $form['advuser_mail']['advuser_new_mail'] = array(
438        '#type' => 'textarea',      '#type' => 'textarea',
439        '#title' => t('Mail body'),      '#title' => t('Mail body'),
440        '#description' => t('The mail that is going to be sent to the selected roles.  You may insert substitution variables within this item.'),      '#description' => t('The mail that is going to be sent to the selected roles.  You may insert substitution variables within this item.'),
441        '#default_value' => variable_get('advuser_new_mail', ADVUSER_DEFAULT_NEW_MAIL),      '#default_value' => variable_get('advuser_new_mail', NULL),
442      );    );
443    
444     //User change notification     //User change notification
445     $form['advuser_mail']['advuser_modify_notify'] = array(     $form['advuser_mail']['advuser_modify_notify'] = array(
446        '#type' => 'checkbox',      '#type' => 'checkbox',
447        '#title' => t('Send notifications on user profile updates'),      '#title' => t('Send notifications on user profile updates'),
448        '#description' => t('Notify selected roles when users update their profiles.'),      '#description' => t('Notify selected roles when users update their profiles.'),
449        '#default_value' => variable_get('advuser_modify_notify', ADVUSER_DEFAULT_MODIFY_NOTIFY),      '#default_value' => variable_get('advuser_modify_notify', FALSE),
450      );    );
451    
452    $form['advuser_mail']['advuser_modify_subject'] = array(    $form['advuser_mail']['advuser_modify_subject'] = array(
453        '#type' => 'textfield',      '#type' => 'textfield',
454        '#title' => t('Mail subject'),      '#title' => t('Mail subject'),
455        '#description' => t('The subject of the mail that is going to be sent when a user modifies their profiles.  You may insert substitution variables within this item.'),      '#description' => t('The subject of the mail that is going to be sent when a user modifies their profiles.  You may insert substitution variables within this item.'),
456        '#default_value' => variable_get('advuser_modify_subject', ADVUSER_DEFAULT_MODIFY_SUBJECT),      '#default_value' => variable_get('advuser_modify_subject', NULL),
457      );    );
458    $form['advuser_mail']['advuser_modify_mail'] = array(    $form['advuser_mail']['advuser_modify_mail'] = array(
459        '#type' => 'textarea',      '#type' => 'textarea',
460        '#title' => t('Mail body'),      '#title' => t('Mail body'),
461        '#description' => t('The mail that is going to be sent to the selected roles when a user modifies their account.  You may insert substitution variables within this item.'),      '#description' => t('The mail that is going to be sent to the selected roles when a user modifies their account.  You may insert substitution variables within this item.'),
462        '#default_value' => variable_get('advuser_modify_mail', ADVUSER_DEFAULT_MODIFY_MAIL),      '#default_value' => variable_get('advuser_modify_mail', NULL),
463      );    );
464    
465      //Maximum rows in dataset to display    //Maximum rows in dataset to display
466      $form['advuser_mail']['advuser_listno'] = array(    $form['advuser_mail']['advuser_listno'] = array(
467        '#type' => 'select',      '#type' => 'select',
468        '#options' => drupal_map_assoc(array(0, 10, 25, 50, 75, 100, 125, 150, 175, 200)),      '#options' => drupal_map_assoc(array(1, 10, 25, 50, 75, 100, 125, 150, 175, 200)),
469        '#title' => t('Number of users in listing'),      '#title' => t('Number of users in listing'),
470        '#description' => t('Sets how many users to display in table view'),      '#description' => t('Sets how many users to display in table view'),
471        '#default_value' => variable_get('advuser_listno', ADVUSER_DEFAULT_LISTNO),      '#default_value' => variable_get('advuser_listno', 50),
472      );    );
473    
474    $roles = user_roles(1);    $sel_roles_count = count(users_by_access('receive email advuser'));
   /*$options = array();  
   foreach ( $roles as $rid => $role) {  
     $options["$rid"] = $role;  
   }*/  
   //print_r();  
   $values = array();  
   $options = variable_get('advuser_new_roles', ADVUSER_DEFAULT_NEW_ROLES);  
   $sel_roles_count = 0;  
   foreach ( (array)$options as $opt => $v ) {  
     if ( $v > 0 ) {  
       $values[] = $v;  
       $sel_roles_count++;  
     }  
   }  
   $form['advuser_mailonnew']['advuser_new_roles'] = array(  
       '#type' => 'checkboxes',  
       '#title' => t('Notification Roles'),  
       '#description' => t('Roles that receive email notifications.'),  
       '#options' => $roles,  
       '#default_value' => $values /*variable_get('advuser_new_roles', ADVUSER_DEFAULT_NEW_ROLES)*/,  
     );  
   
475    if ($sel_roles_count == 0) {    if ($sel_roles_count == 0) {
476      $form['advuser_mailonnew']['no_roles_sel_warning']      $form['advuser_mailonnew']['no_roles_sel_warning'] = array(
477        = array('#type' => 'markup',        '#type' => 'markup',
478                '#value' => '<div class="advuser-settings-warning"><strong>WARNING: No roles selected!</strong> - no email notifications will be sent.</div>');        '#prefix' => '<div class="advuser-settings-warning">',
479          '#value' => '<strong>WARNING: No users have "receive email advuser" ' .
480                      l('access permissions', 'admin/user/access') .
481                      '!</strong> - No email notifications will be sent.',
482          '#suffix' => '</div>',
483        );
484    }    }
485    
486    if ( module_exists('profile') ) {    if ( module_exists('profile') ) {
487      $form['advuser_profile'] = array(      $form['advuser_profile'] = array(
488          '#type' => 'fieldset',        '#type' => 'fieldset',
489          '#title' => t('Profile module special settings'),        '#title' => t('Profile module special settings'),
490          '#collapsible' => TRUE,        '#collapsible' => TRUE,
491          '#collapsed' => TRUE,        '#collapsed' => TRUE,
492        );      );
493    
494      $fields = array();      $fields = array();
495      $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d ORDER BY category, weight', PROFILE_HIDDEN);      $result = db_query('SELECT * FROM {profile_fields} ORDER BY category, weight');
496      while ( $row = db_fetch_object($result)) {      while ( $row = db_fetch_object($result)) {
497        $fields[$row->fid] = $row->title;        $fields[$row->fid] = $row->title;
498      }      }
499    
500      $values = array();      $values = array();
501      $options = variable_get('advuser_profile_fields', ADVUSER_DEFAULT_PROFILE_FIELDS);      $options = variable_get('advuser_profile_fields', NULL);
502      foreach ( (array)$options as $opt => $v ) {      foreach ( (array)$options as $opt => $v ) {
503        if ( $v > 0 ) {        if ( $v > 0 ) {
504          $values[] = $v;          $values[] = $v;
# Line 771  function advuser_settings() { Line 511  function advuser_settings() {
511          '#title' => t('Profile fields'),          '#title' => t('Profile fields'),
512          '#options' => $fields,          '#options' => $fields,
513          '#default_value' => $values,          '#default_value' => $values,
514        );      );
   
515    }    }
516    return system_settings_form($form);    return system_settings_form($form);
517  }  }
# Line 782  function advuser_settings() { Line 521  function advuser_settings() {
521   * @param $user the user account   * @param $user the user account
522   * @return An associative array of substitution variables   * @return An associative array of substitution variables
523   */   */
524  function _advuser_get_variables(&$user) {  function _advuser_get_variables($user) {
525    $variables =    return array(
526      array(      '%user_name' => $user->name,
527            '%username' => $user->name,      '%site' => variable_get("site_name", "drupal"),
528            '%site' => variable_get("site_name", "drupal"),      '%uri' => url('user/'. $user->uid, NULL, NULL, TRUE),
529            '%uri' => url('user/'. $user->uid, NULL, NULL, TRUE),      '%user_email' => $user->mail,
530            '%user_email' => $user->mail,      '%user_status' => t($user->status ? 'Active' : 'Blocked'),
531            /* FUTURE: '%user_signature' => $user->signature, */      '%user_theme' => empty($user->theme) ? t('DEFAULT') : $user->theme,
532            '%google_user' => "http:/www.google.com/search?q=%22$user->mail%22",      '%user_created' => strftime('%x %X', $user->created),
533            '%yahoo_user' => "http://search.yahoo.com/search/?p=%22$user->mail%22",      '%user_language' => empty($user->language) ? t('DEFAULT') : $user->language,
534            );      '%user_timezone' => empty($user->timezone) ? '0' : "$user->timezone",
535    return $variables;      '%user_signature' => $user->signature,
536        '%google_user' => "http://www.google.com/search?q=%22$user->mail%22",
537        '%yahoo_user' => "http://search.yahoo.com/search/?p=%22$user->mail%22",
538      );
539  }  }
540    
541  /**  /**
542   * Construct a db query 'where' clause fragment so we can get a list of users to notify   * @private
543   * TODO: this needs cleanup.  There should be a way to gather a list of users who are   * Return a list of users to send notification of user changes.
544   * in roles.   *
545   */   * @return resource         // The result of the db_query.
546  function _advuser_get_roles_query_fragment($roles) {   */
547    // TODO: this needs to be cleaned up.  function _advuser_dbquery_users_to_notify() {
548    if (is_array($roles) ) {    $user_where = users_by_access('receive email advuser');
549      foreach ((array)$roles as $role_k => $role_v) {    $user_where = implode(',', $user_where);
550        if ( $role_v > 0 ) {    return empty($user_where) ? FALSE : db_query('SELECT u.mail, u.name FROM {users} u WHERE uid IN (' . $user_where . ')');
         if ( $role_v == DRUPAL_AUTHENTICATED_RID ) {  
           $role_where = ' OR 1';  
         }  
          else {  
           $role_where = ' OR ur.rid = '. $role_v;  
         }  
       }  
     }  
   }  
   return $role_where;  
 }  
   
 function _advuser_dbquery_users_to_notify($roles) {  
   $role_where = _advuser_get_roles_query_fragment($roles);  
   return db_query('SELECT u.mail, u.name FROM {users} u LEFT JOIN {users_roles} ur on u.uid = ur.uid WHERE 0 '. $role_where );  
551  }  }
552    
553    
554  /**  /**
555   * Handle user insertion (new users)   * Handle user insertion (new users)
  * TODO: DRY (don't repeat yourself!)  
556   */   */
   
557  function advuser_user_insert($edit, $user, $category) {  function advuser_user_insert($edit, $user, $category) {
558    // send mail    // Check to see if we notify the administrator of new users.
559    if ( variable_get('advuser_new_notify', ADVUSER_DEFAULT_NEW_NOTIFY) ) {    // Only send if the user isn't created by an administrator.
560      $new_notify = variable_get('advuser_new_notify', FALSE) &&
561                  ! user_access('administer_users');
562      if ($new_notify) {
563      $from = variable_get("site_mail", ini_get("sendmail_from"));      $from = variable_get("site_mail", ini_get("sendmail_from"));
564      $body = variable_get('advuser_new_mail', ADVUSER_DEFAULT_NEW_MAIL);      $body = variable_get('advuser_new_mail', NULL);
565      $subject = variable_get('advuser_new_subject', ADVUSER_DEFAULT_NEW_SUBJECT);      $subject = variable_get('advuser_new_subject', NULL);
566    
567      // these are invariant for all sent emails      // these are invariant for all sent emails
568      $variables = _advuser_get_variables($user);      $variables = _advuser_get_variables($user);
# Line 843  function advuser_user_insert($edit, $use Line 571  function advuser_user_insert($edit, $use
571    
572      watchdog('advuser', "Sending user account mail: subj='$user_subject' body='$user_body'");      watchdog('advuser', "Sending user account mail: subj='$user_subject' body='$user_body'");
573    
574      $roles = variable_get('advuser_new_roles', ADVUSER_DEFAULT_NEW_ROLES);      _advuser_mail_roles($user_subject, $user_body, $from);
575      $result = _advuser_dbquery_users_to_notify($roles);    }
576    }
577    
578    /**
579     * @public
580     * List of users for given roles
581     *
582     * @param string $perm                  // The string permission.
583     * @return array                        // An array of uid.
584     */
585    function users_by_access($perm) {
586      $select_permissions = "SELECT ur.uid FROM {permission} p LEFT JOIN {users_roles} ur ON ur.rid = p.rid WHERE p.perm like '%%%s%%'";
587      $ret = array();
588      $result = db_query($select_permissions, $perm);
589      while ($data = db_fetch_object($result)) {
590        if (isset($data->uid)) {
591          $ret[] = $data->uid;
592        }
593      }
594      return $ret;
595    }
596    
597    /**
598     * @private
599     * Mail users in requested notification role.
600     *
601     * @param string $user_subject
602     * @param string $user_body
603     * @param string $from
604     */
605    function _advuser_mail_roles ($user_subject, $user_body, $from) {
606      static $mail_list = array();
607      if (empty($mail_list)) {
608        $result = _advuser_dbquery_users_to_notify();
609      while ($row = db_fetch_object($result)) {      while ($row = db_fetch_object($result)) {
610        drupal_mail('advanced-user-mail', $row->mail, $user_subject, $user_body, $from);        $mail_list[] = $row->mail;
611      }      }
612    }    }
613      foreach ($mail_list as $to) {
614        drupal_mail('advanced-user-mail', $to, $user_subject, $user_body, $from);
615      }
616  }  }
617    
618  /**  /**
# Line 856  function advuser_user_insert($edit, $use Line 620  function advuser_user_insert($edit, $use
620   */   */
621    
622  /**  /**
623   * Handle user edit   * Notify administrator of user profile edit.
  * TODO: DRY (don't repeat yourself!)  
624   */   */
625  function advuser_user_update($edit, $user, $category) {  function advuser_user_update($edit, $user, $category) {
626    // send mail    // Check to see if we notify the administrator of the modified user profile.
627    if ( variable_get('advuser_modify_notify', ADVUSER_DEFAULT_MODIFY_NOTIFY) ) {    // Only send if the user isn't modified by an administrator.
628      $modify_notify = variable_get('advuser_modify_notify', FALSE) &&
629                     ! user_access('administer users');
630      if ($modify_notify) {
631      $from = variable_get("site_mail", ini_get("sendmail_from"));      $from = variable_get("site_mail", ini_get("sendmail_from"));
632      $body = variable_get('advuser_modify_mail', ADVUSER_DEFAULT_MODIFY_MAIL);      $body = variable_get('advuser_modify_mail', NULL);
633      $subject = variable_get('advuser_modify_subject', ADVUSER_DEFAULT_MODIFY_SUBJECT);      $subject = variable_get('advuser_modify_subject', NULL);
634    
635      // these are invariant for all sent emails      // these are invariant for all sent emails
636      $variables = _advuser_get_variables($user);      $variables = _advuser_get_variables($user);
# Line 873  function advuser_user_update($edit, $use Line 639  function advuser_user_update($edit, $use
639    
640      watchdog('advuser', "Sending user account mail: subj='$user_subject' body='$user_body'");      watchdog('advuser', "Sending user account mail: subj='$user_subject' body='$user_body'");
641    
642      $roles = variable_get('advuser_new_roles', ADVUSER_DEFAULT_NEW_ROLES);      _advuser_mail_roles($user_subject, $user_body, $from);
     $result = _advuser_dbquery_users_to_notify($roles);  
     while ($row = db_fetch_object($result)) {  
       drupal_mail('advanced-user-mail', $row->mail, $user_subject, $user_body, $from);  
     }  
643    }    }
644  }  }
645    
# Line 886  function advuser_user_update($edit, $use Line 648  function advuser_user_update($edit, $use
648   * hook_user implementation   * hook_user implementation
649   */   */
650  function advuser_user($type, &$edit, &$user, $category = NULL) {  function advuser_user($type, &$edit, &$user, $category = NULL) {
651      $return = NULL;
652    switch ($type) {    switch ($type) {
653    case 'insert':      case 'insert': {
654      return advuser_user_insert($edit, $user, $category);        $return = advuser_user_insert($edit, $user, $category);
655    case 'update':      } break;
656      return advuser_user_update($edit, $user, $category);      case 'after_update': {
657          $return = advuser_user_update($edit, $user, $category);
658        } break;
659      }
660      return $return;
661    }
662    
663    /**
664     * Selected Profile Fields
665     * @return array
666     */
667    function advuser_profile_fields() {
668      static $ret = array();
669      if (!count($ret) && module_exists('profile')) {
670        $fields = variable_get('advuser_profile_fields', NULL);
671        if (is_array($fields)) {
672          foreach ( $fields as $fid => $value) {
673            if ( $value ) {
674              $ret[]= db_fetch_object(db_query('SELECT * FROM {profile_fields} WHERE fid = %d', $fid));
675            }
676          }
677        }
678      }
679      return $ret;
680    }
681    
682    /**
683     * Profile Field Values
684     *
685     * @param int $fid
686     * @param int $uid
687     * @return mixed
688     */
689    function advuser_profile_value($fid, $uid) {
690      $ret = db_result(db_query("SELECT value FROM {profile_values} WHERE fid = %d and uid = %d", $fid, $uid));
691      if ($ret === FALSE) {
692        $ret = NULL;
693      }
694      return $ret;
695    }
696    
697    /**
698     * User Roles for use in ADVUSER.
699     *
700     * @return array
701     */
702    function advuser_user_roles() {
703      static $roles;
704      if (empty($roles)) {
705        $roles = user_roles(1);
706        unset ($roles[DRUPAL_AUTHENTICATED_RID]);
707    }    }
708      return $roles;
   //print $type;  
709  }  }
710    
711  // vim:ft=php:et:sw=2:ts=2:sts=2:ai:sta  // vim:ft=php:sts=2:sw=2:ts=2:et:ai:sta:ff=unix

Legend:
Removed from v.1.13  
changed lines
  Added in v.1.14

  ViewVC Help
Powered by ViewVC 1.1.3