Get all the logged-in user - drupal

I want to have my own chat. (I can't use the Chat module because I have to personalize it.) I have to retrieve all the users who are online, but I can't see any variable for that.
I am only able to get the name of the currently logged-in user, but not the rest of the logged-in users.

You can fetch a list of all logged in users by querying the sessions table. I'm assuming you're using Drupal 6.
<?php
$result = db_query('SELECT uid FROM {sessions} WHERE uid != 0');
$users = array();
while($user = db_fetch_array($result)) {
$users[] = user_load($user);
}
The query excludes sessions for uid = 0 as these are anonymous users. $users is the array of user objects as described in the Drupal API Docs.
You can optimize this if you already know what part of the user objects you will use (e.g. just the user id and name) by removing the user_load() in while loop and adding to the query a join with the users table, as each user_load() makes one additional query. The following would get you a list of logged in users' id and names:
<?php
$result = db_query('SELECT u.uid, u.name FROM {sessions} s INNER JOIN {users} u ON u.uid = s.uid WHERE s.uid != 0');
$users = array();
while($users[] = db_fetch_array($result));
Since logged in users never time out (you can stay logged in indefinitely), it may be useful to exclude logged in users who haven't accessed the site in a while (i.e. maybe an hour of inactivity):
$timestamp = time - 3600; // 3600s is one hour.
$result = db_query('SELECT uid FROM {sessions} WHERE uid != 0 AND timestamp >= %d', $timestamp);
You might also want to limit how many users to return. For example, maybe you want to grab - at most - the last 10 logged in users who accessed the site:
$limit = 10; // Limit to the last 10 users.
$result = db_query_range('SELECT uid FROM {sessions} WHERE uid != 0 ORDER BY timestamp DESC', $timestamp, 0, $limit);
As an aside, if you're going to be using magic numbers (like $limit or the 3600s), you should make them persistent using variable_set(), variable_get(), and variable_del().

Related

How to best store custom user fields for non logged in users in Wordpress

I have a Wordpress site that has lots of users who are just visitors. They can choose 2 settings which determines the sort order of results and these are saved as cookies.
If they choose to create an account later then I'd like to pre-populate 2 custom user fields (I'm using Advanced Custom Fields) with their previous choices as visitors from the cookies.
What is the best way to do this? I.e something the same way Woocommerce stores cart data / wishlists for non logged in users that persist after account creation.
Currently I am using this for the sorting but it seems a bit inefficient if I am going to try and pre-populate fields on registration anyway...
//check if user is logged in and then get saved fuel choice
if ( is_user_logged_in() ) {
$userid = get_current_user_id();
$fuelchoice = get_the_author_meta( 'fuel_choice', $userid );
} else {
//get the cookie if just a visitor
if(isset($_COOKIE['fuelchoice'])) {
$fuelchoice = $_COOKIE["fuelchoice"];
}
}
if ($fuelchoice == "diesel"){
//sort function etc
}

Is there a function to retrieve all current logged-in users?

Is there a function to retrieve all current logged-in users for Drupal 7?
I tried to build a query based on Get all the logged-in user.
$query->join('users', 'u', 's.uid = u.uid'); //JOIN sessions with users
$query->fields('u',array('name')) //SELECT the fields from node
->orderBy('timestamp', 'DESC') //ORDER BY timestamp
->range(0,10); //LIMIT to 10 records
->execute()
->fetchAll();
$result = $query->execute();
I'm still missing something on to retrieve all names from $result as an array, and on how to limit the query to return the users who were active in the last 5 minutes.
I need to put these into an array with their usernames in #title and their user IDs in #href.
Retrieve users logged in last 5 minutes :
$users_results = db_query('SELECT u.uid , u.name FROM users u
WHERE ( UNIX_TIMESTAMP(NOW()) - u.access ) < (5*60)')
->fetchAllKeyed();
dsm($users_results);
EDIT
Like asked :
foreach($users_results as $uid => $name){
$users[$name] = array('#title' => $name , '#href' => $uid);
}

(Wordpress) User Registered On Current Month

How to made function to count total user registered on Wordpress site with just specific roles (eg: manager) and just users that registered current month only?
Example code, it will output user registered all time, I want it just ouput user registered on current month only.
function totalusertoday() {
global $wpdb;
$query = "SELECT COUNT(ID) FROM {$wpdb->prefix}users WHERE user_status = 0";
return $wpdb->get_var($query);
}
echo 'Total User Today: ' . totalusertoday();
Have a look at the Database Model:
http://codex.wordpress.org/images/9/97/WP3.8-ERD.png
To count all new users from this month, simply select all Users with registred Timestamp > then 1. day of this month.
To get only users with a specific role you have to select the user and the wp_usermeta, in wp_usermeta is a row called wp_capabilities.
http://wordpress.org/support/topic/name-of-database-fields-for-user-rolespermissions
Basically it's just a bit of sql query.
Solved! I'm just put filter for current month and year on user registered. And I've made simple code for this. Here is example code:
<?php
global $wpdb;
$date = getdate();
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users WHERE MONTH(user_registered) = $date[mon] AND YEAR(user_registered) = $date[year]" );
echo "<p>User count is {$user_count}</p>";
?>

Can I temporarily change a user's role in Wordpress?

I need to grant users a specific role (Editor, Administrator, etc.) along with all its capabilities on the fly in Wordpress, but I don't want to update their role in the database (so that the next time they come back, they will have their original role). How can I go about doing this?
Here's what I ended up doing:
add_filter( 'user_has_cap', 'override_caps' );
function override_caps($allcaps){
if( ... ){ // When to override caps
$role_name = 'administrator';
$role = get_role($role_name); // Get the role object by role name
$allcaps = $role->capabilities; // Get the capabilities for the role
$allcaps[$role_name] = true; // Add role name to capabilities
}
return $allcaps;
}

Drupal - Restricting access to users

I need to be able to add pages and then restrict these by different types of user: Anonymous, Partial and Full.
When registering, a user can enter all details to get a full registration or only half their details e.g don't need to enter address, telephone etc to gain a partial registration type.
Then when adding a page I need to be able to select whether anonymous, partial and/or full have access to it. If they don't then it still needs to show the summary of the page as a teaser but they won't have access to the main content until they have registered and signed in.
I have installed the Simple Access plugin which allows me to create groups but unsure how to implement the registration form so that if the user only enters the required fields they will become a Partial user, otherwise they will become a Full user. Any suggestions?
You can use the Rules module. Create a triggered rule that runs on new user creation, then check the fields and finally assign the user a role accordingly.
I've ended up using a hook to implement whether a user is a normal authorised user or a full user. Can someone please check the hook below is correct? Im new to Drupal so not sure if any other tables are affected when adding/deleting roles.
function module_user_update(&$edit, $account, $category) {
$dob = field_get_items('user', $account, 'field_dob');
$address1 = field_get_items('user', $account, 'field_address1');
$address2 = field_get_items('user', $account, 'field_address2');
$address3 = field_get_items('user', $account, 'field_address3');
$city = field_get_items('user', $account, 'field_city');
$postcode = field_get_items('user', $account, 'field_postcode');
$county = field_get_items('user', $account, 'field_county');
$telephone = field_get_items('user', $account, 'field_telephone');
if(empty($dob[0]['value']) || empty($address1[0]['value']) || empty($address2[0]['value']) || empty($address3[0]['value']) || empty($city[0]['value']) || empty($postcode[0]['value']) || empty($county[0][$
{
$userid = $account->uid;
//remove full role from db so user is only an authorised user
db_query("DELETE FROM {users_roles} WHERE uid = '".$userid."' && rid = '5'");
} else {
$userid = $account->uid;
//delete full role if it already exists so it doesnt go in twice
db_query("DELETE FROM {users_roles} WHERE uid = '".$userid."' && rid = '5'");
//insert full role
db_query("INSERT INTO {users_roles} (rid, uid) VALUES ('5',$userid)");
}
}
You would do well to look into some of the beginning Drupal tutorials. Roles, rules, triggers and CCK (and content_permissions) -- those are the modules/concepts you'll be looking at learning about.
They will arm you with what you need. CCK will allow for you to create specific content types, content_permissions (included in CCK) will allow for you to set visibility based on a user's role, roles will allow for you to create a new group of users, and as #Laxman13 said, rules will allow for you to set up rules to do what needs to be done (i.e. add this user to X role), and triggers will provide you with the functionality to do that.

Resources