$value) { if ($key == 'uid' || $key == 'status') { $query[] = "$key = %d"; $params[] = $value; } else if ($key == 'pass') { $query[] = "pass = '%s'"; $params[] = md5($value); } else { $query[]= "LOWER($key) = LOWER('%s')"; $params[] = $value; } } $result = db_query('SELECT * FROM {users} u WHERE ' . implode(' AND ', $query), $params); if (db_num_rows($result)) { $user = db_fetch_object($result); $user = drupal_unpack($user); $user->roles = array(); if ($user->uid) { $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; } else { $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user'; } $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); while ($role = db_fetch_object($result)) { $user->roles[$role->rid] = $role->name; } user_module_invoke('load', $array, $user); } else { $user = FALSE; } return $user; } /** * Save changes to a user account or add a new user. * * @param $account * The $user object for the user to modify or add. If $user->uid is * omitted, a new user will be added. * * @param $array * An array of fields and values to save. For example array('name' => 'My name'); * Setting a field to null deletes it from the data column. * * @param $category * (optional) The category for storing profile information in. */ function user_save($account, $array = array(), $category = 'account') { // Dynamically compose a SQL query: $user_fields = user_fields(); if ($account->uid) { user_module_invoke('update', $array, $account, $category); $data = unserialize(db_result(db_query('SELECT data FROM {users} WHERE uid = %d', $account->uid))); foreach ($array as $key => $value) { if ($key == 'pass' && !empty($value)) { $query .= "$key = '%s', "; $v[] = md5($value); } else if ((substr($key, 0, 4) !== 'auth') && ($key != 'pass')) { if (in_array($key, $user_fields)) { // Save standard fields $query .= "$key = '%s', "; $v[] = $value; } else if ($key != 'roles') { // Roles is a special case: it used below. if ($value === null) { unset($data[$key]); } else { $data[$key] = $value; } } } } $query .= "data = '%s' "; $v[] = serialize($data); db_query("UPDATE {users} SET $query WHERE uid = %d", array_merge($v, array($account->uid))); // Reload user roles if provided if (is_array($array['roles'])) { db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid); foreach (array_keys($array['roles']) as $rid) { if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, $rid); } } } // Delete a blocked user's sessions to kick them if they are online. if (isset($array['status']) && $array['status'] == 0) { db_query('DELETE FROM {sessions} WHERE uid = %d', $account->uid); } // Refresh user object $user = user_load(array('uid' => $account->uid)); } else { $array['created'] = time(); $array['uid'] = db_next_id('{users}_uid'); // Note, we wait with saving the data column to prevent module-handled // fields from being saved there. We cannot invoke hook_user('insert') here // because we don't have a fully initialized user object yet. foreach ($array as $key => $value) { switch($key) { case 'pass': $fields[] = $key; $values[] = md5($value); $s[] = "'%s'"; break; case 'uid': case 'mode': case 'sort': case 'threshold': case 'created': case 'access': case 'login': case 'status': $fields[] = $key; $values[] = $value; $s[] = "%d"; break; default: if (substr($key, 0, 4) !== 'auth' && in_array($key, $user_fields)) { $fields[] = $key; $values[] = $value; $s[] = "'%s'"; } break; } } db_query('INSERT INTO {users} ('. implode(', ', $fields) .') VALUES ('. implode(', ', $s) .')', $values); // Reload user roles (delete just to be safe). db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']); foreach ((array)$array['roles'] as $rid) { db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid); } // Build the initial user object. $user = user_load(array('uid' => $array['uid'])); user_module_invoke('insert', $array, $user, $category); // Build and save the serialized data field now $data = array(); foreach ($array as $key => $value) { if ((substr($key, 0, 4) !== 'auth') && ($key != 'roles') && (!in_array($key, $user_fields)) && ($value !== null)) { $data[$key] = $value; } } db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid); // Build the finished user object. $user = user_load(array('uid' => $array['uid'])); } // Save distributed authentication mappings $authmaps = array(); foreach ($array as $key => $value) { if (substr($key, 0, 4) == 'auth') { $authmaps[$key] = $value; } } if (sizeof($authmaps) > 0) { user_set_authmaps($user, $authmaps); } return $user; } /** * Verify the syntax of the given name. */ function user_validate_name($name) { if (!strlen($name)) return t('You must enter a username.'); if (substr($name, 0, 1) == ' ') return t('The username cannot begin with a space.'); if (substr($name, -1) == ' ') return t('The username cannot end with a space.'); if (ereg(' ', $name)) return t('The username cannot contain multiple spaces in a row.'); if (ereg("[^\x80-\xF7 [:alnum:]@_.-]", $name)) return t('The username contains an illegal character.'); if (preg_match('/[\x{80}-\x{A0}'. // Non-printable ISO-8859-1 + NBSP '\x{AD}'. // Soft-hyphen '\x{2000}-\x{200F}'. // Various space characters '\x{2028}-\x{202F}'. // Bidirectional text overrides '\x{205F}-\x{206F}'. // Various text hinting characters '\x{FEFF}'. // Byte order mark '\x{FF01}-\x{FF60}'. // Full-width latin '\x{FFF9}-\x{FFFD}]/u', // Replacement characters $name)) { return t('The username contains an illegal character.'); } if (ereg('@', $name) && !eregi('@([0-9a-z](-?[0-9a-z])*.)+[a-z]{2}([zmuvtg]|fo|me)?$', $name)) return t('The username is not a valid authentication ID.'); if (strlen($name) > 56) return t('The username %name is too long: it must be less than 56 characters.', array('%name' => theme('placeholder', $name))); } function user_validate_mail($mail) { if (!$mail) return t('You must enter an e-mail address.'); if (!valid_email_address($mail)) { return t('The e-mail address %mail is not valid.', array('%mail' => theme('placeholder', $mail))); } } function user_validate_picture($file, &$edit, $user) { global $form_values; // Initialize the picture: $form_values['picture'] = $user->picture; // Check that uploaded file is an image, with a maximum file size // and maximum height/width. $info = image_get_info($file->filepath); list($maxwidth, $maxheight) = explode('x', variable_get('user_picture_dimensions', '85x85')); if (!$info || !$info['extension']) { form_set_error('picture_upload', t('The uploaded file was not an image.')); } else if (image_get_toolkit()) { image_scale($file->filepath, $file->filepath, $maxwidth, $maxheight); } else if (filesize($file->filepath) > (variable_get('user_picture_file_size', '30') * 1000)) { form_set_error('picture_upload', t('The uploaded image is too large; the maximum file size is %size kB.', array('%size' => variable_get('user_picture_file_size', '30')))); } else if ($info['width'] > $maxwidth || $info['height'] > $maxheight) { form_set_error('picture_upload', t('The uploaded image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => variable_get('user_picture_dimensions', '85x85')))); } if (!form_get_errors()) { if ($file = file_save_upload('picture_upload', variable_get('user_picture_path', 'pictures') .'/picture-'. $user->uid . '.' . $info['extension'], 1)) { $form_values['picture'] = $file->filepath; } else { form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist.", array('%directory' => ''. variable_get('user_picture_path', 'pictures') .''))); } } } /** * Generate a random alphanumeric password. */ function user_password($length = 10) { // This variable contains the list of allowable characters for the // password. Note that the number 0 and the letter 'O' have been // removed to avoid confusion between the two. The same is true // of 'I', 1, and l. $allowable_characters = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // Zero-based count of characters in the allowable list: $len = strlen($allowable_characters) - 1; // Declare the password as a blank string. $pass = ''; // Loop the number of times specified by $length. for ($i = 0; $i < $length; $i++) { // Each iteration, pick a random character from the // allowable string and append it to the password: $pass .= $allowable_characters[mt_rand(0, $len)]; } return $pass; } /** * Determine whether the user has a given privilege. * * @param $string * The permission, such as "administer nodes", being checked for. * @param $account * (optional) The account to check, if not given use currently logged in user. * * @return * boolean TRUE if the current user has the requested permission. * * All permission checks in Drupal should go through this function. This * way, we guarantee consistent behavior, and ensure that the superuser * can perform all actions. */ function user_access($string, $account = NULL) { global $user; static $perm = array(); if (is_null($account)) { $account = $user; } // User #1 has all privileges: if ($account->uid == 1) { return TRUE; } // To reduce the number of SQL queries, we cache the user's permissions // in a static variable. // // We are going to always reset $perm[$account->uid] // // if (!isset($perm[$account->uid])) { // // Modified this to call user_all_roles(); // // $result = db_query("SELECT DISTINCT(p.perm) FROM {role} r INNER JOIN {permission} p ON p.rid = r.rid WHERE r.rid IN (%s)", implode(',', array_keys($account->roles))); $result = db_query("SELECT DISTINCT(p.perm) FROM {role} r INNER JOIN {permission} p ON p.rid = r.rid WHERE r.rid IN (%s)", implode(',', user_all_roles($account))); // $perm[$account->uid] = ''; while ($row = db_fetch_object($result)) { $perm[$account->uid] .= "$row->perm, "; } // end while // // Another test to see what is written to $perm[$acount->uid] // // $testDate = format_date(time(), 'custom', 'Y-m-d h:i:s a'); // $testUser = $account->uid; // $testUserName = $account->name; // $testAArg0 = arg(0); // $testAArg1 = arg(1); // $testAArg2 = arg(2); // if (user_table_exists('test')) { // $testQuery = "insert into test values('user_access string : " . $string . "|" . $testDate . "|" . $testUser . "|" . $testUserName . "| arg0 : " . $testAArg0 . "| arg1 : " . $testAArg1 . "| arg2 : " . $testAArg2 . "| perm value : " . $perm[$account->uid] . "')"; // db_query($testQuery); // } // // end test // // } // end isset if if (isset($perm[$account->uid])) { return strpos($perm[$account->uid], "$string, ") !== FALSE; } return FALSE; } // // This function takes the global $user (or $account) value and returns a list // of group and non-group roles for this user // function user_all_roles($user) { // This will be the process to get BOTH the group and non-group roles for a user $uid = $user->uid; $gid = 0; $nodeID = 0; $uri_request_id = $_SERVER['REQUEST_URI']; $arg = explode("/", $uri_request_id); $ogroles = array(); $x1 = 0; // // This will by default add the anonymous user role (no need since we merge user->roles) // // $ogroles[0] = 1; // $x1 = 1; // // We get the groupID // $group_node = og_get_group_context(); $gid02 = $group_node->nid; $gid = $gid02; if ($gid02 === null) $gid = 0; // // If the above doesn't get the groupID, then we start trying stuff // if ($gid == 0) { // http://doadance.scbbs.com/drupal03/node/79 if (arg(0) == 'node' && is_numeric(arg(1)) && is_null(arg(2))) { $nodeID = (int)arg(1); $gid = getgid($nodeID, $uid); } // http://doadance.scbbs.com/drupal03/node/79/edit // http://doadance.scbbs.com/drupal03/node/79/outline // http://doadance.scbbs.com/drupal03/node/79/track if (arg(0) == 'node' && is_numeric(arg(1)) && (arg(2) == 'edit' || arg(2) == 'outline' || arg(2) == 'track' ) ) { $nodeID = (int)arg(1); $gid = getgid($nodeID, $uid); } // 0 1 2 // http://www.mysite.com/comment/edit/14 // if (arg(0) == 'comment' && is_numeric(arg(2)) && arg(1) == 'edit' ) { $comment = _comment_load(arg(2)); $nodeID = $comment->nid; $gid = getgid($nodeID, $uid); } // 0 1 2 // http://www.mysite.com/comment/reply/128#comment_form // if (arg(0) == 'comment' && arg(1) == 'reply' ) { $subsections = explode("#", arg(2)); $nodeID = (int)$subsections[0]; $gid = getgid($nodeID, $uid); } // og_term access // 0 1 2 3 // http://www.mysite.com/node/add/forum/121 // if (arg(0) == 'node' && is_numeric(arg(3)) && arg(1) == 'add' ) { $nodeID = (int)arg(3); $gid = getgid($nodeID, $uid); } // Here we get the gid directly // // http://doadance.scbbs.com/drupal03/og/users/72 // http://doadance.scbbs.com/drupal03/og/manage/72 if (arg(0) == 'og' && is_numeric(arg(2)) && is_null(arg(3))) { $gid = (int)arg(2); } // og_calendar // // http://doadance.scbbs.com/drupal03/og_calendar/72 if (arg(0) == 'og_calendar' && is_numeric(arg(1)) && is_null(arg(2))) { $gid = (int)arg(1); } // og_forum // 0 1 2 3 // http://www.mysite.com/og_forum/39/72?edit[og_groups][]=72 // http://www.mysite.com/og_forum/37/71?sort=asc&order=Replies&edit[og_groups][0]=71 if ($arg[1] == 'og_forum' && strpos($arg[3], 'og_groups') !== false && (!is_null($arg[3])) ) { $subsections = explode("=", $arg[3]); foreach ($subsections as $subsection) { if (is_numeric($subsection)) { $gid = (int)$subsection; } } } // og create nodes // 0 1 2 3 // http://sbn.scbbs.com/node/add/forum?edit[og_groups][]=72 // http://sbn.scbbs.com/node/add/simplenews?edit[og_groups][]=72 // http://sbn.scbbs.com/node/add/webform?edit[og_groups][]=72 // http://sbn.scbbs.com/node/add/video?edit[og_groups][]=72 // http://sbn.scbbs.com/node/add/page?edit[og_groups][]=72 // http://sbn.scbbs.com/node/add/blog?edit[og_groups][]=72 // http://sbn.scbbs.com/node/add/event?edit[og_groups][]=72 // http://sbn.scbbs.com/node/add/poll?edit[og_groups][]=72 // http://sbn.scbbs.com/node/add/flexinode-3?edit[og_groups][]=72 if ($arg[1] == 'node' && strpos($arg[3], 'og_groups') !== false && (!is_null($arg[3])) ) { $subsections = explode("=", $arg[3]); $gid = (int)$subsections[1]; } } // end $gid if // // Now, using $uid and $gid we find out what roles this user has in this group; // // // And, this is the query I want to use // $results = db_query('SELECT role.rid FROM role INNER JOIN og_users_roles ON role.rid = og_users_roles.rid WHERE og_users_roles.uid = ' . $uid . ' AND og_users_roles.gid = ' . $gid ); while ( $row = db_fetch_array($results) ) { $ogroles[$x1] = $row["rid"]; $x1++; } // // First, we need to create an array of the $user->role keys // // $temp = implode(", ", array_keys($user02->roles)); $temp = implode(", ", array_keys($user->roles)); $c = array(); $c = explode(", ", $temp); // // Next, we add the $user->roles array to the $ogroles array // $d = array(); $d = array_merge($c, $ogroles); // // Debug to test table // // $testDate = format_date(time(), 'custom', 'Y-m-d h:i:s a'); // $testUser = $user->uid; // $testUserName = $user->name; // $testURL = $uri_request_id; // $testArg0 = $arg[0]; // $testArg1 = $arg[1]; // $testArg2 = $arg[2]; // $testAArg0 = arg(0); // $testAArg1 = arg(1); // $testAArg2 = arg(2); // $testGroup = $gid; // $testArray = implode(",", $d); // $testResults = 'SELECT role.rid FROM role INNER JOIN og_users_roles ON role.rid = og_users_roles.rid WHERE og_users_roles.uid = ' . $uid . ' AND og_users_roles.gid = ' . $gid; // if (user_table_exists('test')) { // $testQuery = "insert into test values('" . $testDate . "|" . $testUser . "|" . $testUserName . "|" . $testURL . "|" . $testAArg0 . "|" . $testAArg1 . "|" . $testAArg2 . "| GroupID : " . $testGroup. "| Results : " . $testResults . "| Rows : " . $x1 . "| Array : " . $testArray . "')"; // db_query($testQuery); // } // // End debug test // // // If I don't do this, then I won't get the merged results; // return $d; } // end user_all_roles() function getgid($nodeID, $uid) { // This will return a $gid based upon the $nodeID and $uid supplied $gid = 0; // $result = db_query("select node_access.gid from node_access INNER JOIN og_uid ON node_access.gid = og_uid.nid WHERE node_access.nid = $nodeID AND og_uid.uid = $uid"); $result = db_query("select node_access.gid from node_access INNER JOIN og_uid ON node_access.gid = og_uid.nid WHERE node_access.realm = 'og_subscriber' AND node_access.nid = $nodeID AND og_uid.uid = $uid"); while($t = db_fetch_object($result)) { $gid = $t->gid; } // If $gid still equals 0 then try searching og_term table (if it exists) // og forums will typically be listed here if ($gid == 0) { if (user_table_exists('og_term')) { $result = db_query("select og_term.nid from og_term INNER JOIN og_uid ON og_term.nid = og_uid.nid WHERE og_term.tid = $nodeID AND og_uid.uid = $uid"); while($t = db_fetch_object($result)) { $gid = $t->nid; } } } return $gid; } // end getgid() function user_table_exists($table) { return db_num_rows(db_query("SHOW TABLES LIKE '{" . db_escape_table($table) . "}'")); } /** * Checks for usernames blocked by user administration * * @return boolean true for blocked users, false for active */ function user_is_blocked($name) { $allow = db_fetch_object(db_query("SELECT * FROM {users} WHERE status = 1 AND name = LOWER('%s')", $name)); $deny = db_fetch_object(db_query("SELECT * FROM {users} WHERE status = 0 AND name = LOWER('%s')", $name)); return $deny && !$allow; } /** * Send an e-mail message. */ function user_mail($mail, $subject, $message, $header) { if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) { include_once './' . variable_get('smtp_library', ''); return user_mail_wrapper($mail, $subject, $message, $header); } else { /* ** Note: if you are having problems with sending mail, or mails look wrong ** when they are received you may have to modify the str_replace to suit ** your systems. ** - \r\n will work under dos and windows. ** - \n will work for linux, unix and BSDs. ** - \r will work for macs. ** ** According to RFC 2646, it's quite rude to not wrap your e-mails: ** ** "The Text/Plain media type is the lowest common denominator of ** Internet e-mail, with lines of no more than 997 characters (by ** convention usually no more than 80), and where the CRLF sequence ** represents a line break [MIME-IMT]." ** ** CRLF === \r\n ** ** http://www.rfc-editor.org/rfc/rfc2646.txt ** */ return mail( $mail, mime_header_encode($subject), str_replace("\r", '', $message), "MIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8; format=flowed\nContent-transfer-encoding: 8Bit\n" . $header ); } } function user_fields() { static $fields; if (!$fields) { $result = db_query('SELECT * FROM {users} WHERE uid = 1'); if (db_num_rows($result)) { $fields = array_keys(db_fetch_array($result)); } else { // Make sure we return the default fields at least $fields = array('uid', 'name', 'pass', 'mail', 'picture', 'mode', 'sort', 'threshold', 'theme', 'signature', 'created', 'access', 'login', 'status', 'timezone', 'language', 'init', 'data'); } } return $fields; } /** * Implementation of hook_perm(). */ function user_perm() { return array('administer access control', 'administer users', 'access user profiles', 'change own username'); } /** * Implementation of hook_file_download(). * * Ensure that user pictures (avatars) are always downloadable. */ function user_file_download($file) { if (strpos($file, variable_get('user_picture_path', 'pictures') .'/picture-') === 0) { $info = image_get_info(file_create_path($file)); return array('Content-type: '. $info['mime_type']); } } /** * Implementation of hook_search(). */ function user_search($op = 'search', $keys = null) { switch ($op) { case 'name': if (user_access('access user profiles')) { return t('users'); } case 'search': if (user_access('access user profiles')) { $find = array(); // Replace wildcards with MySQL/PostgreSQL wildcards. $keys = preg_replace('!\*+!', '%', $keys); $result = pager_query("SELECT * FROM {users} WHERE LOWER(name) LIKE LOWER('%%%s%%')", 15, 0, NULL, $keys); while ($account = db_fetch_object($result)) { $find[] = array('title' => $account->name, 'link' => url('user/'. $account->uid)); } return $find; } } } /** * Implementation of hook_user(). */ function user_user($type, &$edit, &$user, $category = NULL) { if ($type == 'view') { $items[] = array('title' => t('Member for'), 'value' => format_interval(time() - $user->created), 'class' => 'member', ); return array(t('History') => $items); } if ($type == 'form' && $category == 'account') { return user_edit_form(arg(1), $edit); } if ($type == 'validate' && $category == 'account') { return _user_edit_validate(arg(1), $edit); } if ($type == 'submit' && $category == 'account') { return _user_edit_submit(arg(1), $edit); } if ($type == 'categories') { return array(array('name' => 'account', 'title' => t('account settings'), 'weight' => 1)); } } /** * Implementation of hook_block(). */ function user_block($op = 'list', $delta = 0, $edit = array()) { global $user; if ($op == 'list') { $blocks[0]['info'] = t('User login'); $blocks[1]['info'] = t('Navigation'); $blocks[2]['info'] = t('Who\'s new'); $blocks[3]['info'] = t('Who\'s online'); return $blocks; } else if ($op == 'configure' && $delta == 3) { $period = drupal_map_assoc(array(30, 60, 120, 180, 300, 600, 900, 1800, 2700, 3600, 5400, 7200, 10800, 21600, 43200, 86400), 'format_interval'); $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.')); $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.')); return $form; } else if ($op == 'save' && $delta == 3) { variable_set('user_block_seconds_online', $edit['user_block_seconds_online']); variable_set('user_block_max_list_count', $edit['user_block_max_list_count']); } else if ($op == 'view') { $block = array(); switch ($delta) { case 0: // For usability's sake, avoid showing two login forms on one page. if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) { $form['#action'] = url($_GET['q'], drupal_get_destination()); $form['#id'] = 'user-login-form'; $form['name'] = array('#type' => 'textfield', '#title' => t('Username'), '#maxlength' => 60, '#size' => 15, '#required' => TRUE, ); $form['pass'] = array('#type' => 'password', '#title' => t('Password'), '#size' => 15, '#required' => TRUE, ); $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), ); if (variable_get('user_register', 1)) { $items[] = l(t('Create new account'), 'user/register', array('title' => t('Create a new user account.'))); } $items[] = l(t('Request new password'), 'user/password', array('title' => t('Request new password via e-mail.'))); $form['links'] = array('#value' => theme('item_list', $items)); $block['subject'] = t('User login'); $block['content'] = drupal_get_form('user_login_block', $form, 'user_login'); } return $block; case 1: if ($menu = theme('menu_tree')) { $block['subject'] = $user->uid ? $user->name : t('Navigation'); $block['content'] = $menu; } return $block; case 2: if (user_access('access content')) { // Retrieve a list of new users who have subsequently accessed the site successfully. $result = db_query_range('SELECT uid, name FROM {users} WHERE status != 0 AND access != 0 ORDER BY created DESC', 0, 5); while ($account = db_fetch_object($result)) { $items[] = $account; } $output = theme('user_list', $items); $block['subject'] = t('Who\'s new'); $block['content'] = $output; } return $block; case 3: if (user_access('access content')) { // Count users with activity in the past defined period. $time_period = variable_get('user_block_seconds_online', 900); // Perform database queries to gather online user lists. $guests = db_fetch_object(db_query('SELECT COUNT(sid) AS count FROM {sessions} WHERE timestamp >= %d AND uid = 0', time() - $time_period)); $users = db_query('SELECT uid, name, access FROM {users} WHERE access >= %d AND uid != 0 ORDER BY access DESC', time() - $time_period); $total_users = db_num_rows($users); // Format the output with proper grammar. if ($total_users == 1 && $guests->count == 1) { $output = t('There is currently %members and %visitors online.', array('%members' => format_plural($total_users, '1 user', '%count users'), '%visitors' => format_plural($guests->count, '1 guest', '%count guests'))); } else { $output = t('There are currently %members and %visitors online.', array('%members' => format_plural($total_users, '1 user', '%count users'), '%visitors' => format_plural($guests->count, '1 guest', '%count guests'))); } // Display a list of currently online users. $max_users = variable_get('user_block_max_list_count', 10); if ($total_users && $max_users) { $items = array(); while ($max_users-- && $account = db_fetch_object($users)) { $items[] = $account; } $output .= theme('user_list', $items, t('Online users')); } $block['subject'] = t('Who\'s online'); $block['content'] = $output; } return $block; } } } function theme_user_picture($account) { if (variable_get('user_pictures', 0)) { if ($account->picture && file_exists($account->picture)) { $picture = file_create_url($account->picture); } else if (variable_get('user_picture_default', '')) { $picture = variable_get('user_picture_default', ''); } if (isset($picture)) { $alt = t('%user\'s picture', array('%user' => $account->name ? $account->name : variable_get('anonymous', 'Anonymous'))); $picture = theme('image', $picture, $alt, $alt, '', false); if (!empty($account->uid) && user_access('access user profiles')) { $picture = l($picture, "user/$account->uid", array('title' => t('View user profile.')), NULL, NULL, FALSE, TRUE); } return "
$msg
"); } $form['name'] = array('#type' => 'textfield', '#title' => t('Username'), '#size' => 30, '#maxlength' => 60, '#required' => TRUE, '#attributes' => array('tabindex' => '1'), ); if (variable_get('drupal_authentication_service', FALSE) && count(user_auth_help_links()) > 0) { $form['name']['#description'] = t('Enter your %s username, or an ID from one of our affiliates: %a.', array('%s' => variable_get('site_name', 'local'), '%a' => implode(', ', user_auth_help_links()))); } else { $form['name']['#description'] = t('Enter your %s username.', array('%s' => variable_get('site_name', 'local'))); } $form['pass'] = array('#type' => 'password', '#title' => t('Password'), '#description' => t('Enter the password that accompanies your username.'), '#required' => TRUE, '#attributes' => array('tabindex' => '2'), ); $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), '#weight' => 2, '#attributes' => array('tabindex' => '3')); return drupal_get_form('user_login', $form); } function user_login_validate($form_id, $form_values) { if ($form_values['name']) { if (user_is_blocked($form_values['name'])) { // blocked in user administration form_set_error('login', t('The username %name has not been activated or is blocked.', array('%name' => theme('placeholder', $form_values['name'])))); } else if (drupal_is_denied('user', $form_values['name'])) { // denied by access controls form_set_error('login', t('The name %name is a reserved username.', array('%name' => theme('placeholder', $form_values['name'])))); } else if ($form_values['pass']) { $user = user_authenticate($form_values['name'], trim($form_values['pass'])); if (!$user->uid) { form_set_error('login', t('Sorry. Unrecognized username or password.') .' '. l(t('Have you forgotten your password?'), 'user/password')); watchdog('user', t('Login attempt failed for %user.', array('%user' => theme('placeholder', $form_values['name'])))); } } } } function user_login_submit($form_id, $form_values) { global $user; if ($user->uid) { // To handle the edge case where this function is called during a // bootstrap, check for the existence of t(). if (function_exists('t')) { $message = t('Session opened for %name.', array('%name' => theme('placeholder', $user->name))); } else { $message = "Session opened for ". check_plain($user->name); } watchdog('user', $message); // Update the user table timestamp noting user has logged in. db_query("UPDATE {users} SET login = %d WHERE uid = %d", time(), $user->uid); user_module_invoke('login', $form_values, $user); $old_session_id = session_id(); session_regenerate_id(); db_query("UPDATE {sessions} SET sid = '%s' WHERE sid = '%s'", session_id(), $old_session_id); } } function user_authenticate($name, $pass) { global $user; // Try to log in the user locally. Don't set $user unless successful. if ($account = user_load(array('name' => $name, 'pass' => $pass, 'status' => 1))) { $user = $account; } // Strip name and server from ID: if ($server = strrchr($name, '@')) { $name = substr($name, 0, strlen($name) - strlen($server)); $server = substr($server, 1); } // When possible, determine corresponding external auth source. Invoke // source, and log in user if successful: if (!$user->uid && $server && $result = user_get_authmaps("$name@$server")) { if (module_invoke(key($result), 'auth', $name, $pass, $server)) { $user = user_external_load("$name@$server"); watchdog('user', t('External load by %user using module %module.', array('%user' => theme('placeholder', $name .'@'. $server), '%module' => theme('placeholder', key($result))))); } else { $error = t('Invalid password for %s.', array('%s' => theme('placeholder', $name .'@'. $server))); } } // Try each external authentication source in series. Register user if // successful. else if (!$user->uid && $server) { foreach (module_list() as $module) { if (module_hook($module, 'auth')) { if (module_invoke($module, 'auth', $name, $pass, $server)) { if (variable_get('user_register', 1) == 1) { $account = user_load(array('name' => "$name@$server")); if (!$account->uid) { // Register this new user. $user = user_save('', array('name' => "$name@$server", 'pass' => user_password(), 'init' => "$name@$server", 'status' => 1, "authname_$module" => "$name@$server")); watchdog('user', t('New external user: %user using module %module.', array('%user' => theme('placeholder', $name .'@'. $server), '%module' => theme('placeholder', $module))), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $user->uid .'/edit')); break; } } } } } } return $user; } /** * Menu callback; logs the current user out, and redirects to the home page. */ function user_logout() { global $user; watchdog('user', t('Session closed for %name.', array('%name' => theme('placeholder', $user->name)))); // Destroy the current session: session_destroy(); module_invoke_all('user', 'logout', NULL, $user); // We have to use $GLOBALS to unset a global variable: $user = user_load(array('uid' => 0)); drupal_goto(); } function user_pass() { // Display form: $form['name'] = array('#type' => 'textfield', '#title' => t('Username'), '#size' => 30, '#maxlength' => 60, ); $form['mail'] = array('#type' => 'textfield', '#title' => t('E-mail address'), '#size' => 30, '#maxlength' => 64, ); $form['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'), '#weight' => 2, ); return drupal_get_form('user_pass', $form); } function user_pass_validate() { global $form_values; $name = $form_values['name']; $mail = $form_values['mail']; if ($name && !($form_values['account'] = user_load(array('name' => $name, 'status' => 1)))) { form_set_error('name', t('Sorry. The username %name is not recognized.', array('%name' => theme('placeholder', $name)))); } else if ($mail && !($form_values['account'] = user_load(array('mail' => $mail, 'status' => 1)))) { form_set_error('mail', t('Sorry. The e-mail address %email is not recognized.', array('%email' => theme('placeholder', $mail)))); } else if (!$mail && !$name) { form_set_error('password', t('You must provide either a username or e-mail address.')); } } function user_pass_submit($form_id, $form_values) { global $base_url; $account = $form_values['account']; $from = variable_get('site_mail', ini_get('sendmail_from')); // Mail one time login URL and instructions. $variables = array('%username' => $account->name, '%site' => variable_get('site_name', 'drupal'), '%login_url' => user_pass_reset_url($account), '%uri' => $base_url, '%uri_brief' => substr($base_url, strlen('http://')), '%mailto' => $account->mail, '%date' => format_date(time()), '%login_uri' => url('user', NULL, NULL, TRUE), '%edit_uri' => url('user/'. $account->uid .'/edit', NULL, NULL, TRUE)); $subject = _user_mail_text('pass_subject', $variables); $body = _user_mail_text('pass_body', $variables); $headers = "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from"; $mail_success = user_mail($account->mail, $subject, $body, $headers); if ($mail_success) { watchdog('user', t('Password reset instructions mailed to %name at %email.', array('%name' => ''. $account->name .'', '%email' => ''. $account->mail .''))); drupal_set_message(t('Further instructions have been sent to your e-mail address.')); } else { watchdog('user', t('Error mailing password reset instructions to %name at %email.', array('%name' => theme('placeholder', $account->name), '%email' => theme('placeholder', $account->mail))), WATCHDOG_ERROR); drupal_set_message(t('Unable to send mail. Please contact the site admin.')); } return 'user'; } function theme_user_pass($form) { $output = ''. t('Enter your username or your e-mail address.') .'
'; $output .= form_render($form); return $output; } /** * Menu callback; process one time login link and redirects to the user page on success. */ function user_pass_reset($uid, $timestamp, $hashed_pass, $action = NULL) { global $user; // Check if the user is already logged in. The back button is often the culprit here. if ($user->uid) { drupal_set_message(t('You have already used this one-time login link. It is not necessary to use this link to login anymore. You are already logged in.')); drupal_goto(); } else { // Time out, in seconds, until login URL expires. 24 hours = 86400 seconds. $timeout = 86400; $current = time(); // Some redundant checks for extra security ? if ($timestamp < $current && $account = user_load(array('uid' => $uid, 'status' => 1)) ) { // No time out for first time login. if ($account->login && $current - $timestamp > $timeout) { drupal_set_message(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.')); drupal_goto('user/password'); } else if ($account->uid && $timestamp > $account->login && $timestamp < $current && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login)) { // First stage is a confirmation form, then login if ($action == 'login') { watchdog('user', t('User %name used one-time login link at time %timestamp.', array('%name' => "$account->name", '%timestamp' => $timestamp))); // Update the user table noting user has logged in. // And this also makes this hashed password a one-time-only login. db_query("UPDATE {users} SET login = %d WHERE uid = %d", time(), $account->uid); // Now we can set the new user. $user = $account; // And proceed with normal login, going to user page. user_module_invoke('login', $edit, $user); drupal_set_message(t('You have just used your one-time login link. It is no longer necessary to use this link to login. Please change your password.')); drupal_goto('user/'. $user->uid .'/edit'); } else { $form['message'] = array('#value' => t('This is a one-time login for %user_name and will expire on %expiration_date
Click on this button to login to the site and change your password.
', array('%user_name' => theme('placeholder',$account->name), '%expiration_date' => format_date($timestamp + $timeout)))); $form['help'] = array('#value' => t('This login can be used only once.
')); $form['submit'] = array('#type' => 'submit', '#value' => t('Log in')); $form['#action'] = url("user/reset/$uid/$timestamp/$hashed_pass/login"); return drupal_get_form('user_pass_reset', $form); } } else { drupal_set_message(t('You have tried to use a one-time login link which has either been used or is no longer valid. Please request a new one using the form below.')); drupal_goto('user/password'); } } else { // Deny access, no more clues. // Everything will be in the watchdog's URL for the administrator to check. drupal_access_denied(); } } } function user_pass_reset_url($account) { $timestamp = time(); return url("user/reset/$account->uid/$timestamp/".user_pass_rehash($account->pass, $timestamp, $account->login), NULL, NULL, TRUE); } function user_pass_rehash($password, $timestamp, $login) { return md5($timestamp . $password . $login); } function user_register() { global $user; $admin = user_access('administer users'); // If we aren't admin but already logged on, go to the user page instead. if (!$admin && $user->uid) { drupal_goto('user/'. $user->uid); } // Display the registration form. if (!$admin) { $form['user_registration_help'] = array('#type' => 'markup', '#value' => filter_xss_admin(variable_get('user_registration_help', ''))); } $affiliates = user_auth_help_links(); if (!$admin && count($affiliates) > 0) { $affiliates = implode(', ', $affiliates); $form['affiliates'] = array('#type' => 'markup', '#value' => ''. t('Note: if you have an account with one of our affiliates (%s), you may login now instead of registering.', array('%s' => $affiliates, '%login_uri' => url('user'))) .'
'); } $form['name'] = array('#type' => 'textfield', '#title' => t('Username'), '#size' => 30, '#maxlength' => 60, '#description' => t('Your full name or your preferred username; only letters, numbers and spaces are allowed.'), '#required' => TRUE); $form['mail'] = array('#type' => 'textfield', '#title' => t('E-mail address'), '#size' => 30, '#maxlength' => 64, '#description' => t('A password and instructions will be sent to this e-mail address, so make sure it is accurate.'), '#required' => TRUE, ); if ($admin) { $form['pass'] = array('#type' => 'password', '#title' => t('Password'), '#size' => 30, '#description' => t('Provide a password for the new account.'), '#required' => TRUE, ); $form['notify'] = array( '#type' => 'checkbox', '#title' => t('Notify user of new account') ); } $extra = _user_forms($null, $null, $null, 'register'); // Only display form_group around default fields if there are other groups. if ($extra) { $form['account'] = array('#type' => 'fieldset', '#title' => t('Account information')); $form['account']['name'] = $form['name']; $form['account']['mail'] = $form['mail']; $form['account']['pass'] = $form['pass']; $form['account']['notify'] = $form['notify']; unset($form['name'], $form['mail'], $form['pass'], $form['notify']); $form = array_merge($form, $extra); } $form['submit'] = array('#type' => 'submit', '#value' => t('Create new account'), '#weight' => 30); return drupal_get_form('user_register', $form); } function user_register_validate($form_id, $form_values) { user_module_invoke('validate', $form_values, $form_values, 'account'); } function user_register_submit($form_id, $form_values) { global $base_url; $admin = user_access('administer users'); $mail = $form_values['mail']; $name = $form_values['name']; $pass = $admin ? $form_values['pass'] : user_password(); $notify = $form_values['notify']; $from = variable_get('site_mail', ini_get('sendmail_from')); if (!$admin && array_intersect(array_keys($form_values), array('uid', 'roles', 'init', 'session', 'status'))) { watchdog('security', t('Detected malicious attempt to alter protected user fields.'), WATCHDOG_WARNING); return 'user/register'; } $account = user_save('', array_merge($form_values, array('pass' => $pass, 'init' => $mail, 'status' => ($admin || variable_get('user_register', 1) == 1)))); watchdog('user', t('New user: %name %email.', array('%name' => theme('placeholder', $name), '%email' => theme('placeholder', '<'. $mail .'>'))), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $account->uid .'/edit')); $variables = array('%username' => $name, '%site' => variable_get('site_name', 'drupal'), '%password' => $pass, '%uri' => $base_url, '%uri_brief' => substr($base_url, strlen('http://')), '%mailto' => $mail, '%date' => format_date(time()), '%login_uri' => url('user', NULL, NULL, TRUE), '%edit_uri' => url('user/'. $account->uid .'/edit', NULL, NULL, TRUE), '%login_url' => user_pass_reset_url($account)); // The first user may login immediately, and receives a customized welcome e-mail. if ($account->uid == 1) { user_mail($mail, t('Drupal user account details for %s', array('%s' => $name)), strtr(t("%username,\n\nYou may now login to %uri using the following username and password:\n\n username: %username\n password: %password\n\n%edit_uri\n\n--drupal"), $variables), "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from"); drupal_set_message(t('Welcome to Drupal. You are user #1, which gives you full and immediate access. All future registrants will receive their passwords via e-mail, so please make sure your website e-mail address is set properly under the general settings on the settings page.
Your password is %pass. You may change your password below.
', array('%pass' => $pass, '%settings' => url('admin/settings')))); user_authenticate($account->name, trim($pass)); // Set the installed schema version of the system module to the most recent version. include_once './includes/install.inc'; drupal_set_installed_schema_version('system', max(drupal_get_schema_versions('system'))); return 'user/1/edit'; } else { if ($admin && !$notify) { drupal_set_message(t('Created a new user account. No e-mail has been sent.')); return 'admin/user'; } else if ($account->status || $notify) { // Create new user account, no administrator approval required. $subject = $notify ? _user_mail_text('admin_subject', $variables) : _user_mail_text('welcome_subject', $variables); $body = $notify ? _user_mail_text('admin_body', $variables) : _user_mail_text('welcome_body', $variables); user_mail($mail, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from"); if ($notify) { drupal_set_message(t('Password and further instructions have been e-mailed to the new user %user.', array('%user' => theme('placeholder', $name)))); return 'admin/user'; } else { drupal_set_message(t('Your password and further instructions have been sent to your e-mail address.')); return ''; } } else { // Create new user account, administrator approval required. $subject = _user_mail_text('approval_subject', $variables); $body = _user_mail_text('approval_body', $variables); user_mail($mail, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from"); user_mail(variable_get('site_mail', ini_get('sendmail_from')), $subject, t("%u has applied for an account.\n\n%uri", array('%u' => $account->name, '%uri' => url("user/$account->uid/edit", NULL, NULL, TRUE))), "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from"); drupal_set_message(t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.'. t('The user module allows users to register, login, and logout. 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 can setup 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 anonymous - a user who has not logged in, and authenticated a user who has signed up and who has been authorized. ') .'
'; $output .= ''. t('Users can use their own name or handle and can fine tune some personal configuration settings through their individual my account page. Registered users need to authenticate by supplying either a local username and password, or a remote username and password such as DelphiForums ID, or one from a Drupal powered website. A visitor accessing your website is assigned an unique ID, the so-called session ID, which is stored in a cookie. For security\'s sake, the cookie does not contain personal information but acts as a key to retrieve the information stored on your server. ') .'
'; $output .= t('You can
'. t('For more information please read the configuration and customization handbook User page.', array('%user' => 'http://drupal.org/handbook/modules/user/')) .'
'; return $output; case 'admin/modules#description': return t('Manages the user registration and login system.'); case 'admin/user': return t('Drupal allows users to register, login, logout, maintain user profiles, etc. No participant can use his own name to post content until he signs up for a user account.
'); case 'admin/user/create': case 'admin/user/account/create': return t('This web page allows the administrators to register a new users by hand. Note that you cannot have a user where either the e-mail address or the username match another user in the system.
'); case strstr($section, 'admin/access/rules'): return t('Set up username and e-mail address access rules for new and 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.
'); case 'admin/access': return t('Permissions let you control what users can do on your site. Each user role (defined on the user roles page) 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/access/roles'))); case 'admin/access/roles': return t('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 user permissions. Examples of roles include: anonymous user, authenticated user, moderator, administrator and so on. In this area you will define the role names of the various roles. To delete a role choose "edit".
By default, Drupal comes with two user roles:
Enter a simple pattern ("*" may be used as a wildcard match) to search for a username. For example, one may search for "br" and Drupal might return "brian", "brad", and "brenda".
'); case 'admin/user/configure': case 'admin/user/configure/settings': return t('In order to use the full power of Drupal a visitor must sign up for an account. This page lets you setup how a user signs up, logs out, the guidelines from the system about user subscriptions, and the e-mails the system will send to the user.
'); case 'user/help#user': $site = variable_get('site_name', 'this website'); $output = t("One of the more tedious moments in visiting a new website is filling out the registration form. Here at %site, you do not have to fill out a registration form if you are already a member of %help-links. This capability is called distributed authentication, and is unique to Drupal, the software which powers %site.
Distributed authentication enables a new user to input a username and password into the login box, and immediately be recognized, even if that user never registered at %site. This works because Drupal knows how to communicate with external registration databases. For example, lets say that new user 'Joe' is already a registered member of Delphi Forums. Drupal informs Joe on registration and login screens that he may login with his Delphi ID instead of registering with %site. Joe likes that idea, and logs in with a username of joe@remote.delphiforums.com and his usual Delphi password. Drupal then contacts the remote.delphiforums.com server behind the scenes (usually using XML-RPC, HTTP POST, or SOAP) and asks: \"Is the password for user Joe correct?\". If Delphi replies yes, then we create a new %site account for Joe and log him into it. Joe may keep on logging into %site in the same manner, and he will always be logged into the same account.
", array('%help-links' => (implode(', ', user_auth_help_links())), '%site' => "$site", '%drupal' => 'http://drupal.org', '%delphi-forums' => 'http://www.delphiforums.com', '%xml' => 'http://www.xmlrpc.com', '%http-post' => 'http://www.w3.org/Protocols/', '%soap' => 'http://www.soapware.org')); foreach (module_list() as $module) { if (module_hook($module, 'auth')) { $output .= "