web/drupal/modules/user/user.module
branchdrupal
changeset 74 0ff3ba646492
equal deleted inserted replaced
73:fcf75e232c5b 74:0ff3ba646492
       
     1 <?php
       
     2 // $Id: user.module,v 1.892.2.14 2009/07/01 20:51:56 goba Exp $
       
     3 
       
     4 /**
       
     5  * @file
       
     6  * Enables the user registration and login system.
       
     7  */
       
     8 
       
     9 define('USERNAME_MAX_LENGTH', 60);
       
    10 define('EMAIL_MAX_LENGTH', 64);
       
    11 
       
    12 /**
       
    13  * Invokes hook_user() in every module.
       
    14  *
       
    15  * We cannot use module_invoke() for this, because the arguments need to
       
    16  * be passed by reference.
       
    17  */
       
    18 function user_module_invoke($type, &$array, &$user, $category = NULL) {
       
    19   foreach (module_list() as $module) {
       
    20     $function = $module .'_user';
       
    21     if (function_exists($function)) {
       
    22       $function($type, $array, $user, $category);
       
    23     }
       
    24   }
       
    25 }
       
    26 
       
    27 /**
       
    28  * Implementation of hook_theme().
       
    29  */
       
    30 function user_theme() {
       
    31   return array(
       
    32     'user_picture' => array(
       
    33       'arguments' => array('account' => NULL),
       
    34       'template' => 'user-picture',
       
    35     ),
       
    36     'user_profile' => array(
       
    37       'arguments' => array('account' => NULL),
       
    38       'template' => 'user-profile',
       
    39       'file' => 'user.pages.inc',
       
    40     ),
       
    41     'user_profile_category' => array(
       
    42       'arguments' => array('element' => NULL),
       
    43       'template' => 'user-profile-category',
       
    44       'file' => 'user.pages.inc',
       
    45     ),
       
    46     'user_profile_item' => array(
       
    47       'arguments' => array('element' => NULL),
       
    48       'template' => 'user-profile-item',
       
    49       'file' => 'user.pages.inc',
       
    50     ),
       
    51     'user_list' => array(
       
    52       'arguments' => array('users' => NULL, 'title' => NULL),
       
    53     ),
       
    54     'user_admin_perm' => array(
       
    55       'arguments' => array('form' => NULL),
       
    56       'file' => 'user.admin.inc',
       
    57     ),
       
    58     'user_admin_new_role' => array(
       
    59       'arguments' => array('form' => NULL),
       
    60       'file' => 'user.admin.inc',
       
    61     ),
       
    62     'user_admin_account' => array(
       
    63       'arguments' => array('form' => NULL),
       
    64       'file' => 'user.admin.inc',
       
    65     ),
       
    66     'user_filter_form' => array(
       
    67       'arguments' => array('form' => NULL),
       
    68       'file' => 'user.admin.inc',
       
    69     ),
       
    70     'user_filters' => array(
       
    71       'arguments' => array('form' => NULL),
       
    72       'file' => 'user.admin.inc',
       
    73     ),
       
    74     'user_signature' => array(
       
    75       'arguments' => array('signature' => NULL),
       
    76     ),
       
    77   );
       
    78 }
       
    79 
       
    80 function user_external_load($authname) {
       
    81   $result = db_query("SELECT uid FROM {authmap} WHERE authname = '%s'", $authname);
       
    82 
       
    83   if ($user = db_fetch_array($result)) {
       
    84     return user_load($user);
       
    85   }
       
    86   else {
       
    87     return 0;
       
    88   }
       
    89 }
       
    90 
       
    91 /**
       
    92  * Perform standard Drupal login operations for a user object.
       
    93  *
       
    94  * The user object must already be authenticated. This function verifies
       
    95  * that the user account is not blocked/denied and then performs the login,
       
    96  * updates the login timestamp in the database, invokes hook_user('login'),
       
    97  * and regenerates the session.
       
    98  *
       
    99  * @param $account
       
   100  *    An authenticated user object to be set as the currently logged
       
   101  *    in user.
       
   102  * @param $edit
       
   103  *    The array of form values submitted by the user, if any.
       
   104  *    This array is passed to hook_user op login.
       
   105  * @return boolean
       
   106  *    TRUE if the login succeeds, FALSE otherwise.
       
   107  */
       
   108 function user_external_login($account, $edit = array()) {
       
   109   $form = drupal_get_form('user_login');
       
   110 
       
   111   $state['values'] = $edit;
       
   112   if (empty($state['values']['name'])) {
       
   113     $state['values']['name'] = $account->name;
       
   114   }
       
   115 
       
   116   // Check if user is blocked or denied by access rules.
       
   117   user_login_name_validate($form, $state, (array)$account);
       
   118   if (form_get_errors()) {
       
   119     // Invalid login.
       
   120     return FALSE;
       
   121   }
       
   122 
       
   123   // Valid login.
       
   124   global $user;
       
   125   $user = $account;
       
   126   user_authenticate_finalize($state['values']);
       
   127   return TRUE;
       
   128 }
       
   129 
       
   130 /**
       
   131  * Fetch a user object.
       
   132  *
       
   133  * @param $array
       
   134  *   An associative array of attributes to search for in selecting the
       
   135  *   user, such as user name or e-mail address.
       
   136  *
       
   137  * @return
       
   138  *   A fully-loaded $user object upon successful user load or FALSE if user
       
   139  *   cannot be loaded.
       
   140  */
       
   141 function user_load($array = array()) {
       
   142   // Dynamically compose a SQL query:
       
   143   $query = array();
       
   144   $params = array();
       
   145 
       
   146   if (is_numeric($array)) {
       
   147     $array = array('uid' => $array);
       
   148   }
       
   149   elseif (!is_array($array)) {
       
   150     return FALSE;
       
   151   }
       
   152 
       
   153   foreach ($array as $key => $value) {
       
   154     if ($key == 'uid' || $key == 'status') {
       
   155       $query[] = "$key = %d";
       
   156       $params[] = $value;
       
   157     }
       
   158     else if ($key == 'pass') {
       
   159       $query[] = "pass = '%s'";
       
   160       $params[] = md5($value);
       
   161     }
       
   162     else {
       
   163       $query[]= "LOWER($key) = LOWER('%s')";
       
   164       $params[] = $value;
       
   165     }
       
   166   }
       
   167   $result = db_query('SELECT * FROM {users} u WHERE '. implode(' AND ', $query), $params);
       
   168 
       
   169   if ($user = db_fetch_object($result)) {
       
   170     $user = drupal_unpack($user);
       
   171 
       
   172     $user->roles = array();
       
   173     if ($user->uid) {
       
   174       $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
       
   175     }
       
   176     else {
       
   177       $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
       
   178     }
       
   179     $result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d', $user->uid);
       
   180     while ($role = db_fetch_object($result)) {
       
   181       $user->roles[$role->rid] = $role->name;
       
   182     }
       
   183     user_module_invoke('load', $array, $user);
       
   184   }
       
   185   else {
       
   186     $user = FALSE;
       
   187   }
       
   188 
       
   189   return $user;
       
   190 }
       
   191 
       
   192 /**
       
   193  * Save changes to a user account or add a new user.
       
   194  *
       
   195  * @param $account
       
   196  *   The $user object for the user to modify or add. If $user->uid is
       
   197  *   omitted, a new user will be added.
       
   198  *
       
   199  * @param $array
       
   200  *   (optional) An array of fields and values to save. For example,
       
   201  *   array('name' => 'My name'); Setting a field to NULL deletes it from
       
   202  *   the data column.
       
   203  *
       
   204  * @param $category
       
   205  *   (optional) The category for storing profile information in.
       
   206  *
       
   207  * @return
       
   208  *   A fully-loaded $user object upon successful save or FALSE if the save failed.
       
   209  */
       
   210 function user_save($account, $array = array(), $category = 'account') {
       
   211   // Dynamically compose a SQL query:
       
   212   $user_fields = user_fields();
       
   213   if (is_object($account) && $account->uid) {
       
   214     user_module_invoke('update', $array, $account, $category);
       
   215     $query = '';
       
   216     $data = unserialize(db_result(db_query('SELECT data FROM {users} WHERE uid = %d', $account->uid)));
       
   217     // Consider users edited by an administrator as logged in, if they haven't
       
   218     // already, so anonymous users can view the profile (if allowed).
       
   219     if (empty($array['access']) && empty($account->access) && user_access('administer users')) {
       
   220       $array['access'] = time();
       
   221     }
       
   222     foreach ($array as $key => $value) {
       
   223       if ($key == 'pass' && !empty($value)) {
       
   224         $query .= "$key = '%s', ";
       
   225         $v[] = md5($value);
       
   226       }
       
   227       else if ((substr($key, 0, 4) !== 'auth') && ($key != 'pass')) {
       
   228         if (in_array($key, $user_fields)) {
       
   229           // Save standard fields.
       
   230           $query .= "$key = '%s', ";
       
   231           $v[] = $value;
       
   232         }
       
   233         else if ($key != 'roles') {
       
   234           // Roles is a special case: it used below.
       
   235           if ($value === NULL) {
       
   236             unset($data[$key]);
       
   237           }
       
   238           else {
       
   239             $data[$key] = $value;
       
   240           }
       
   241         }
       
   242       }
       
   243     }
       
   244     $query .= "data = '%s' ";
       
   245     $v[] = serialize($data);
       
   246 
       
   247     $success = db_query("UPDATE {users} SET $query WHERE uid = %d", array_merge($v, array($account->uid)));
       
   248     if (!$success) {
       
   249       // The query failed - better to abort the save than risk further data loss.
       
   250       return FALSE;
       
   251     }
       
   252 
       
   253     // Reload user roles if provided.
       
   254     if (isset($array['roles']) && is_array($array['roles'])) {
       
   255       db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);
       
   256 
       
   257       foreach (array_keys($array['roles']) as $rid) {
       
   258         if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
       
   259           db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, $rid);
       
   260         }
       
   261       }
       
   262     }
       
   263 
       
   264     // Delete a blocked user's sessions to kick them if they are online.
       
   265     if (isset($array['status']) && $array['status'] == 0) {
       
   266       sess_destroy_uid($account->uid);
       
   267     }
       
   268 
       
   269     // If the password changed, delete all open sessions and recreate
       
   270     // the current one.
       
   271     if (!empty($array['pass'])) {
       
   272       sess_destroy_uid($account->uid);
       
   273       if ($account->uid == $GLOBALS['user']->uid) {
       
   274         sess_regenerate();
       
   275       }
       
   276     }
       
   277 
       
   278     // Refresh user object.
       
   279     $user = user_load(array('uid' => $account->uid));
       
   280 
       
   281     // Send emails after we have the new user object.
       
   282     if (isset($array['status']) && $array['status'] != $account->status) {
       
   283       // The user's status is changing; conditionally send notification email.
       
   284       $op = $array['status'] == 1 ? 'status_activated' : 'status_blocked';
       
   285       _user_mail_notify($op, $user);
       
   286     }
       
   287 
       
   288     user_module_invoke('after_update', $array, $user, $category);
       
   289   }
       
   290   else {
       
   291     // Allow 'created' to be set by the caller.
       
   292     if (!isset($array['created'])) {
       
   293       $array['created'] = time();
       
   294     }
       
   295     // Consider users created by an administrator as already logged in, so
       
   296     // anonymous users can view the profile (if allowed).
       
   297     if (empty($array['access']) && user_access('administer users')) {
       
   298       $array['access'] = time();
       
   299     }
       
   300 
       
   301     // Note: we wait to save the data column to prevent module-handled
       
   302     // fields from being saved there. We cannot invoke hook_user('insert') here
       
   303     // because we don't have a fully initialized user object yet.
       
   304     foreach ($array as $key => $value) {
       
   305       switch ($key) {
       
   306         case 'pass':
       
   307           $fields[] = $key;
       
   308           $values[] = md5($value);
       
   309           $s[] = "'%s'";
       
   310           break;
       
   311         case 'mode':       case 'sort':     case 'timezone':
       
   312         case 'threshold':  case 'created':  case 'access':
       
   313         case 'login':      case 'status':
       
   314           $fields[] = $key;
       
   315           $values[] = $value;
       
   316           $s[] = "%d";
       
   317           break;
       
   318         default:
       
   319           if (substr($key, 0, 4) !== 'auth' && in_array($key, $user_fields)) {
       
   320             $fields[] = $key;
       
   321             $values[] = $value;
       
   322             $s[] = "'%s'";
       
   323           }
       
   324           break;
       
   325       }
       
   326     }
       
   327     $success = db_query('INSERT INTO {users} ('. implode(', ', $fields) .') VALUES ('. implode(', ', $s) .')', $values);
       
   328     if (!$success) {
       
   329       // On a failed INSERT some other existing user's uid may be returned.
       
   330       // We must abort to avoid overwriting their account.
       
   331       return FALSE;
       
   332     }
       
   333 
       
   334     // Build the initial user object.
       
   335     $array['uid'] = db_last_insert_id('users', 'uid');
       
   336     $user = user_load(array('uid' => $array['uid']));
       
   337 
       
   338     user_module_invoke('insert', $array, $user, $category);
       
   339 
       
   340     // Build and save the serialized data field now.
       
   341     $data = array();
       
   342     foreach ($array as $key => $value) {
       
   343       if ((substr($key, 0, 4) !== 'auth') && ($key != 'roles') && (!in_array($key, $user_fields)) && ($value !== NULL)) {
       
   344         $data[$key] = $value;
       
   345       }
       
   346     }
       
   347     db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid);
       
   348 
       
   349     // Save user roles (delete just to be safe).
       
   350     if (isset($array['roles']) && is_array($array['roles'])) {
       
   351       db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
       
   352       foreach (array_keys($array['roles']) as $rid) {
       
   353         if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
       
   354           db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
       
   355         }
       
   356       }
       
   357     }
       
   358 
       
   359     // Build the finished user object.
       
   360     $user = user_load(array('uid' => $array['uid']));
       
   361   }
       
   362 
       
   363   // Save distributed authentication mappings.
       
   364   $authmaps = array();
       
   365   foreach ($array as $key => $value) {
       
   366     if (substr($key, 0, 4) == 'auth') {
       
   367       $authmaps[$key] = $value;
       
   368     }
       
   369   }
       
   370   if (sizeof($authmaps) > 0) {
       
   371     user_set_authmaps($user, $authmaps);
       
   372   }
       
   373 
       
   374   return $user;
       
   375 }
       
   376 
       
   377 /**
       
   378  * Verify the syntax of the given name.
       
   379  */
       
   380 function user_validate_name($name) {
       
   381   if (!strlen($name)) return t('You must enter a username.');
       
   382   if (substr($name, 0, 1) == ' ') return t('The username cannot begin with a space.');
       
   383   if (substr($name, -1) == ' ') return t('The username cannot end with a space.');
       
   384   if (strpos($name, '  ') !== FALSE) return t('The username cannot contain multiple spaces in a row.');
       
   385   if (ereg("[^\x80-\xF7 [:alnum:]@_.-]", $name)) return t('The username contains an illegal character.');
       
   386   if (preg_match('/[\x{80}-\x{A0}'.          // Non-printable ISO-8859-1 + NBSP
       
   387                    '\x{AD}'.                 // Soft-hyphen
       
   388                    '\x{2000}-\x{200F}'.      // Various space characters
       
   389                    '\x{2028}-\x{202F}'.      // Bidirectional text overrides
       
   390                    '\x{205F}-\x{206F}'.      // Various text hinting characters
       
   391                    '\x{FEFF}'.               // Byte order mark
       
   392                    '\x{FF01}-\x{FF60}'.      // Full-width latin
       
   393                    '\x{FFF9}-\x{FFFD}'.      // Replacement characters
       
   394                    '\x{0}]/u',               // NULL byte
       
   395                    $name)) {
       
   396     return t('The username contains an illegal character.');
       
   397   }
       
   398   if (strpos($name, '@') !== FALSE && !eregi('@([0-9a-z](-?[0-9a-z])*.)+[a-z]{2}([zmuvtg]|fo|me)?$', $name)) return t('The username is not a valid authentication ID.');
       
   399   if (strlen($name) > USERNAME_MAX_LENGTH) return t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => USERNAME_MAX_LENGTH));
       
   400 }
       
   401 
       
   402 function user_validate_mail($mail) {
       
   403   if (!$mail) return t('You must enter an e-mail address.');
       
   404   if (!valid_email_address($mail)) {
       
   405     return t('The e-mail address %mail is not valid.', array('%mail' => $mail));
       
   406   }
       
   407 }
       
   408 
       
   409 function user_validate_picture(&$form, &$form_state) {
       
   410   // If required, validate the uploaded picture.
       
   411   $validators = array(
       
   412     'file_validate_is_image' => array(),
       
   413     'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
       
   414     'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
       
   415   );
       
   416   if ($file = file_save_upload('picture_upload', $validators)) {
       
   417     // Remove the old picture.
       
   418     if (isset($form_state['values']['_account']->picture) && file_exists($form_state['values']['_account']->picture)) {
       
   419       file_delete($form_state['values']['_account']->picture);
       
   420     }
       
   421 
       
   422     // The image was saved using file_save_upload() and was added to the
       
   423     // files table as a temporary file. We'll make a copy and let the garbage
       
   424     // collector delete the original upload.
       
   425     $info = image_get_info($file->filepath);
       
   426     $destination = variable_get('user_picture_path', 'pictures') .'/picture-'. $form['#uid'] .'.'. $info['extension'];
       
   427     if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
       
   428       $form_state['values']['picture'] = $file->filepath;
       
   429     }
       
   430     else {
       
   431       form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
       
   432     }
       
   433   }
       
   434 }
       
   435 
       
   436 /**
       
   437  * Generate a random alphanumeric password.
       
   438  */
       
   439 function user_password($length = 10) {
       
   440   // This variable contains the list of allowable characters for the
       
   441   // password. Note that the number 0 and the letter 'O' have been
       
   442   // removed to avoid confusion between the two. The same is true
       
   443   // of 'I', 1, and 'l'.
       
   444   $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
       
   445 
       
   446   // Zero-based count of characters in the allowable list:
       
   447   $len = strlen($allowable_characters) - 1;
       
   448 
       
   449   // Declare the password as a blank string.
       
   450   $pass = '';
       
   451 
       
   452   // Loop the number of times specified by $length.
       
   453   for ($i = 0; $i < $length; $i++) {
       
   454 
       
   455     // Each iteration, pick a random character from the
       
   456     // allowable string and append it to the password:
       
   457     $pass .= $allowable_characters[mt_rand(0, $len)];
       
   458   }
       
   459 
       
   460   return $pass;
       
   461 }
       
   462 
       
   463 /**
       
   464  * Determine whether the user has a given privilege.
       
   465  *
       
   466  * @param $string
       
   467  *   The permission, such as "administer nodes", being checked for.
       
   468  * @param $account
       
   469  *   (optional) The account to check, if not given use currently logged in user.
       
   470  * @param $reset
       
   471  *   (optional) Resets the user's permissions cache, which will result in a
       
   472  *   recalculation of the user's permissions. This is necessary to support
       
   473  *   dynamically added user roles.
       
   474  *
       
   475  * @return
       
   476  *   Boolean TRUE if the current user has the requested permission.
       
   477  *
       
   478  * All permission checks in Drupal should go through this function. This
       
   479  * way, we guarantee consistent behavior, and ensure that the superuser
       
   480  * can perform all actions.
       
   481  */
       
   482 function user_access($string, $account = NULL, $reset = FALSE) {
       
   483   global $user;
       
   484   static $perm = array();
       
   485 
       
   486   if ($reset) {
       
   487     $perm = array();
       
   488   }
       
   489 
       
   490   if (is_null($account)) {
       
   491     $account = $user;
       
   492   }
       
   493 
       
   494   // User #1 has all privileges:
       
   495   if ($account->uid == 1) {
       
   496     return TRUE;
       
   497   }
       
   498 
       
   499   // To reduce the number of SQL queries, we cache the user's permissions
       
   500   // in a static variable.
       
   501   if (!isset($perm[$account->uid])) {
       
   502     $result = db_query("SELECT p.perm FROM {role} r INNER JOIN {permission} p ON p.rid = r.rid WHERE r.rid IN (". db_placeholders($account->roles) .")", array_keys($account->roles));
       
   503 
       
   504     $perms = array();
       
   505     while ($row = db_fetch_object($result)) {
       
   506       $perms += array_flip(explode(', ', $row->perm));
       
   507     }
       
   508     $perm[$account->uid] = $perms;
       
   509   }
       
   510 
       
   511   return isset($perm[$account->uid][$string]);
       
   512 }
       
   513 
       
   514 /**
       
   515  * Checks for usernames blocked by user administration.
       
   516  *
       
   517  * @return boolean TRUE for blocked users, FALSE for active.
       
   518  */
       
   519 function user_is_blocked($name) {
       
   520   $deny = db_fetch_object(db_query("SELECT name FROM {users} WHERE status = 0 AND name = LOWER('%s')", $name));
       
   521 
       
   522   return $deny;
       
   523 }
       
   524 
       
   525 function user_fields() {
       
   526   static $fields;
       
   527 
       
   528   if (!$fields) {
       
   529     $result = db_query('SELECT * FROM {users} WHERE uid = 1');
       
   530     if ($field = db_fetch_array($result)) {
       
   531       $fields = array_keys($field);
       
   532     }
       
   533     else {
       
   534       // Make sure we return the default fields at least.
       
   535       $fields = array('uid', 'name', 'pass', 'mail', 'picture', 'mode', 'sort', 'threshold', 'theme', 'signature', 'signature_format', 'created', 'access', 'login', 'status', 'timezone', 'language', 'init', 'data');
       
   536     }
       
   537   }
       
   538 
       
   539   return $fields;
       
   540 }
       
   541 
       
   542 /**
       
   543  * Implementation of hook_perm().
       
   544  */
       
   545 function user_perm() {
       
   546   return array('administer permissions', 'administer users', 'access user profiles', 'change own username');
       
   547 }
       
   548 
       
   549 /**
       
   550  * Implementation of hook_file_download().
       
   551  *
       
   552  * Ensure that user pictures (avatars) are always downloadable.
       
   553  */
       
   554 function user_file_download($file) {
       
   555   if (strpos($file, variable_get('user_picture_path', 'pictures') .'/picture-') === 0) {
       
   556     $info = image_get_info(file_create_path($file));
       
   557     return array('Content-type: '. $info['mime_type']);
       
   558   }
       
   559 }
       
   560 
       
   561 /**
       
   562  * Implementation of hook_search().
       
   563  */
       
   564 function user_search($op = 'search', $keys = NULL, $skip_access_check = FALSE) {
       
   565   switch ($op) {
       
   566     case 'name':
       
   567       if ($skip_access_check || user_access('access user profiles')) {
       
   568         return t('Users');
       
   569       }
       
   570     case 'search':
       
   571       if (user_access('access user profiles')) {
       
   572         $find = array();
       
   573         // Replace wildcards with MySQL/PostgreSQL wildcards.
       
   574         $keys = preg_replace('!\*+!', '%', $keys);
       
   575         if (user_access('administer users')) {
       
   576           // Administrators can also search in the otherwise private email field.
       
   577           $result = pager_query("SELECT name, uid, mail FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%') OR LOWER(mail) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys, $keys);
       
   578           while ($account = db_fetch_object($result)) {
       
   579             $find[] = array('title' => $account->name .' ('. $account->mail .')', 'link' => url('user/'. $account->uid, array('absolute' => TRUE)));
       
   580           }
       
   581         }
       
   582         else {
       
   583           $result = pager_query("SELECT name, uid FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys);
       
   584           while ($account = db_fetch_object($result)) {
       
   585             $find[] = array('title' => $account->name, 'link' => url('user/'. $account->uid, array('absolute' => TRUE)));
       
   586           }
       
   587         }
       
   588         return $find;
       
   589       }
       
   590   }
       
   591 }
       
   592 
       
   593 /**
       
   594  * Implementation of hook_elements().
       
   595  */
       
   596 function user_elements() {
       
   597   return array(
       
   598     'user_profile_category' => array(),
       
   599     'user_profile_item' => array(),
       
   600   );
       
   601 }
       
   602 
       
   603 /**
       
   604  * Implementation of hook_user().
       
   605  */
       
   606 function user_user($type, &$edit, &$account, $category = NULL) {
       
   607   if ($type == 'view') {
       
   608     $account->content['user_picture'] = array(
       
   609       '#value' => theme('user_picture', $account),
       
   610       '#weight' => -10,
       
   611     );
       
   612     if (!isset($account->content['summary'])) {
       
   613       $account->content['summary'] = array();
       
   614     }
       
   615     $account->content['summary'] += array(
       
   616       '#type' => 'user_profile_category',
       
   617       '#attributes' => array('class' => 'user-member'),
       
   618       '#weight' => 5,
       
   619       '#title' => t('History'),
       
   620     );
       
   621     $account->content['summary']['member_for'] =  array(
       
   622       '#type' => 'user_profile_item',
       
   623       '#title' => t('Member for'),
       
   624       '#value' => format_interval(time() - $account->created),
       
   625     );
       
   626   }
       
   627   if ($type == 'form' && $category == 'account') {
       
   628     $form_state = array();
       
   629     return user_edit_form($form_state, (isset($account->uid) ? $account->uid : FALSE), $edit);
       
   630   }
       
   631 
       
   632   if ($type == 'validate' && $category == 'account') {
       
   633     return _user_edit_validate((isset($account->uid) ? $account->uid : FALSE), $edit);
       
   634   }
       
   635 
       
   636   if ($type == 'submit' && $category == 'account') {
       
   637     return _user_edit_submit((isset($account->uid) ? $account->uid : FALSE), $edit);
       
   638   }
       
   639 
       
   640   if ($type == 'categories') {
       
   641     return array(array('name' => 'account', 'title' => t('Account settings'), 'weight' => 1));
       
   642   }
       
   643 }
       
   644 
       
   645 function user_login_block() {
       
   646   $form = array(
       
   647     '#action' => url($_GET['q'], array('query' => drupal_get_destination())),
       
   648     '#id' => 'user-login-form',
       
   649     '#validate' => user_login_default_validators(),
       
   650     '#submit' => array('user_login_submit'),
       
   651   );
       
   652   $form['name'] = array('#type' => 'textfield',
       
   653     '#title' => t('Username'),
       
   654     '#maxlength' => USERNAME_MAX_LENGTH,
       
   655     '#size' => 15,
       
   656     '#required' => TRUE,
       
   657   );
       
   658   $form['pass'] = array('#type' => 'password',
       
   659     '#title' => t('Password'),
       
   660     '#maxlength' => 60,
       
   661     '#size' => 15,
       
   662     '#required' => TRUE,
       
   663   );
       
   664   $form['submit'] = array('#type' => 'submit',
       
   665     '#value' => t('Log in'),
       
   666   );
       
   667   $items = array();
       
   668   if (variable_get('user_register', 1)) {
       
   669     $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
       
   670   }
       
   671   $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('Request new password via e-mail.'))));
       
   672   $form['links'] = array('#value' => theme('item_list', $items));
       
   673   return $form;
       
   674 }
       
   675 
       
   676 /**
       
   677  * Implementation of hook_block().
       
   678  */
       
   679 function user_block($op = 'list', $delta = 0, $edit = array()) {
       
   680   global $user;
       
   681 
       
   682   if ($op == 'list') {
       
   683     $blocks[0]['info'] = t('User login');
       
   684     // Not worth caching.
       
   685     $blocks[0]['cache'] = BLOCK_NO_CACHE;
       
   686 
       
   687     $blocks[1]['info'] = t('Navigation');
       
   688     // Menu blocks can't be cached because each menu item can have
       
   689     // a custom access callback. menu.inc manages its own caching.
       
   690     $blocks[1]['cache'] = BLOCK_NO_CACHE;
       
   691 
       
   692     $blocks[2]['info'] = t('Who\'s new');
       
   693 
       
   694     // Too dynamic to cache.
       
   695     $blocks[3]['info'] = t('Who\'s online');
       
   696     $blocks[3]['cache'] = BLOCK_NO_CACHE;
       
   697     return $blocks;
       
   698   }
       
   699   else if ($op == 'configure' && $delta == 2) {
       
   700     $form['user_block_whois_new_count'] = array(
       
   701       '#type' => 'select',
       
   702       '#title' => t('Number of users to display'),
       
   703       '#default_value' => variable_get('user_block_whois_new_count', 5),
       
   704       '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)),
       
   705     );
       
   706     return $form;
       
   707   }
       
   708   else if ($op == 'configure' && $delta == 3) {
       
   709     $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval');
       
   710     $form['user_block_seconds_online'] = array('#type' => 'select', '#title' => t('User activity'), '#default_value' => variable_get('user_block_seconds_online', 900), '#options' => $period, '#description' => t('A user is considered online for this long after they have last viewed a page.'));
       
   711     $form['user_block_max_list_count'] = array('#type' => 'select', '#title' => t('User list length'), '#default_value' => variable_get('user_block_max_list_count', 10), '#options' => drupal_map_assoc(array(0, 5, 10, 15, 20, 25, 30, 40, 50, 75, 100)), '#description' => t('Maximum number of currently online users to display.'));
       
   712 
       
   713     return $form;
       
   714   }
       
   715   else if ($op == 'save' && $delta == 2) {
       
   716     variable_set('user_block_whois_new_count', $edit['user_block_whois_new_count']);
       
   717   }
       
   718   else if ($op == 'save' && $delta == 3) {
       
   719     variable_set('user_block_seconds_online', $edit['user_block_seconds_online']);
       
   720     variable_set('user_block_max_list_count', $edit['user_block_max_list_count']);
       
   721   }
       
   722   else if ($op == 'view') {
       
   723     $block = array();
       
   724 
       
   725     switch ($delta) {
       
   726       case 0:
       
   727         // For usability's sake, avoid showing two login forms on one page.
       
   728         if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
       
   729 
       
   730           $block['subject'] = t('User login');
       
   731           $block['content'] = drupal_get_form('user_login_block');
       
   732         }
       
   733         return $block;
       
   734 
       
   735       case 1:
       
   736         if ($menu = menu_tree()) {
       
   737           $block['subject'] = $user->uid ? check_plain($user->name) : t('Navigation');
       
   738           $block['content'] = $menu;
       
   739         }
       
   740         return $block;
       
   741 
       
   742       case 2:
       
   743         if (user_access('access content')) {
       
   744           // Retrieve a list of new users who have subsequently accessed the site successfully.
       
   745           $result = db_query_range('SELECT uid, name FROM {users} WHERE status != 0 AND access != 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5));
       
   746           while ($account = db_fetch_object($result)) {
       
   747             $items[] = $account;
       
   748           }
       
   749           $output = theme('user_list', $items);
       
   750 
       
   751           $block['subject'] = t('Who\'s new');
       
   752           $block['content'] = $output;
       
   753         }
       
   754         return $block;
       
   755 
       
   756       case 3:
       
   757         if (user_access('access content')) {
       
   758           // Count users active within the defined period.
       
   759           $interval = time() - variable_get('user_block_seconds_online', 900);
       
   760 
       
   761           // Perform database queries to gather online user lists.  We use s.timestamp
       
   762           // rather than u.access because it is much faster.
       
   763           $anonymous_count = sess_count($interval);
       
   764           $authenticated_users = db_query('SELECT DISTINCT u.uid, u.name, s.timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.timestamp >= %d AND s.uid > 0 ORDER BY s.timestamp DESC', $interval);
       
   765           $authenticated_count = 0;
       
   766           $max_users = variable_get('user_block_max_list_count', 10);
       
   767           $items = array();
       
   768           while ($account = db_fetch_object($authenticated_users)) {
       
   769             if ($max_users > 0) {
       
   770               $items[] = $account;
       
   771               $max_users--;
       
   772             }
       
   773             $authenticated_count++;
       
   774           }
       
   775 
       
   776           // Format the output with proper grammar.
       
   777           if ($anonymous_count == 1 && $authenticated_count == 1) {
       
   778             $output = t('There is currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
       
   779           }
       
   780           else {
       
   781             $output = t('There are currently %members and %visitors online.', array('%members' => format_plural($authenticated_count, '1 user', '@count users'), '%visitors' => format_plural($anonymous_count, '1 guest', '@count guests')));
       
   782           }
       
   783 
       
   784           // Display a list of currently online users.
       
   785           $max_users = variable_get('user_block_max_list_count', 10);
       
   786           if ($authenticated_count && $max_users) {
       
   787             $output .= theme('user_list', $items, t('Online users'));
       
   788           }
       
   789 
       
   790           $block['subject'] = t('Who\'s online');
       
   791           $block['content'] = $output;
       
   792         }
       
   793         return $block;
       
   794     }
       
   795   }
       
   796 }
       
   797 
       
   798 /**
       
   799  * Process variables for user-picture.tpl.php.
       
   800  *
       
   801  * The $variables array contains the following arguments:
       
   802  * - $account
       
   803  *
       
   804  * @see user-picture.tpl.php
       
   805  */
       
   806 function template_preprocess_user_picture(&$variables) {
       
   807   $variables['picture'] = '';
       
   808   if (variable_get('user_pictures', 0)) {
       
   809     $account = $variables['account'];
       
   810     if (!empty($account->picture) && file_exists($account->picture)) {
       
   811       $picture = file_create_url($account->picture);
       
   812     }
       
   813     else if (variable_get('user_picture_default', '')) {
       
   814       $picture = variable_get('user_picture_default', '');
       
   815     }
       
   816 
       
   817     if (isset($picture)) {
       
   818       $alt = t("@user's picture", array('@user' => $account->name ? $account->name : variable_get('anonymous', t('Anonymous'))));
       
   819       $variables['picture'] = theme('image', $picture, $alt, $alt, '', FALSE);
       
   820       if (!empty($account->uid) && user_access('access user profiles')) {
       
   821         $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
       
   822         $variables['picture'] = l($variables['picture'], "user/$account->uid", $attributes);
       
   823       }
       
   824     }
       
   825   }
       
   826 }
       
   827 
       
   828 /**
       
   829  * Make a list of users.
       
   830  *
       
   831  * @param $users
       
   832  *   An array with user objects. Should contain at least the name and uid.
       
   833  * @param $title
       
   834  *  (optional) Title to pass on to theme_item_list().
       
   835  *
       
   836  * @ingroup themeable
       
   837  */
       
   838 function theme_user_list($users, $title = NULL) {
       
   839   if (!empty($users)) {
       
   840     foreach ($users as $user) {
       
   841       $items[] = theme('username', $user);
       
   842     }
       
   843   }
       
   844   return theme('item_list', $items, $title);
       
   845 }
       
   846 
       
   847 function user_is_anonymous() {
       
   848   // Menu administrators can see items for anonymous when administering.
       
   849   return !$GLOBALS['user']->uid || !empty($GLOBALS['menu_admin']);
       
   850 }
       
   851 
       
   852 function user_is_logged_in() {
       
   853   return (bool)$GLOBALS['user']->uid;
       
   854 }
       
   855 
       
   856 function user_register_access() {
       
   857   return user_is_anonymous() && variable_get('user_register', 1);
       
   858 }
       
   859 
       
   860 function user_view_access($account) {
       
   861   return $account && $account->uid &&
       
   862     (
       
   863       // Always let users view their own profile.
       
   864       ($GLOBALS['user']->uid == $account->uid) ||
       
   865       // Administrators can view all accounts.
       
   866       user_access('administer users') ||
       
   867       // The user is not blocked and logged in at least once.
       
   868       ($account->access && $account->status && user_access('access user profiles'))
       
   869     );
       
   870 }
       
   871 
       
   872 /**
       
   873  * Access callback for user account editing.
       
   874  */
       
   875 function user_edit_access($account) {
       
   876   return (($GLOBALS['user']->uid == $account->uid) || user_access('administer users')) && $account->uid > 0;
       
   877 }
       
   878 
       
   879 function user_load_self($arg) {
       
   880   $arg[1] = user_load($GLOBALS['user']->uid);
       
   881   return $arg;
       
   882 }
       
   883 
       
   884 /**
       
   885  * Implementation of hook_menu().
       
   886  */
       
   887 function user_menu() {
       
   888   $items['user/autocomplete'] = array(
       
   889     'title' => 'User autocomplete',
       
   890     'page callback' => 'user_autocomplete',
       
   891     'access callback' => 'user_access',
       
   892     'access arguments' => array('access user profiles'),
       
   893     'type' => MENU_CALLBACK,
       
   894     'file' => 'user.pages.inc',
       
   895   );
       
   896 
       
   897   // Registration and login pages.
       
   898   $items['user'] = array(
       
   899     'title' => 'User account',
       
   900     'page callback' => 'user_page',
       
   901     'access callback' => TRUE,
       
   902     'type' => MENU_CALLBACK,
       
   903     'file' => 'user.pages.inc',
       
   904   );
       
   905 
       
   906   $items['user/login'] = array(
       
   907     'title' => 'Log in',
       
   908     'access callback' => 'user_is_anonymous',
       
   909     'type' => MENU_DEFAULT_LOCAL_TASK,
       
   910   );
       
   911 
       
   912   $items['user/register'] = array(
       
   913     'title' => 'Create new account',
       
   914     'page callback' => 'drupal_get_form',
       
   915     'page arguments' => array('user_register'),
       
   916     'access callback' => 'user_register_access',
       
   917     'type' => MENU_LOCAL_TASK,
       
   918     'file' => 'user.pages.inc',
       
   919   );
       
   920 
       
   921   $items['user/password'] = array(
       
   922     'title' => 'Request new password',
       
   923     'page callback' => 'drupal_get_form',
       
   924     'page arguments' => array('user_pass'),
       
   925     'access callback' => 'user_is_anonymous',
       
   926     'type' => MENU_LOCAL_TASK,
       
   927     'file' => 'user.pages.inc',
       
   928   );
       
   929   $items['user/reset/%/%/%'] = array(
       
   930     'title' => 'Reset password',
       
   931     'page callback' => 'drupal_get_form',
       
   932     'page arguments' => array('user_pass_reset', 2, 3, 4),
       
   933     'access callback' => TRUE,
       
   934     'type' => MENU_CALLBACK,
       
   935     'file' => 'user.pages.inc',
       
   936   );
       
   937 
       
   938   // Admin user pages.
       
   939   $items['admin/user'] = array(
       
   940     'title' => 'User management',
       
   941     'description' => "Manage your site's users, groups and access to site features.",
       
   942     'position' => 'left',
       
   943     'page callback' => 'system_admin_menu_block_page',
       
   944     'access arguments' => array('access administration pages'),
       
   945     'file' => 'system.admin.inc',
       
   946     'file path' => drupal_get_path('module', 'system'),
       
   947   );
       
   948   $items['admin/user/user'] = array(
       
   949     'title' => 'Users',
       
   950     'description' => 'List, add, and edit users.',
       
   951     'page callback' => 'user_admin',
       
   952     'page arguments' => array('list'),
       
   953     'access arguments' => array('administer users'),
       
   954     'file' => 'user.admin.inc',
       
   955   );
       
   956   $items['admin/user/user/list'] = array(
       
   957     'title' => 'List',
       
   958     'type' => MENU_DEFAULT_LOCAL_TASK,
       
   959     'weight' => -10,
       
   960   );
       
   961   $items['admin/user/user/create'] = array(
       
   962     'title' => 'Add user',
       
   963     'page arguments' => array('create'),
       
   964     'access arguments' => array('administer users'),
       
   965     'type' => MENU_LOCAL_TASK,
       
   966     'file' => 'user.admin.inc',
       
   967   );
       
   968   $items['admin/user/settings'] = array(
       
   969     'title' => 'User settings',
       
   970     'description' => 'Configure default behavior of users, including registration requirements, e-mails, and user pictures.',
       
   971     'page callback' => 'drupal_get_form',
       
   972     'page arguments' => array('user_admin_settings'),
       
   973     'access arguments' => array('administer users'),
       
   974     'file' => 'user.admin.inc',
       
   975   );
       
   976 
       
   977   // Admin access pages.
       
   978   $items['admin/user/permissions'] = array(
       
   979     'title' => 'Permissions',
       
   980     'description' => 'Determine access to features by selecting permissions for roles.',
       
   981     'page callback' => 'drupal_get_form',
       
   982     'page arguments' => array('user_admin_perm'),
       
   983     'access arguments' => array('administer permissions'),
       
   984     'file' => 'user.admin.inc',
       
   985   );
       
   986   $items['admin/user/roles'] = array(
       
   987     'title' => 'Roles',
       
   988     'description' => 'List, edit, or add user roles.',
       
   989     'page callback' => 'drupal_get_form',
       
   990     'page arguments' => array('user_admin_new_role'),
       
   991     'access arguments' => array('administer permissions'),
       
   992     'file' => 'user.admin.inc',
       
   993   );
       
   994   $items['admin/user/roles/edit'] = array(
       
   995     'title' => 'Edit role',
       
   996     'page arguments' => array('user_admin_role'),
       
   997     'access arguments' => array('administer permissions'),
       
   998     'type' => MENU_CALLBACK,
       
   999     'file' => 'user.admin.inc',
       
  1000   );
       
  1001   $items['admin/user/rules'] = array(
       
  1002     'title' => 'Access rules',
       
  1003     'description' => 'List and create rules to disallow usernames, e-mail addresses, and IP addresses.',
       
  1004     'page callback' => 'user_admin_access',
       
  1005     'access arguments' => array('administer permissions'),
       
  1006     'file' => 'user.admin.inc',
       
  1007   );
       
  1008   $items['admin/user/rules/list'] = array(
       
  1009     'title' => 'List',
       
  1010     'type' => MENU_DEFAULT_LOCAL_TASK,
       
  1011     'weight' => -10,
       
  1012   );
       
  1013   $items['admin/user/rules/add'] = array(
       
  1014     'title' => 'Add rule',
       
  1015     'page callback' => 'user_admin_access_add',
       
  1016     'access arguments' => array('administer permissions'),
       
  1017     'type' => MENU_LOCAL_TASK,
       
  1018     'file' => 'user.admin.inc',
       
  1019   );
       
  1020   $items['admin/user/rules/check'] = array(
       
  1021     'title' => 'Check rules',
       
  1022     'page callback' => 'user_admin_access_check',
       
  1023     'access arguments' => array('administer permissions'),
       
  1024     'type' => MENU_LOCAL_TASK,
       
  1025     'file' => 'user.admin.inc',
       
  1026   );
       
  1027   $items['admin/user/rules/edit'] = array(
       
  1028     'title' => 'Edit rule',
       
  1029     'page callback' => 'user_admin_access_edit',
       
  1030     'access arguments' => array('administer permissions'),
       
  1031     'type' => MENU_CALLBACK,
       
  1032     'file' => 'user.admin.inc',
       
  1033   );
       
  1034   $items['admin/user/rules/delete'] = array(
       
  1035     'title' => 'Delete rule',
       
  1036     'page callback' => 'drupal_get_form',
       
  1037     'page arguments' => array('user_admin_access_delete_confirm'),
       
  1038     'access arguments' => array('administer permissions'),
       
  1039     'type' => MENU_CALLBACK,
       
  1040     'file' => 'user.admin.inc',
       
  1041   );
       
  1042 
       
  1043   $items['logout'] = array(
       
  1044     'title' => 'Log out',
       
  1045     'access callback' => 'user_is_logged_in',
       
  1046     'page callback' => 'user_logout',
       
  1047     'weight' => 10,
       
  1048     'file' => 'user.pages.inc',
       
  1049   );
       
  1050 
       
  1051   $items['user/%user_uid_optional'] = array(
       
  1052     'title' => 'My account',
       
  1053     'title callback' => 'user_page_title',
       
  1054     'title arguments' => array(1),
       
  1055     'page callback' => 'user_view',
       
  1056     'page arguments' => array(1),
       
  1057     'access callback' => 'user_view_access',
       
  1058     'access arguments' => array(1),
       
  1059     'parent' => '',
       
  1060     'file' => 'user.pages.inc',
       
  1061   );
       
  1062 
       
  1063   $items['user/%user/view'] = array(
       
  1064     'title' => 'View',
       
  1065     'type' => MENU_DEFAULT_LOCAL_TASK,
       
  1066     'weight' => -10,
       
  1067   );
       
  1068 
       
  1069   $items['user/%user/delete'] = array(
       
  1070     'title' => 'Delete',
       
  1071     'page callback' => 'drupal_get_form',
       
  1072     'page arguments' => array('user_confirm_delete', 1),
       
  1073     'access callback' => 'user_access',
       
  1074     'access arguments' => array('administer users'),
       
  1075     'type' => MENU_CALLBACK,
       
  1076     'file' => 'user.pages.inc',
       
  1077   );
       
  1078 
       
  1079   $items['user/%user_category/edit'] = array(
       
  1080     'title' => 'Edit',
       
  1081     'page callback' => 'user_edit',
       
  1082     'page arguments' => array(1),
       
  1083     'access callback' => 'user_edit_access',
       
  1084     'access arguments' => array(1),
       
  1085     'type' => MENU_LOCAL_TASK,
       
  1086     'load arguments' => array('%map', '%index'),
       
  1087     'file' => 'user.pages.inc',
       
  1088   );
       
  1089 
       
  1090   $items['user/%user_category/edit/account'] = array(
       
  1091     'title' => 'Account',
       
  1092     'type' => MENU_DEFAULT_LOCAL_TASK,
       
  1093     'load arguments' => array('%map', '%index'),
       
  1094   );
       
  1095 
       
  1096   $empty_account = new stdClass();
       
  1097   if (($categories = _user_categories($empty_account)) && (count($categories) > 1)) {
       
  1098     foreach ($categories as $key => $category) {
       
  1099       // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
       
  1100       if ($category['name'] != 'account') {
       
  1101         $items['user/%user_category/edit/'. $category['name']] = array(
       
  1102           'title callback' => 'check_plain',
       
  1103           'title arguments' => array($category['title']),
       
  1104           'page callback' => 'user_edit',
       
  1105           'page arguments' => array(1, 3),
       
  1106           'access callback' => isset($category['access callback']) ? $category['access callback'] : 'user_edit_access',
       
  1107           'access arguments' => isset($category['access arguments']) ? $category['access arguments'] : array(1),
       
  1108           'type' => MENU_LOCAL_TASK,
       
  1109           'weight' => $category['weight'],
       
  1110           'load arguments' => array('%map', '%index'),
       
  1111           'tab_parent' => 'user/%/edit',
       
  1112           'file' => 'user.pages.inc',
       
  1113         );
       
  1114       }
       
  1115     }
       
  1116   }
       
  1117   return $items;
       
  1118 }
       
  1119 
       
  1120 function user_init() {
       
  1121   drupal_add_css(drupal_get_path('module', 'user') .'/user.css', 'module');
       
  1122 }
       
  1123 
       
  1124 function user_uid_optional_load($arg) {
       
  1125   return user_load(isset($arg) ? $arg : $GLOBALS['user']->uid);
       
  1126 }
       
  1127 
       
  1128 /**
       
  1129  * Return a user object after checking if any profile category in the path exists.
       
  1130  */
       
  1131 function user_category_load($uid, &$map, $index) {
       
  1132   static $user_categories, $accounts;
       
  1133 
       
  1134   // Cache $account - this load function will get called for each profile tab.
       
  1135   if (!isset($accounts[$uid])) {
       
  1136     $accounts[$uid] = user_load($uid);
       
  1137   }
       
  1138   $valid = TRUE;
       
  1139   if ($account = $accounts[$uid]) {
       
  1140     // Since the path is like user/%/edit/category_name, the category name will
       
  1141     // be at a position 2 beyond the index corresponding to the % wildcard.
       
  1142     $category_index = $index + 2;
       
  1143     // Valid categories may contain slashes, and hence need to be imploded.
       
  1144     $category_path = implode('/', array_slice($map, $category_index));
       
  1145     if ($category_path) {
       
  1146       // Check that the requested category exists.
       
  1147       $valid = FALSE;
       
  1148       if (!isset($user_categories)) {
       
  1149         $empty_account = new stdClass();
       
  1150         $user_categories = _user_categories($empty_account);
       
  1151       }
       
  1152       foreach ($user_categories as $category) {
       
  1153         if ($category['name'] == $category_path) {
       
  1154           $valid = TRUE;
       
  1155           // Truncate the map array in case the category name had slashes.
       
  1156           $map = array_slice($map, 0, $category_index);
       
  1157           // Assign the imploded category name to the last map element.
       
  1158           $map[$category_index] = $category_path;
       
  1159           break;
       
  1160         }
       
  1161       }
       
  1162     }
       
  1163   }
       
  1164   return $valid ? $account : FALSE;
       
  1165 }
       
  1166 
       
  1167 /**
       
  1168  * Returns the user id of the currently logged in user.
       
  1169  */
       
  1170 function user_uid_optional_to_arg($arg) {
       
  1171   // Give back the current user uid when called from eg. tracker, aka.
       
  1172   // with an empty arg. Also use the current user uid when called from
       
  1173   // the menu with a % for the current account link.
       
  1174   return empty($arg) || $arg == '%' ? $GLOBALS['user']->uid : $arg;
       
  1175 }
       
  1176 
       
  1177 /**
       
  1178  * Menu item title callback - use the user name if it's not the current user.
       
  1179  */
       
  1180 function user_page_title($account) {
       
  1181   if ($account->uid == $GLOBALS['user']->uid) {
       
  1182     return t('My account');
       
  1183   }
       
  1184   return $account->name;
       
  1185 }
       
  1186 
       
  1187 /**
       
  1188  * Discover which external authentication module(s) authenticated a username.
       
  1189  *
       
  1190  * @param $authname
       
  1191  *   A username used by an external authentication module.
       
  1192  * @return
       
  1193  *   An associative array with module as key and username as value.
       
  1194  */
       
  1195 function user_get_authmaps($authname = NULL) {
       
  1196   $result = db_query("SELECT authname, module FROM {authmap} WHERE authname = '%s'", $authname);
       
  1197   $authmaps = array();
       
  1198   $has_rows = FALSE;
       
  1199   while ($authmap = db_fetch_object($result)) {
       
  1200     $authmaps[$authmap->module] = $authmap->authname;
       
  1201     $has_rows = TRUE;
       
  1202   }
       
  1203   return $has_rows ? $authmaps : 0;
       
  1204 }
       
  1205 
       
  1206 /**
       
  1207  * Save mappings of which external authentication module(s) authenticated
       
  1208  * a user. Maps external usernames to user ids in the users table.
       
  1209  *
       
  1210  * @param $account
       
  1211  *   A user object.
       
  1212  * @param $authmaps
       
  1213  *   An associative array with a compound key and the username as the value.
       
  1214  *   The key is made up of 'authname_' plus the name of the external authentication
       
  1215  *   module.
       
  1216  * @see user_external_login_register()
       
  1217  */
       
  1218 function user_set_authmaps($account, $authmaps) {
       
  1219   foreach ($authmaps as $key => $value) {
       
  1220     $module = explode('_', $key, 2);
       
  1221     if ($value) {
       
  1222       db_query("UPDATE {authmap} SET authname = '%s' WHERE uid = %d AND module = '%s'", $value, $account->uid, $module[1]);
       
  1223       if (!db_affected_rows()) {
       
  1224         db_query("INSERT INTO {authmap} (authname, uid, module) VALUES ('%s', %d, '%s')", $value, $account->uid, $module[1]);
       
  1225       }
       
  1226     }
       
  1227     else {
       
  1228       db_query("DELETE FROM {authmap} WHERE uid = %d AND module = '%s'", $account->uid, $module[1]);
       
  1229     }
       
  1230   }
       
  1231 }
       
  1232 
       
  1233 /**
       
  1234  * Form builder; the main user login form.
       
  1235  *
       
  1236  * @ingroup forms
       
  1237  */
       
  1238 function user_login(&$form_state) {
       
  1239   global $user;
       
  1240 
       
  1241   // If we are already logged on, go to the user page instead.
       
  1242   if ($user->uid) {
       
  1243     drupal_goto('user/'. $user->uid);
       
  1244   }
       
  1245 
       
  1246   // Display login form:
       
  1247   $form['name'] = array('#type' => 'textfield',
       
  1248     '#title' => t('Username'),
       
  1249     '#size' => 60,
       
  1250     '#maxlength' => USERNAME_MAX_LENGTH,
       
  1251     '#required' => TRUE,
       
  1252   );
       
  1253 
       
  1254   $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
       
  1255   $form['pass'] = array('#type' => 'password',
       
  1256     '#title' => t('Password'),
       
  1257     '#description' => t('Enter the password that accompanies your username.'),
       
  1258     '#required' => TRUE,
       
  1259   );
       
  1260   $form['#validate'] = user_login_default_validators();
       
  1261   $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), '#weight' => 2);
       
  1262 
       
  1263   return $form;
       
  1264 }
       
  1265 
       
  1266 /**
       
  1267  * Set up a series for validators which check for blocked/denied users,
       
  1268  * then authenticate against local database, then return an error if
       
  1269  * authentication fails. Distributed authentication modules are welcome
       
  1270  * to use hook_form_alter() to change this series in order to
       
  1271  * authenticate against their user database instead of the local users
       
  1272  * table.
       
  1273  *
       
  1274  * We use three validators instead of one since external authentication
       
  1275  * modules usually only need to alter the second validator.
       
  1276  *
       
  1277  * @see user_login_name_validate()
       
  1278  * @see user_login_authenticate_validate()
       
  1279  * @see user_login_final_validate()
       
  1280  * @return array
       
  1281  *   A simple list of validate functions.
       
  1282  */
       
  1283 function user_login_default_validators() {
       
  1284   return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
       
  1285 }
       
  1286 
       
  1287 /**
       
  1288  * A FAPI validate handler. Sets an error if supplied username has been blocked
       
  1289  * or denied access.
       
  1290  */
       
  1291 function user_login_name_validate($form, &$form_state) {
       
  1292   if (isset($form_state['values']['name'])) {
       
  1293     if (user_is_blocked($form_state['values']['name'])) {
       
  1294       // blocked in user administration
       
  1295       form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
       
  1296     }
       
  1297     else if (drupal_is_denied('user', $form_state['values']['name'])) {
       
  1298       // denied by access controls
       
  1299       form_set_error('name', t('The name %name is a reserved username.', array('%name' => $form_state['values']['name'])));
       
  1300     }
       
  1301   }
       
  1302 }
       
  1303 
       
  1304 /**
       
  1305  * A validate handler on the login form. Check supplied username/password
       
  1306  * against local users table. If successful, sets the global $user object.
       
  1307  */
       
  1308 function user_login_authenticate_validate($form, &$form_state) {
       
  1309   user_authenticate($form_state['values']);
       
  1310 }
       
  1311 
       
  1312 /**
       
  1313  * A validate handler on the login form. Should be the last validator. Sets an
       
  1314  * error if user has not been authenticated yet.
       
  1315  */
       
  1316 function user_login_final_validate($form, &$form_state) {
       
  1317   global $user;
       
  1318   if (!$user->uid) {
       
  1319     form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
       
  1320     watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_state['values']['name']));
       
  1321   }
       
  1322 }
       
  1323 
       
  1324 /**
       
  1325  * Try to log in the user locally.
       
  1326  *
       
  1327  * @param $form_values
       
  1328  *   Form values with at least 'name' and 'pass' keys, as well as anything else
       
  1329  *   which should be passed along to hook_user op 'login'.
       
  1330  *
       
  1331  * @return
       
  1332  *  A $user object, if successful.
       
  1333  */
       
  1334 function user_authenticate($form_values = array()) {
       
  1335   global $user;
       
  1336 
       
  1337   // Load the account to check if the e-mail is denied by an access rule.
       
  1338   // Doing this check here saves us a user_load() in user_login_name_validate()
       
  1339   // and introduces less code change for a security fix.
       
  1340   $account = user_load(array('name' => $form_values['name'], 'pass' => trim($form_values['pass']), 'status' => 1));
       
  1341   if ($account && drupal_is_denied('mail', $account->mail)) {
       
  1342     form_set_error('name', t('The name %name is registered using a reserved e-mail address and therefore could not be logged in.', array('%name' => $account->name)));
       
  1343   }
       
  1344 
       
  1345   // Name and pass keys are required.
       
  1346   // The user is about to be logged in, so make sure no error was previously
       
  1347   // encountered in the validation process.
       
  1348   if (!form_get_errors() && !empty($form_values['name']) && !empty($form_values['pass']) && $account) {
       
  1349     $user = $account;
       
  1350     user_authenticate_finalize($form_values);
       
  1351     return $user;
       
  1352   }
       
  1353 }
       
  1354 
       
  1355 /**
       
  1356  * Finalize the login process. Must be called when logging in a user.
       
  1357  *
       
  1358  * The function records a watchdog message about the new session, saves the
       
  1359  * login timestamp, calls hook_user op 'login' and generates a new session.
       
  1360  *
       
  1361  * $param $edit
       
  1362  *   This array is passed to hook_user op login.
       
  1363  */
       
  1364 function user_authenticate_finalize(&$edit) {
       
  1365   global $user;
       
  1366   watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
       
  1367   // Update the user table timestamp noting user has logged in.
       
  1368   // This is also used to invalidate one-time login links.
       
  1369   $user->login = time();
       
  1370   db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);
       
  1371 
       
  1372   // Regenerate the session ID to prevent against session fixation attacks.
       
  1373   sess_regenerate();
       
  1374   user_module_invoke('login', $edit, $user);
       
  1375 }
       
  1376 
       
  1377 /**
       
  1378  * Submit handler for the login form. Redirects the user to a page.
       
  1379  *
       
  1380  * The user is redirected to the My Account page. Setting the destination in
       
  1381  * the query string (as done by the user login block) overrides the redirect.
       
  1382  */
       
  1383 function user_login_submit($form, &$form_state) {
       
  1384   global $user;
       
  1385   if ($user->uid) {
       
  1386     $form_state['redirect'] = 'user/'. $user->uid;
       
  1387     return;
       
  1388   }
       
  1389 }
       
  1390 
       
  1391 /**
       
  1392  * Helper function for authentication modules. Either login in or registers
       
  1393  * the current user, based on username. Either way, the global $user object is
       
  1394  * populated based on $name.
       
  1395  */
       
  1396 function user_external_login_register($name, $module) {
       
  1397   global $user;
       
  1398 
       
  1399   $existing_user = user_load(array('name' => $name));
       
  1400   if (isset($existing_user->uid)) {
       
  1401     $user = $existing_user;
       
  1402   }
       
  1403   else {
       
  1404     // Register this new user.
       
  1405     $userinfo = array(
       
  1406       'name' => $name,
       
  1407       'pass' => user_password(),
       
  1408       'init' => $name,
       
  1409       'status' => 1,
       
  1410       "authname_$module" => $name,
       
  1411       'access' => time()
       
  1412     );
       
  1413     $account = user_save('', $userinfo);
       
  1414     // Terminate if an error occured during user_save().
       
  1415     if (!$account) {
       
  1416       drupal_set_message(t("Error saving user account."), 'error');
       
  1417       return;
       
  1418     }
       
  1419     $user = $account;
       
  1420     watchdog('user', 'New external user: %name using module %module.', array('%name' => $name, '%module' => $module), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $user->uid .'/edit'));
       
  1421   }
       
  1422 }
       
  1423 
       
  1424 function user_pass_reset_url($account) {
       
  1425   $timestamp = time();
       
  1426   return url("user/reset/$account->uid/$timestamp/". user_pass_rehash($account->pass, $timestamp, $account->login), array('absolute' => TRUE));
       
  1427 }
       
  1428 
       
  1429 function user_pass_rehash($password, $timestamp, $login) {
       
  1430   return md5($timestamp . $password . $login);
       
  1431 }
       
  1432 
       
  1433 function user_edit_form(&$form_state, $uid, $edit, $register = FALSE) {
       
  1434   _user_password_dynamic_validation();
       
  1435   $admin = user_access('administer users');
       
  1436 
       
  1437   // Account information:
       
  1438   $form['account'] = array('#type' => 'fieldset',
       
  1439     '#title' => t('Account information'),
       
  1440     '#weight' => -10,
       
  1441   );
       
  1442   // Only show name field when: registration page; or user is editing own account and can change username; or an admin user.
       
  1443   if ($register || ($GLOBALS['user']->uid == $uid && user_access('change own username')) || $admin) {
       
  1444     $form['account']['name'] = array('#type' => 'textfield',
       
  1445       '#title' => t('Username'),
       
  1446       '#default_value' => $edit['name'],
       
  1447       '#maxlength' => USERNAME_MAX_LENGTH,
       
  1448       '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.'),
       
  1449       '#required' => TRUE,
       
  1450     );
       
  1451   }
       
  1452   $form['account']['mail'] = array('#type' => 'textfield',
       
  1453     '#title' => t('E-mail address'),
       
  1454     '#default_value' => $edit['mail'],
       
  1455     '#maxlength' => EMAIL_MAX_LENGTH,
       
  1456     '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
       
  1457     '#required' => TRUE,
       
  1458   );
       
  1459   if (!$register) {
       
  1460     $form['account']['pass'] = array('#type' => 'password_confirm',
       
  1461       '#description' => t('To change the current user password, enter the new password in both fields.'),
       
  1462       '#size' => 25,
       
  1463     );
       
  1464   }
       
  1465   elseif (!variable_get('user_email_verification', TRUE) || $admin) {
       
  1466     $form['account']['pass'] = array(
       
  1467       '#type' => 'password_confirm',
       
  1468       '#description' => t('Provide a password for the new account in both fields.'),
       
  1469       '#required' => TRUE,
       
  1470       '#size' => 25,
       
  1471     );
       
  1472   }
       
  1473   if ($admin) {
       
  1474     $form['account']['status'] = array(
       
  1475       '#type' => 'radios',
       
  1476       '#title' => t('Status'),
       
  1477       '#default_value' => isset($edit['status']) ? $edit['status'] : 1,
       
  1478       '#options' => array(t('Blocked'), t('Active'))
       
  1479     );
       
  1480   }
       
  1481   if (user_access('administer permissions')) {
       
  1482     $roles = user_roles(TRUE);
       
  1483 
       
  1484     // The disabled checkbox subelement for the 'authenticated user' role
       
  1485     // must be generated separately and added to the checkboxes element,
       
  1486     // because of a limitation in D6 FormAPI not supporting a single disabled
       
  1487     // checkbox within a set of checkboxes.
       
  1488     // TODO: This should be solved more elegantly. See issue #119038.
       
  1489     $checkbox_authenticated = array(
       
  1490       '#type' => 'checkbox',
       
  1491       '#title' => $roles[DRUPAL_AUTHENTICATED_RID],
       
  1492       '#default_value' => TRUE,
       
  1493       '#disabled' => TRUE,
       
  1494     );
       
  1495 
       
  1496     unset($roles[DRUPAL_AUTHENTICATED_RID]);
       
  1497     if ($roles) {
       
  1498       $default = empty($edit['roles']) ? array() : array_keys($edit['roles']);
       
  1499       $form['account']['roles'] = array(
       
  1500         '#type' => 'checkboxes',
       
  1501         '#title' => t('Roles'),
       
  1502         '#default_value' => $default,
       
  1503         '#options' => $roles,
       
  1504         DRUPAL_AUTHENTICATED_RID => $checkbox_authenticated,
       
  1505       );
       
  1506     }
       
  1507   }
       
  1508 
       
  1509   // Signature:
       
  1510   if (variable_get('user_signatures', 0) && module_exists('comment') && !$register) {
       
  1511     $form['signature_settings'] = array(
       
  1512       '#type' => 'fieldset',
       
  1513       '#title' => t('Signature settings'),
       
  1514       '#weight' => 1,
       
  1515     );
       
  1516     $form['signature_settings']['signature'] = array(
       
  1517       '#type' => 'textarea',
       
  1518       '#title' => t('Signature'),
       
  1519       '#default_value' => $edit['signature'],
       
  1520       '#description' => t('Your signature will be publicly displayed at the end of your comments.'),
       
  1521     );
       
  1522 
       
  1523     // Prevent a "validation error" message when the user attempts to save with a default value they
       
  1524     // do not have access to.
       
  1525     if (!filter_access($edit['signature_format']) && empty($_POST)) {
       
  1526       drupal_set_message(t("The signature input format has been set to a format you don't have access to. It will be changed to a format you have access to when you save this page."));
       
  1527       $edit['signature_format'] = FILTER_FORMAT_DEFAULT;
       
  1528     }
       
  1529 
       
  1530     $form['signature_settings']['signature_format'] = filter_form($edit['signature_format'], NULL, array('signature_format'));
       
  1531   }
       
  1532 
       
  1533   // Picture/avatar:
       
  1534   if (variable_get('user_pictures', 0) && !$register) {
       
  1535     $form['picture'] = array('#type' => 'fieldset', '#title' => t('Picture'), '#weight' => 1);
       
  1536     $picture = theme('user_picture', (object)$edit);
       
  1537     if ($edit['picture']) {
       
  1538       $form['picture']['current_picture'] = array('#value' => $picture);
       
  1539       $form['picture']['picture_delete'] = array('#type' => 'checkbox', '#title' => t('Delete picture'), '#description' => t('Check this box to delete your current picture.'));
       
  1540     }
       
  1541     else {
       
  1542       $form['picture']['picture_delete'] = array('#type' => 'hidden');
       
  1543     }
       
  1544     $form['picture']['picture_upload'] = array('#type' => 'file', '#title' => t('Upload picture'), '#size' => 48, '#description' => t('Your virtual face or picture. Maximum dimensions are %dimensions and the maximum size is %size kB.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85'), '%size' => variable_get('user_picture_file_size', '30'))) .' '. variable_get('user_picture_guidelines', ''));
       
  1545     $form['#validate'][] = 'user_profile_form_validate';
       
  1546     $form['#validate'][] = 'user_validate_picture';
       
  1547   }
       
  1548   $form['#uid'] = $uid;
       
  1549 
       
  1550   return $form;
       
  1551 }
       
  1552 
       
  1553 function _user_edit_validate($uid, &$edit) {
       
  1554   // Validate the username when: new user account; or user is editing own account and can change username; or an admin user.
       
  1555   if (!$uid || ($GLOBALS['user']->uid == $uid && user_access('change own username')) || user_access('administer users')) {
       
  1556     if ($error = user_validate_name($edit['name'])) {
       
  1557       form_set_error('name', $error);
       
  1558     }
       
  1559     else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d AND LOWER(name) = LOWER('%s')", $uid, $edit['name'])) > 0) {
       
  1560       form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
       
  1561     }
       
  1562     else if (drupal_is_denied('user', $edit['name'])) {
       
  1563       form_set_error('name', t('The name %name has been denied access.', array('%name' => $edit['name'])));
       
  1564     }
       
  1565   }
       
  1566 
       
  1567   // Validate the e-mail address:
       
  1568   if ($error = user_validate_mail($edit['mail'])) {
       
  1569     form_set_error('mail', $error);
       
  1570   }
       
  1571   else if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE uid != %d AND LOWER(mail) = LOWER('%s')", $uid, $edit['mail'])) > 0) {
       
  1572     form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $edit['mail'], '@password' => url('user/password'))));
       
  1573   }
       
  1574   else if (drupal_is_denied('mail', $edit['mail'])) {
       
  1575     form_set_error('mail', t('The e-mail address %email has been denied access.', array('%email' => $edit['mail'])));
       
  1576   }
       
  1577 }
       
  1578 
       
  1579 function _user_edit_submit($uid, &$edit) {
       
  1580   $account = user_load($uid);
       
  1581   // Delete picture if requested, and if no replacement picture was given.
       
  1582   if (!empty($edit['picture_delete'])) {
       
  1583     if ($account->picture && file_exists($account->picture)) {
       
  1584       file_delete($account->picture);
       
  1585     }
       
  1586     $edit['picture'] = '';
       
  1587   }
       
  1588   if (isset($edit['roles'])) {
       
  1589     $edit['roles'] = array_filter($edit['roles']);
       
  1590   }
       
  1591 }
       
  1592 
       
  1593 /**
       
  1594  * Delete a user.
       
  1595  *
       
  1596  * @param $edit An array of submitted form values.
       
  1597  * @param $uid The user ID of the user to delete.
       
  1598  */
       
  1599 function user_delete($edit, $uid) {
       
  1600   $account = user_load(array('uid' => $uid));
       
  1601   sess_destroy_uid($uid);
       
  1602   _user_mail_notify('status_deleted', $account);
       
  1603   db_query('DELETE FROM {users} WHERE uid = %d', $uid);
       
  1604   db_query('DELETE FROM {users_roles} WHERE uid = %d', $uid);
       
  1605   db_query('DELETE FROM {authmap} WHERE uid = %d', $uid);
       
  1606   $variables = array('%name' => $account->name, '%email' => '<'. $account->mail .'>');
       
  1607   watchdog('user', 'Deleted user: %name %email.', $variables, WATCHDOG_NOTICE);
       
  1608   module_invoke_all('user', 'delete', $edit, $account);
       
  1609 }
       
  1610 
       
  1611 /**
       
  1612  * Builds a structured array representing the profile content.
       
  1613  *
       
  1614  * @param $account
       
  1615  *   A user object.
       
  1616  *
       
  1617  * @return
       
  1618  *   A structured array containing the individual elements of the profile.
       
  1619  */
       
  1620 function user_build_content(&$account) {
       
  1621   $edit = NULL;
       
  1622   user_module_invoke('view', $edit, $account);
       
  1623   // Allow modules to modify the fully-built profile.
       
  1624   drupal_alter('profile', $account);
       
  1625 
       
  1626   return $account->content;
       
  1627 }
       
  1628 
       
  1629 /**
       
  1630  * Implementation of hook_mail().
       
  1631  */
       
  1632 function user_mail($key, &$message, $params) {
       
  1633   $language = $message['language'];
       
  1634   $variables = user_mail_tokens($params['account'], $language);
       
  1635   $message['subject'] .= _user_mail_text($key .'_subject', $language, $variables);
       
  1636   $message['body'][] = _user_mail_text($key .'_body', $language, $variables);
       
  1637 }
       
  1638 
       
  1639 /**
       
  1640  * Returns a mail string for a variable name.
       
  1641  *
       
  1642  * Used by user_mail() and the settings forms to retrieve strings.
       
  1643  */
       
  1644 function _user_mail_text($key, $language = NULL, $variables = array()) {
       
  1645   $langcode = isset($language) ? $language->language : NULL;
       
  1646 
       
  1647   if ($admin_setting = variable_get('user_mail_'. $key, FALSE)) {
       
  1648     // An admin setting overrides the default string.
       
  1649     return strtr($admin_setting, $variables);
       
  1650   }
       
  1651   else {
       
  1652     // No override, return default string.
       
  1653     switch ($key) {
       
  1654       case 'register_no_approval_required_subject':
       
  1655         return t('Account details for !username at !site', $variables, $langcode);
       
  1656       case 'register_no_approval_required_body':
       
  1657         return t("!username,\n\nThank you for registering at !site. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n--  !site team", $variables, $langcode);
       
  1658       case 'register_admin_created_subject':
       
  1659         return t('An administrator created an account for you at !site', $variables, $langcode);
       
  1660       case 'register_admin_created_body':
       
  1661         return t("!username,\n\nA site administrator at !site has created an account for you. You may now log in to !login_uri using the following username and password:\n\nusername: !username\npassword: !password\n\nYou may also log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\n\n--  !site team", $variables, $langcode);
       
  1662       case 'register_pending_approval_subject':
       
  1663       case 'register_pending_approval_admin_subject':
       
  1664         return t('Account details for !username at !site (pending admin approval)', $variables, $langcode);
       
  1665       case 'register_pending_approval_body':
       
  1666         return t("!username,\n\nThank you for registering at !site. Your application for an account is currently pending approval. Once it has been approved, you will receive another e-mail containing information about how to log in, set your password, and other details.\n\n\n--  !site team", $variables, $langcode);
       
  1667       case 'register_pending_approval_admin_body':
       
  1668         return t("!username has applied for an account.\n\n!edit_uri", $variables, $langcode);
       
  1669       case 'password_reset_subject':
       
  1670         return t('Replacement login information for !username at !site', $variables, $langcode);
       
  1671       case 'password_reset_body':
       
  1672         return t("!username,\n\nA request to reset the password for your account has been made at !site.\n\nYou may now log in to !uri_brief by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once. It expires after one day and nothing will happen if it's not used.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.", $variables, $langcode);
       
  1673       case 'status_activated_subject':
       
  1674         return t('Account details for !username at !site (approved)', $variables, $langcode);
       
  1675       case 'status_activated_body':
       
  1676         return t("!username,\n\nYour account at !site has been activated.\n\nYou may now log in by clicking on this link or copying and pasting it in your browser:\n\n!login_url\n\nThis is a one-time login, so it can be used only once.\n\nAfter logging in, you will be redirected to !edit_uri so you can change your password.\n\nOnce you have set your own password, you will be able to log in to !login_uri in the future using:\n\nusername: !username\n", $variables, $langcode);
       
  1677       case 'status_blocked_subject':
       
  1678         return t('Account details for !username at !site (blocked)', $variables, $langcode);
       
  1679       case 'status_blocked_body':
       
  1680         return t("!username,\n\nYour account on !site has been blocked.", $variables, $langcode);
       
  1681       case 'status_deleted_subject':
       
  1682         return t('Account details for !username at !site (deleted)', $variables, $langcode);
       
  1683       case 'status_deleted_body':
       
  1684         return t("!username,\n\nYour account on !site has been deleted.", $variables, $langcode);
       
  1685     }
       
  1686   }
       
  1687 }
       
  1688 
       
  1689 /*** Administrative features ***********************************************/
       
  1690 
       
  1691 /**
       
  1692  * Retrieve an array of roles matching specified conditions.
       
  1693  *
       
  1694  * @param $membersonly
       
  1695  *   Set this to TRUE to exclude the 'anonymous' role.
       
  1696  * @param $permission
       
  1697  *   A string containing a permission. If set, only roles containing that
       
  1698  *   permission are returned.
       
  1699  *
       
  1700  * @return
       
  1701  *   An associative array with the role id as the key and the role name as
       
  1702  *   value.
       
  1703  */
       
  1704 function user_roles($membersonly = FALSE, $permission = NULL) {
       
  1705   // System roles take the first two positions.
       
  1706   $roles = array(
       
  1707     DRUPAL_ANONYMOUS_RID => NULL,
       
  1708     DRUPAL_AUTHENTICATED_RID => NULL,
       
  1709   );
       
  1710 
       
  1711   if (!empty($permission)) {
       
  1712     $result = db_query("SELECT r.* FROM {role} r INNER JOIN {permission} p ON r.rid = p.rid WHERE p.perm LIKE '%%%s%%' ORDER BY r.name", $permission);
       
  1713   }
       
  1714   else {
       
  1715     $result = db_query('SELECT * FROM {role} ORDER BY name');
       
  1716   }
       
  1717 
       
  1718   while ($role = db_fetch_object($result)) {
       
  1719     switch ($role->rid) {
       
  1720       // We only translate the built in role names
       
  1721       case DRUPAL_ANONYMOUS_RID:
       
  1722         if (!$membersonly) {
       
  1723           $roles[$role->rid] = t($role->name);
       
  1724         }
       
  1725         break;
       
  1726       case DRUPAL_AUTHENTICATED_RID:
       
  1727         $roles[$role->rid] = t($role->name);
       
  1728         break;
       
  1729       default:
       
  1730         $roles[$role->rid] = $role->name;
       
  1731     }
       
  1732   }
       
  1733 
       
  1734   // Filter to remove unmatched system roles.
       
  1735   return array_filter($roles);
       
  1736 }
       
  1737 
       
  1738 /**
       
  1739  * Implementation of hook_user_operations().
       
  1740  */
       
  1741 function user_user_operations($form_state = array()) {
       
  1742   $operations = array(
       
  1743     'unblock' => array(
       
  1744       'label' => t('Unblock the selected users'),
       
  1745       'callback' => 'user_user_operations_unblock',
       
  1746     ),
       
  1747     'block' => array(
       
  1748       'label' => t('Block the selected users'),
       
  1749       'callback' => 'user_user_operations_block',
       
  1750     ),
       
  1751     'delete' => array(
       
  1752       'label' => t('Delete the selected users'),
       
  1753     ),
       
  1754   );
       
  1755 
       
  1756   if (user_access('administer permissions')) {
       
  1757     $roles = user_roles(TRUE);
       
  1758     unset($roles[DRUPAL_AUTHENTICATED_RID]);  // Can't edit authenticated role.
       
  1759 
       
  1760     $add_roles = array();
       
  1761     foreach ($roles as $key => $value) {
       
  1762       $add_roles['add_role-'. $key] = $value;
       
  1763     }
       
  1764 
       
  1765     $remove_roles = array();
       
  1766     foreach ($roles as $key => $value) {
       
  1767       $remove_roles['remove_role-'. $key] = $value;
       
  1768     }
       
  1769 
       
  1770     if (count($roles)) {
       
  1771       $role_operations = array(
       
  1772         t('Add a role to the selected users') => array(
       
  1773           'label' => $add_roles,
       
  1774         ),
       
  1775         t('Remove a role from the selected users') => array(
       
  1776           'label' => $remove_roles,
       
  1777         ),
       
  1778       );
       
  1779 
       
  1780       $operations += $role_operations;
       
  1781     }
       
  1782   }
       
  1783 
       
  1784   // If the form has been posted, we need to insert the proper data for
       
  1785   // role editing if necessary.
       
  1786   if (!empty($form_state['submitted'])) {
       
  1787     $operation_rid = explode('-', $form_state['values']['operation']);
       
  1788     $operation = $operation_rid[0];
       
  1789     if ($operation == 'add_role' || $operation == 'remove_role') {
       
  1790       $rid = $operation_rid[1];
       
  1791       if (user_access('administer permissions')) {
       
  1792         $operations[$form_state['values']['operation']] = array(
       
  1793           'callback' => 'user_multiple_role_edit',
       
  1794           'callback arguments' => array($operation, $rid),
       
  1795         );
       
  1796       }
       
  1797       else {
       
  1798         watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
       
  1799         return;
       
  1800       }
       
  1801     }
       
  1802   }
       
  1803 
       
  1804   return $operations;
       
  1805 }
       
  1806 
       
  1807 /**
       
  1808  * Callback function for admin mass unblocking users.
       
  1809  */
       
  1810 function user_user_operations_unblock($accounts) {
       
  1811   foreach ($accounts as $uid) {
       
  1812     $account = user_load(array('uid' => (int)$uid));
       
  1813     // Skip unblocking user if they are already unblocked.
       
  1814     if ($account !== FALSE && $account->status == 0) {
       
  1815       user_save($account, array('status' => 1));
       
  1816     }
       
  1817   }
       
  1818 }
       
  1819 
       
  1820 /**
       
  1821  * Callback function for admin mass blocking users.
       
  1822  */
       
  1823 function user_user_operations_block($accounts) {
       
  1824   foreach ($accounts as $uid) {
       
  1825     $account = user_load(array('uid' => (int)$uid));
       
  1826     // Skip blocking user if they are already blocked.
       
  1827     if ($account !== FALSE && $account->status == 1) {
       
  1828       user_save($account, array('status' => 0));
       
  1829     }
       
  1830   }
       
  1831 }
       
  1832 
       
  1833 /**
       
  1834  * Callback function for admin mass adding/deleting a user role.
       
  1835  */
       
  1836 function user_multiple_role_edit($accounts, $operation, $rid) {
       
  1837   // The role name is not necessary as user_save() will reload the user
       
  1838   // object, but some modules' hook_user() may look at this first.
       
  1839   $role_name = db_result(db_query('SELECT name FROM {role} WHERE rid = %d', $rid));
       
  1840 
       
  1841   switch ($operation) {
       
  1842     case 'add_role':
       
  1843       foreach ($accounts as $uid) {
       
  1844         $account = user_load(array('uid' => (int)$uid));
       
  1845         // Skip adding the role to the user if they already have it.
       
  1846         if ($account !== FALSE && !isset($account->roles[$rid])) {
       
  1847           $roles = $account->roles + array($rid => $role_name);
       
  1848           user_save($account, array('roles' => $roles));
       
  1849         }
       
  1850       }
       
  1851       break;
       
  1852     case 'remove_role':
       
  1853       foreach ($accounts as $uid) {
       
  1854         $account = user_load(array('uid' => (int)$uid));
       
  1855         // Skip removing the role from the user if they already don't have it.
       
  1856         if ($account !== FALSE && isset($account->roles[$rid])) {
       
  1857           $roles = array_diff($account->roles, array($rid => $role_name));
       
  1858           user_save($account, array('roles' => $roles));
       
  1859         }
       
  1860       }
       
  1861       break;
       
  1862   }
       
  1863 }
       
  1864 
       
  1865 function user_multiple_delete_confirm(&$form_state) {
       
  1866   $edit = $form_state['post'];
       
  1867 
       
  1868   $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
       
  1869   // array_filter() returns only elements with TRUE values.
       
  1870   foreach (array_filter($edit['accounts']) as $uid => $value) {
       
  1871     $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));
       
  1872     $form['accounts'][$uid] = array('#type' => 'hidden', '#value' => $uid, '#prefix' => '<li>', '#suffix' => check_plain($user) ."</li>\n");
       
  1873   }
       
  1874   $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
       
  1875 
       
  1876   return confirm_form($form,
       
  1877                       t('Are you sure you want to delete these users?'),
       
  1878                       'admin/user/user', t('This action cannot be undone.'),
       
  1879                       t('Delete all'), t('Cancel'));
       
  1880 }
       
  1881 
       
  1882 function user_multiple_delete_confirm_submit($form, &$form_state) {
       
  1883   if ($form_state['values']['confirm']) {
       
  1884     foreach ($form_state['values']['accounts'] as $uid => $value) {
       
  1885       user_delete($form_state['values'], $uid);
       
  1886     }
       
  1887     drupal_set_message(t('The users have been deleted.'));
       
  1888   }
       
  1889   $form_state['redirect'] = 'admin/user/user';
       
  1890   return;
       
  1891 }
       
  1892 
       
  1893 /**
       
  1894  * Implementation of hook_help().
       
  1895  */
       
  1896 function user_help($path, $arg) {
       
  1897   global $user;
       
  1898 
       
  1899   switch ($path) {
       
  1900     case 'admin/help#user':
       
  1901       $output = '<p>'. t('The user module allows users to register, login, and log out. Users benefit from being able to sign on because it associates content they create with their account and allows various permissions to be set for their roles. The user module supports user roles which establish fine grained permissions allowing each role to do only what the administrator wants them to. Each user is assigned to one or more roles. By default there are two roles <em>anonymous</em> - a user who has not logged in, and <em>authenticated</em> a user who has signed up and who has been authorized.') .'</p>';
       
  1902       $output .= '<p>'. t("Users can use their own name or handle and can specify personal configuration settings through their individual <em>My account</em> page. Users must authenticate by supplying a local username and password or through their OpenID, an optional and secure method for logging into many websites with a single username and password. In some configurations, users may authenticate using a username and password from another Drupal site, or through some other site-specific mechanism.") .'</p>';
       
  1903       $output .= '<p>'. t('A visitor accessing your website is assigned a unique ID, or session ID, which is stored in a cookie. The cookie does not contain personal information, but acts as a key to retrieve information from your site. Users should have cookies enabled in their web browser when using your site.') .'</p>';
       
  1904       $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@user">User module</a>.', array('@user' => 'http://drupal.org/handbook/modules/user/')) .'</p>';
       
  1905       return $output;
       
  1906     case 'admin/user/user':
       
  1907       return '<p>'. t('Drupal allows users to register, login, log out, maintain user profiles, etc. Users of the site may not use their own names to post content until they have signed up for a user account.') .'</p>';
       
  1908     case 'admin/user/user/create':
       
  1909     case 'admin/user/user/account/create':
       
  1910       return '<p>'. t("This web page allows administrators to register new users. Users' e-mail addresses and usernames must be unique.") .'</p>';
       
  1911     case 'admin/user/rules':
       
  1912       return '<p>'. t('Set up username and e-mail address access rules for new <em>and</em> existing accounts (currently logged in accounts will not be logged out). If a username or e-mail address for an account matches any deny rule, but not an allow rule, then the account will not be allowed to be created or to log in. A host rule is effective for every page view, not just registrations.') .'</p>';
       
  1913     case 'admin/user/permissions':
       
  1914       return '<p>'. t('Permissions let you control what users can do on your site. Each user role (defined on the <a href="@role">user roles page</a>) has its own set of permissions. For example, you could give users classified as "Administrators" permission to "administer nodes" but deny this power to ordinary, "authenticated" users. You can use permissions to reveal new features to privileged users (those with subscriptions, for example). Permissions also allow trusted users to share the administrative burden of running a busy site.', array('@role' => url('admin/user/roles'))) .'</p>';
       
  1915     case 'admin/user/roles':
       
  1916       return t('<p>Roles allow you to fine tune the security and administration of Drupal. A role defines a group of users that have certain privileges as defined in <a href="@permissions">user permissions</a>. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the <em>role names</em> of the various roles. To delete a role choose "edit".</p><p>By default, Drupal comes with two user roles:</p>
       
  1917       <ul>
       
  1918       <li>Anonymous user: this role is used for users that don\'t have a user account or that are not authenticated.</li>
       
  1919       <li>Authenticated user: this role is automatically granted to all logged in users.</li>
       
  1920       </ul>', array('@permissions' => url('admin/user/permissions')));
       
  1921     case 'admin/user/search':
       
  1922       return '<p>'. t('Enter a simple pattern ("*" may be used as a wildcard match) to search for a username or e-mail address. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda@example.com".') .'</p>';
       
  1923   }
       
  1924 }
       
  1925 
       
  1926 /**
       
  1927  * Retrieve a list of all user setting/information categories and sort them by weight.
       
  1928  */
       
  1929 function _user_categories($account) {
       
  1930   $categories = array();
       
  1931 
       
  1932   foreach (module_list() as $module) {
       
  1933     if ($data = module_invoke($module, 'user', 'categories', NULL, $account, '')) {
       
  1934       $categories = array_merge($data, $categories);
       
  1935     }
       
  1936   }
       
  1937 
       
  1938   usort($categories, '_user_sort');
       
  1939 
       
  1940   return $categories;
       
  1941 }
       
  1942 
       
  1943 function _user_sort($a, $b) {
       
  1944   $a = (array)$a + array('weight' => 0, 'title' => '');
       
  1945   $b = (array)$b + array('weight' => 0, 'title' => '');
       
  1946   return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
       
  1947 }
       
  1948 
       
  1949 /**
       
  1950  * List user administration filters that can be applied.
       
  1951  */
       
  1952 function user_filters() {
       
  1953   // Regular filters
       
  1954   $filters = array();
       
  1955   $roles = user_roles(TRUE);
       
  1956   unset($roles[DRUPAL_AUTHENTICATED_RID]); // Don't list authorized role.
       
  1957   if (count($roles)) {
       
  1958     $filters['role'] = array(
       
  1959       'title' => t('role'),
       
  1960       'where' => "ur.rid = %d",
       
  1961       'options' => $roles,
       
  1962       'join' => '',
       
  1963     );
       
  1964   }
       
  1965 
       
  1966   $options = array();
       
  1967   foreach (module_list() as $module) {
       
  1968     if ($permissions = module_invoke($module, 'perm')) {
       
  1969       asort($permissions);
       
  1970       foreach ($permissions as $permission) {
       
  1971         $options[t('@module module', array('@module' => $module))][$permission] = t($permission);
       
  1972       }
       
  1973     }
       
  1974   }
       
  1975   ksort($options);
       
  1976   $filters['permission'] = array(
       
  1977     'title' => t('permission'),
       
  1978     'join' => 'LEFT JOIN {permission} p ON ur.rid = p.rid',
       
  1979     'where' => " ((p.perm IS NOT NULL AND p.perm LIKE '%%%s%%') OR u.uid = 1) ",
       
  1980     'options' => $options,
       
  1981   );
       
  1982 
       
  1983   $filters['status'] = array(
       
  1984     'title' => t('status'),
       
  1985     'where' => 'u.status = %d',
       
  1986     'join' => '',
       
  1987     'options' => array(1 => t('active'), 0 => t('blocked')),
       
  1988   );
       
  1989   return $filters;
       
  1990 }
       
  1991 
       
  1992 /**
       
  1993  * Build query for user administration filters based on session.
       
  1994  */
       
  1995 function user_build_filter_query() {
       
  1996   $filters = user_filters();
       
  1997 
       
  1998   // Build query
       
  1999   $where = $args = $join = array();
       
  2000   foreach ($_SESSION['user_overview_filter'] as $filter) {
       
  2001     list($key, $value) = $filter;
       
  2002     // This checks to see if this permission filter is an enabled permission for
       
  2003     // the authenticated role. If so, then all users would be listed, and we can
       
  2004     // skip adding it to the filter query.
       
  2005     if ($key == 'permission') {
       
  2006       $account = new stdClass();
       
  2007       $account->uid = 'user_filter';
       
  2008       $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
       
  2009       if (user_access($value, $account)) {
       
  2010         continue;
       
  2011       }
       
  2012     }
       
  2013     $where[] = $filters[$key]['where'];
       
  2014     $args[] = $value;
       
  2015     $join[] = $filters[$key]['join'];
       
  2016   }
       
  2017   $where = !empty($where) ? 'AND '. implode(' AND ', $where) : '';
       
  2018   $join = !empty($join) ? ' '. implode(' ', array_unique($join)) : '';
       
  2019 
       
  2020   return array('where' => $where,
       
  2021            'join' => $join,
       
  2022            'args' => $args,
       
  2023          );
       
  2024 }
       
  2025 
       
  2026 /**
       
  2027  * Implementation of hook_forms().
       
  2028  */
       
  2029 function user_forms() {
       
  2030   $forms['user_admin_access_add_form']['callback'] = 'user_admin_access_form';
       
  2031   $forms['user_admin_access_edit_form']['callback'] = 'user_admin_access_form';
       
  2032   $forms['user_admin_new_role']['callback'] = 'user_admin_role';
       
  2033   return $forms;
       
  2034 }
       
  2035 
       
  2036 /**
       
  2037  * Implementation of hook_comment().
       
  2038  */
       
  2039 function user_comment(&$comment, $op) {
       
  2040   // Validate signature.
       
  2041   if ($op == 'view') {
       
  2042     if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
       
  2043       $comment->signature = check_markup($comment->signature, $comment->signature_format, FALSE);
       
  2044     }
       
  2045     else {
       
  2046       $comment->signature = '';
       
  2047     }
       
  2048   }
       
  2049 }
       
  2050 
       
  2051 /**
       
  2052  * Theme output of user signature.
       
  2053  *
       
  2054  * @ingroup themeable
       
  2055  */
       
  2056 function theme_user_signature($signature) {
       
  2057   $output = '';
       
  2058   if ($signature) {
       
  2059     $output .= '<div class="clear">';
       
  2060     $output .= '<div>—</div>';
       
  2061     $output .= $signature;
       
  2062     $output .= '</div>';
       
  2063   }
       
  2064 
       
  2065   return $output;
       
  2066 }
       
  2067 
       
  2068 /**
       
  2069  * Return an array of token to value mappings for user e-mail messages.
       
  2070  *
       
  2071  * @param $account
       
  2072  *  The user object of the account being notified.  Must contain at
       
  2073  *  least the fields 'uid', 'name', and 'mail'.
       
  2074  * @param $language
       
  2075  *  Language object to generate the tokens with.
       
  2076  * @return
       
  2077  *  Array of mappings from token names to values (for use with strtr()).
       
  2078  */
       
  2079 function user_mail_tokens($account, $language) {
       
  2080   global $base_url;
       
  2081   $tokens = array(
       
  2082     '!username' => $account->name,
       
  2083     '!site' => variable_get('site_name', 'Drupal'),
       
  2084     '!login_url' => user_pass_reset_url($account),
       
  2085     '!uri' => $base_url,
       
  2086     '!uri_brief' => preg_replace('!^https?://!', '', $base_url),
       
  2087     '!mailto' => $account->mail,
       
  2088     '!date' => format_date(time(), 'medium', '', NULL, $language->language),
       
  2089     '!login_uri' => url('user', array('absolute' => TRUE, 'language' => $language)),
       
  2090     '!edit_uri' => url('user/'. $account->uid .'/edit', array('absolute' => TRUE, 'language' => $language)),
       
  2091   );
       
  2092   if (!empty($account->password)) {
       
  2093     $tokens['!password'] = $account->password;
       
  2094   }
       
  2095   return $tokens;
       
  2096 }
       
  2097 
       
  2098 /**
       
  2099  * Get the language object preferred by the user. This user preference can
       
  2100  * be set on the user account editing page, and is only available if there
       
  2101  * are more than one languages enabled on the site. If the user did not
       
  2102  * choose a preferred language, or is the anonymous user, the $default
       
  2103  * value, or if it is not set, the site default language will be returned.
       
  2104  *
       
  2105  * @param $account
       
  2106  *   User account to look up language for.
       
  2107  * @param $default
       
  2108  *   Optional default language object to return if the account
       
  2109  *   has no valid language.
       
  2110  */
       
  2111 function user_preferred_language($account, $default = NULL) {
       
  2112   $language_list = language_list();
       
  2113   if ($account->language && isset($language_list[$account->language])) {
       
  2114     return $language_list[$account->language];
       
  2115   }
       
  2116   else {
       
  2117     return $default ? $default : language_default();
       
  2118   }
       
  2119 }
       
  2120 
       
  2121 /**
       
  2122  * Conditionally create and send a notification email when a certain
       
  2123  * operation happens on the given user account.
       
  2124  *
       
  2125  * @see user_mail_tokens()
       
  2126  * @see drupal_mail()
       
  2127  *
       
  2128  * @param $op
       
  2129  *  The operation being performed on the account.  Possible values:
       
  2130  *  'register_admin_created': Welcome message for user created by the admin
       
  2131  *  'register_no_approval_required': Welcome message when user self-registers
       
  2132  *  'register_pending_approval': Welcome message, user pending admin approval
       
  2133  *  'password_reset': Password recovery request
       
  2134  *  'status_activated': Account activated
       
  2135  *  'status_blocked': Account blocked
       
  2136  *  'status_deleted': Account deleted
       
  2137  *
       
  2138  * @param $account
       
  2139  *  The user object of the account being notified.  Must contain at
       
  2140  *  least the fields 'uid', 'name', and 'mail'.
       
  2141  * @param $language
       
  2142  *  Optional language to use for the notification, overriding account language.
       
  2143  * @return
       
  2144  *  The return value from drupal_mail_send(), if ends up being called.
       
  2145  */
       
  2146 function _user_mail_notify($op, $account, $language = NULL) {
       
  2147   // By default, we always notify except for deleted and blocked.
       
  2148   $default_notify = ($op != 'status_deleted' && $op != 'status_blocked');
       
  2149   $notify = variable_get('user_mail_'. $op .'_notify', $default_notify);
       
  2150   if ($notify) {
       
  2151     $params['account'] = $account;
       
  2152     $language = $language ? $language : user_preferred_language($account);
       
  2153     $mail = drupal_mail('user', $op, $account->mail, $language, $params);
       
  2154     if ($op == 'register_pending_approval') {
       
  2155       // If a user registered requiring admin approval, notify the admin, too.
       
  2156       // We use the site default language for this.
       
  2157       drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
       
  2158     }
       
  2159   }
       
  2160   return empty($mail) ? NULL : $mail['result'];
       
  2161 }
       
  2162 
       
  2163 /**
       
  2164  * Add javascript and string translations for dynamic password validation
       
  2165  * (strength and confirmation checking).
       
  2166  *
       
  2167  * This is an internal function that makes it easier to manage the translation
       
  2168  * strings that need to be passed to the javascript code.
       
  2169  */
       
  2170 function _user_password_dynamic_validation() {
       
  2171   static $complete = FALSE;
       
  2172   global $user;
       
  2173   // Only need to do once per page.
       
  2174   if (!$complete) {
       
  2175     drupal_add_js(drupal_get_path('module', 'user') .'/user.js', 'module');
       
  2176 
       
  2177     drupal_add_js(array(
       
  2178       'password' => array(
       
  2179         'strengthTitle' => t('Password strength:'),
       
  2180         'lowStrength' => t('Low'),
       
  2181         'mediumStrength' => t('Medium'),
       
  2182         'highStrength' => t('High'),
       
  2183         'tooShort' => t('It is recommended to choose a password that contains at least six characters. It should include numbers, punctuation, and both upper and lowercase letters.'),
       
  2184         'needsMoreVariation' => t('The password does not include enough variation to be secure. Try:'),
       
  2185         'addLetters' => t('Adding both upper and lowercase letters.'),
       
  2186         'addNumbers' => t('Adding numbers.'),
       
  2187         'addPunctuation' => t('Adding punctuation.'),
       
  2188         'sameAsUsername' => t('It is recommended to choose a password different from the username.'),
       
  2189         'confirmSuccess' => t('Yes'),
       
  2190         'confirmFailure' => t('No'),
       
  2191         'confirmTitle' => t('Passwords match:'),
       
  2192         'username' => (isset($user->name) ? $user->name : ''))),
       
  2193       'setting');
       
  2194     $complete = TRUE;
       
  2195   }
       
  2196 }
       
  2197 
       
  2198 /**
       
  2199  * Implementation of hook_hook_info().
       
  2200  */
       
  2201 function user_hook_info() {
       
  2202   return array(
       
  2203     'user' => array(
       
  2204       'user' => array(
       
  2205         'insert' => array(
       
  2206           'runs when' => t('After a user account has been created'),
       
  2207         ),
       
  2208         'update' => array(
       
  2209           'runs when' => t("After a user's profile has been updated"),
       
  2210         ),
       
  2211         'delete' => array(
       
  2212           'runs when' => t('After a user has been deleted')
       
  2213         ),
       
  2214         'login' => array(
       
  2215           'runs when' => t('After a user has logged in')
       
  2216         ),
       
  2217         'logout' => array(
       
  2218           'runs when' => t('After a user has logged out')
       
  2219         ),
       
  2220         'view' => array(
       
  2221           'runs when' => t("When a user's profile is being viewed")
       
  2222         ),
       
  2223       ),
       
  2224     ),
       
  2225   );
       
  2226 }
       
  2227 
       
  2228 /**
       
  2229  * Implementation of hook_action_info().
       
  2230  */
       
  2231 function user_action_info() {
       
  2232   return array(
       
  2233     'user_block_user_action' => array(
       
  2234       'description' => t('Block current user'),
       
  2235       'type' => 'user',
       
  2236       'configurable' => FALSE,
       
  2237       'hooks' => array(),
       
  2238     ),
       
  2239     'user_block_ip_action' => array(
       
  2240       'description' => t('Ban IP address of current user'),
       
  2241       'type' => 'user',
       
  2242       'configurable' => FALSE,
       
  2243       'hooks' => array(),
       
  2244     ),
       
  2245   );
       
  2246 }
       
  2247 
       
  2248 /**
       
  2249  * Implementation of a Drupal action.
       
  2250  * Blocks the current user.
       
  2251  */
       
  2252 function user_block_user_action(&$object, $context = array()) {
       
  2253   if (isset($object->uid)) {
       
  2254     $uid = $object->uid;
       
  2255   }
       
  2256   elseif (isset($context['uid'])) {
       
  2257     $uid = $context['uid'];
       
  2258   }
       
  2259   else {
       
  2260     global $user;
       
  2261     $uid = $user->uid;
       
  2262   }
       
  2263   db_query("UPDATE {users} SET status = 0 WHERE uid = %d", $uid);
       
  2264   sess_destroy_uid($uid);
       
  2265   watchdog('action', 'Blocked user %name.', array('%name' => check_plain($user->name)));
       
  2266 }
       
  2267 
       
  2268 /**
       
  2269  * Implementation of a Drupal action.
       
  2270  * Adds an access rule that blocks the user's IP address.
       
  2271  */
       
  2272 function user_block_ip_action() {
       
  2273   $ip = ip_address();
       
  2274   db_query("INSERT INTO {access} (mask, type, status) VALUES ('%s', '%s', %d)", $ip, 'host', 0);
       
  2275   watchdog('action', 'Banned IP address %ip', array('%ip' => $ip));
       
  2276 }
       
  2277 
       
  2278 /**
       
  2279  * Submit handler for the user registration form.
       
  2280  *
       
  2281  * This function is shared by the installation form and the normal registration form,
       
  2282  * which is why it can't be in the user.pages.inc file.
       
  2283  */
       
  2284 function user_register_submit($form, &$form_state) {
       
  2285   global $base_url;
       
  2286   $admin = user_access('administer users');
       
  2287 
       
  2288   $mail = $form_state['values']['mail'];
       
  2289   $name = $form_state['values']['name'];
       
  2290   if (!variable_get('user_email_verification', TRUE) || $admin) {
       
  2291     $pass = $form_state['values']['pass'];
       
  2292   }
       
  2293   else {
       
  2294     $pass = user_password();
       
  2295   };
       
  2296   $notify = isset($form_state['values']['notify']) ? $form_state['values']['notify'] : NULL;
       
  2297   $from = variable_get('site_mail', ini_get('sendmail_from'));
       
  2298   if (isset($form_state['values']['roles'])) {
       
  2299     // Remove unset roles.
       
  2300     $roles = array_filter($form_state['values']['roles']);
       
  2301   }
       
  2302   else {
       
  2303     $roles = array();
       
  2304   }
       
  2305 
       
  2306   if (!$admin && array_intersect(array_keys($form_state['values']), array('uid', 'roles', 'init', 'session', 'status'))) {
       
  2307     watchdog('security', 'Detected malicious attempt to alter protected user fields.', array(), WATCHDOG_WARNING);
       
  2308     $form_state['redirect'] = 'user/register';
       
  2309     return;
       
  2310   }
       
  2311   // The unset below is needed to prevent these form values from being saved as
       
  2312   // user data.
       
  2313   unset($form_state['values']['form_token'], $form_state['values']['submit'], $form_state['values']['op'], $form_state['values']['notify'], $form_state['values']['form_id'], $form_state['values']['affiliates'], $form_state['values']['destination']);
       
  2314 
       
  2315   $merge_data = array('pass' => $pass, 'init' => $mail, 'roles' => $roles);
       
  2316   if (!$admin) {
       
  2317     // Set the user's status because it was not displayed in the form.
       
  2318     $merge_data['status'] = variable_get('user_register', 1) == 1;
       
  2319   }
       
  2320   $account = user_save('', array_merge($form_state['values'], $merge_data));
       
  2321   // Terminate if an error occured during user_save().
       
  2322   if (!$account) {
       
  2323     drupal_set_message(t("Error saving user account."), 'error');
       
  2324     $form_state['redirect'] = '';
       
  2325     return;
       
  2326   }
       
  2327   $form_state['user'] = $account;
       
  2328 
       
  2329   watchdog('user', 'New user: %name (%email).', array('%name' => $name, '%email' => $mail), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit'));
       
  2330 
       
  2331   // The first user may login immediately, and receives a customized welcome e-mail.
       
  2332   if ($account->uid == 1) {
       
  2333     drupal_set_message(t('Welcome to Drupal. You are now logged in as user #1, which gives you full control over your website.'));
       
  2334     if (variable_get('user_email_verification', TRUE)) {
       
  2335       drupal_set_message(t('</p><p> Your password is <strong>%pass</strong>. You may change your password below.</p>', array('%pass' => $pass)));
       
  2336     }
       
  2337 
       
  2338     user_authenticate(array_merge($form_state['values'], $merge_data));
       
  2339 
       
  2340     $form_state['redirect'] = 'user/1/edit';
       
  2341     return;
       
  2342   }
       
  2343   else {
       
  2344     // Add plain text password into user account to generate mail tokens.
       
  2345     $account->password = $pass;
       
  2346     if ($admin && !$notify) {
       
  2347       drupal_set_message(t('Created a new user account for <a href="@url">%name</a>. No e-mail has been sent.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
       
  2348     }
       
  2349     else if (!variable_get('user_email_verification', TRUE) && $account->status && !$admin) {
       
  2350       // No e-mail verification is required, create new user account, and login
       
  2351       // user immediately.
       
  2352       _user_mail_notify('register_no_approval_required', $account);
       
  2353       if (user_authenticate(array_merge($form_state['values'], $merge_data))) {
       
  2354         drupal_set_message(t('Registration successful. You are now logged in.'));
       
  2355       }
       
  2356       $form_state['redirect'] = '';
       
  2357       return;
       
  2358     }
       
  2359     else if ($account->status || $notify) {
       
  2360       // Create new user account, no administrator approval required.
       
  2361       $op = $notify ? 'register_admin_created' : 'register_no_approval_required';
       
  2362       _user_mail_notify($op, $account);
       
  2363       if ($notify) {
       
  2364         drupal_set_message(t('Password and further instructions have been e-mailed to the new user <a href="@url">%name</a>.', array('@url' => url("user/$account->uid"), '%name' => $account->name)));
       
  2365       }
       
  2366       else {
       
  2367         drupal_set_message(t('Your password and further instructions have been sent to your e-mail address.'));
       
  2368         $form_state['redirect'] = '';
       
  2369         return;
       
  2370       }
       
  2371     }
       
  2372     else {
       
  2373       // Create new user account, administrator approval required.
       
  2374       _user_mail_notify('register_pending_approval', $account);
       
  2375       drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your e-mail address.'));
       
  2376       $form_state['redirect'] = '';
       
  2377       return;
       
  2378 
       
  2379     }
       
  2380   }
       
  2381 }
       
  2382 
       
  2383 /**
       
  2384  * Form builder; The user registration form.
       
  2385  *
       
  2386  * @ingroup forms
       
  2387  * @see user_register_validate()
       
  2388  * @see user_register_submit()
       
  2389  */
       
  2390 function user_register() {
       
  2391   global $user;
       
  2392 
       
  2393   $admin = user_access('administer users');
       
  2394 
       
  2395   // If we aren't admin but already logged on, go to the user page instead.
       
  2396   if (!$admin && $user->uid) {
       
  2397     drupal_goto('user/'. $user->uid);
       
  2398   }
       
  2399 
       
  2400   $form = array();
       
  2401 
       
  2402   // Display the registration form.
       
  2403   if (!$admin) {
       
  2404     $form['user_registration_help'] = array('#value' => filter_xss_admin(variable_get('user_registration_help', '')));
       
  2405   }
       
  2406 
       
  2407   // Merge in the default user edit fields.
       
  2408   $form = array_merge($form, user_edit_form($form_state, NULL, NULL, TRUE));
       
  2409   if ($admin) {
       
  2410     $form['account']['notify'] = array(
       
  2411      '#type' => 'checkbox',
       
  2412      '#title' => t('Notify user of new account')
       
  2413     );
       
  2414     // Redirect back to page which initiated the create request;
       
  2415     // usually admin/user/user/create.
       
  2416     $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
       
  2417   }
       
  2418 
       
  2419   // Create a dummy variable for pass-by-reference parameters.
       
  2420   $null = NULL;
       
  2421   $extra = _user_forms($null, NULL, NULL, 'register');
       
  2422 
       
  2423   // Remove form_group around default fields if there are no other groups.
       
  2424   if (!$extra) {
       
  2425     foreach (array('name', 'mail', 'pass', 'status', 'roles', 'notify') as $key) {
       
  2426       if (isset($form['account'][$key])) {
       
  2427         $form[$key] = $form['account'][$key];
       
  2428       }
       
  2429     }
       
  2430     unset($form['account']);
       
  2431   }
       
  2432   else {
       
  2433     $form = array_merge($form, $extra);
       
  2434   }
       
  2435 
       
  2436   if (variable_get('configurable_timezones', 1)) {
       
  2437     // Override field ID, so we only change timezone on user registration,
       
  2438     // and never touch it on user edit pages.
       
  2439     $form['timezone'] = array(
       
  2440       '#type' => 'hidden',
       
  2441       '#default_value' => variable_get('date_default_timezone', NULL),
       
  2442       '#id' => 'edit-user-register-timezone',
       
  2443     );
       
  2444 
       
  2445     // Add the JavaScript callback to automatically set the timezone.
       
  2446     drupal_add_js('
       
  2447 // Global Killswitch
       
  2448 if (Drupal.jsEnabled) {
       
  2449   $(document).ready(function() {
       
  2450     Drupal.setDefaultTimezone();
       
  2451   });
       
  2452 }', 'inline');
       
  2453   }
       
  2454 
       
  2455   $form['submit'] = array('#type' => 'submit', '#value' => t('Create new account'), '#weight' => 30);
       
  2456   $form['#validate'][] = 'user_register_validate';
       
  2457 
       
  2458   return $form;
       
  2459 }
       
  2460 
       
  2461 function user_register_validate($form, &$form_state) {
       
  2462   user_module_invoke('validate', $form_state['values'], $form_state['values'], 'account');
       
  2463 }
       
  2464 
       
  2465 /**
       
  2466  * Retrieve a list of all form elements for the specified category.
       
  2467  */
       
  2468 function _user_forms(&$edit, $account, $category, $hook = 'form') {
       
  2469   $groups = array();
       
  2470   foreach (module_list() as $module) {
       
  2471     if ($data = module_invoke($module, 'user', $hook, $edit, $account, $category)) {
       
  2472       $groups = array_merge_recursive($data, $groups);
       
  2473     }
       
  2474   }
       
  2475   uasort($groups, '_user_sort');
       
  2476 
       
  2477   return empty($groups) ? FALSE : $groups;
       
  2478 }