How to check site speed for logged in users - wordpress

How do I measure site speed for logged in users? The tools like pingdom, google page speed etc, check site speed for guests. the reason I ask is this.
My site is fast for guests because I have page caching. For logged in users, I don't have the pages cached and hence it is extremely slow. The end result is that my most loyal visitors (logged in users) are getting a slow site. If I can accurate measure it, I can move towards fixing it. Appreciate the help.

I handled this by creating a test user on the system (let's call the login my_test_user) and then added an action hook on init to check the URL for a token, and if the token is found it logs in as the test user before running the rest of the page. You can use whatever you want as the token as long as it is long and random enough, but this is a decent generator. Keep in mind that you should be using this via SSL (but then again, so should your logins with password).
From a security standpoint I would recommend hard coding the test user either in the code or as a constant in wp-config.php. If this is ever compromised, you don't want the hacker to be able to log in as any user, and your test user should have limited permissions. Perhaps even consider another token/key to enable/disable the functionality based on a wp_option value and only turn on when testing.
Once added to your functions.php you can use any URL in your tools appended with ?login_token=YOUR_LOGIN_TOKEN to view it as my_test_user.
function auto_login() {
$login_token = isset( $_GET['login_token'] )? $_GET['login_token'] : false;
// get a UUID from http://www.uuidgenerator.net/
if ( $login_token == 'ac88dc0e-72a8-4a22-abc0-fb5b5396c0ac' ){
// The test user we want to log in
$user_login = 'my_test_user';
// Get the user info
$user = get_user_by( 'login', $user_login );
// Log the test user in automatically
wp_set_current_user( $user->ID, $user_login );
wp_set_auth_cookie( $user->ID );
do_action( 'wp_login', $user_login );
}
}
// Set with a priority of 1 so that it runs ASAP
add_action( 'init', 'auto_login', 1 );

Related

Allow GravityForms uploaded content to be accessible for one form only

I'm usingGravity Forms where submissions are sent to various emails. Some forms ask for PII via uploaded files, so we restrict access to those links to only those who have login access. This filter is responsible for this feature across all forms.
add_filter( 'gform_require_login_pre_download', '__return_true' );
However, one form doesn't require this level of security and requires the download link to be open.
How can I 'turn off' this feature for one particular form?
This filter might work for this scenario but I'm not sure how to implement it.
https://docs.gravityforms.com/gform_permission_granted_pre_download/
Basically I would want to return $permission_granted if the form id is 6 (and the field id is 8 but not sure if that is required). This is what I have so far.
add_filter( 'gform_permission_granted_pre_download', function( $permission_granted, $form_id, $field_id ) {
if ($form_id = 6){
return $permission_granted;}
}, 10, 3 );

run a piece of code once in a day in wordpress

i was working in a wordpress registration plugin. i stucked in expiry of the user. actually i want to expire the member after one year of his/her registration. and i want to notify them via email before 1 month of their expiry. i am using add_action('init','my function name') to check how many of the user is going to expire after a month and also to send the mail. bt this action hook will run every time a user visits the site which will make my site too slow to load everytime a user will visit. so i want something dat will make this code run once in a day. e.g. when the first user visit the site this code will run and for the whole remaining day this code will not be invoke no matter how many user will visit the website.
Wordpress has a built-in function/API that just do exactly what you want - doing something every day/hour/any interval you specify.
http://codex.wordpress.org/Function_Reference/wp_schedule_event
Taken shamelessly from the above page
add_action( 'wp', 'prefix_setup_schedule' );
/**
* On an early action hook, check if the hook is scheduled - if not, schedule it.
*/
function prefix_setup_schedule() {
if ( ! wp_next_scheduled( 'prefix_daily_event' ) ) {
wp_schedule_event( time(), 'daily', 'prefix_daily_event');
}
}
add_action( 'prefix_daily_event', 'prefix_do_this_daily' );
/**
* On the scheduled action hook, run a function.
*/
function prefix_do_this_daily() {
// check every user and see if their account is expiring, if yes, send your email.
}
prefix_ is presumably to ensure there will be no collision with other plugins, so I suggest you to change this to something unique.
See http://wp.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress/ if you want to know more.

Wordpress inclusion in CodeIgniter leads to destroyed sessions

I had to add a WordPress installation to my CodeIgniter system, so I've put it in a submap called blog and excepted that folder in my .htaccess. All good and well.
I've put the all WordPress tables together with in my CodeIgniter databases with prefix _wp.
I've now loaded the WordPress blog header file into the index.php of CodeIgniter, like so;
require('blog/wp-blog-header.php');
add_filter('site_url', 'ci_site_url', 1);
function ci_site_url() {
include(FCPATH.'/application/config/config.php');
return $config['base_url'];
}
And made a registration method in my Account controller to make an actual link to my Customers. I do this because I want to make the WordPress login/registration obsolete and solely control that from the CodeIgniter login page;
protected function register_wp($email_address = FALSE) {
if ($email_address !== FALSE) {
if (username_exists( $email_address ) == NULL) {
$password = wp_generate_password(12, TRUE);
$user_id = wp_create_user($email_address, $password, $email_address);
wp_update_user(array(
'ID' => $user_id,
'nickname' => $email_address
));
$user = new WP_User($user_id);
$user->set_role('subscriber');
$login_data = array(
'user_id' => $user_id,
'password' => $password,
);
return $login_data;
}
else {
// User already exists with that email address
return FALSE;
}
}
else {
// No email_address given
return FALSE;
}
}
And the login method, to give an idea;
protected function login_wp($user_id = FALSE) {
if ($user_id !== FALSE) {
$user_login = 'admin';
$user = get_userdatabylogin($user_login);
$user_id = $user->ID;
wp_set_current_user($user_id, $user_login);
wp_set_auth_cookie($user_id);
do_action('wp_login', $user_login);
}
else {
// No user_id given
return FALSE;
}
}
All still going well. But here comes the clash; something I was very sad about because everything worked very well up until now:
WordPress overtakes the session and kills CodeIgniter's session.
I already tried tons of things;
session_rename('PHPSESSIDWP'); and then starting another session (with another name) for CodeIgniter after WordPress was loaded
COOKIE path (I'm not 100% sure if I done this right, as it didn't change at all. Read some things online it doesn't work well in all browsers either)
COOKIE domain (seemed to have no effect)
The problem is I can't load the require('blog/wp-blog-header.php'); only in the controller method, as I need to be able to control the logged in state of the WordPress part. Besides that I will get complaints about the site_url() function, that's already claimed by the URL helper.
I think the problem is mainly because both CodeIgniter and WordPress use their own unique way of handling Sessions (CI in the Database and WordPress in "super globals") which probably only makes them use the cookie to remember a "state".
My whole CodeIgniter system already runs on the Database-driven Session models so that's an absolute no-go to make a switch. For WordPress it seems it can't even work with session anymore with it's code features (I know session "do" work, but that doesn't seem to count in any way for the WP core system).
Also I quoted out wp_unregister_GLOBALS(); in the wp-settings.php file.
Plus that I also tried to rename my session COOKIE name in CodeIgniter to use something like session_ci
I really hope someone knows a way to being able to tell CodeIgniter or WordPress to only update their values and don't kill the whole session each time. I also read something about splitting up cookies with .htaccess but can't find good resources on it. So if anyone knows how to do that, I would be eternally grateful.
I'm in despair. Finishing it for 98% and then getting such a letdown in the end :(..
Update
Maybe I can do something in the WordPress section that handles the cookies?
http://codex.wordpress.org/Function_Reference/wp_set_auth_cookie
Sadly I'm not really home in the WordPress world. I solely have to use it this one time due to the bought template that the people really wanted to use in the blog.
Also this page states the following;
WordPress uses the two cookies to bypass the password entry portion of wp-login.php. If WordPress recognizes that you have valid, non-expired cookies, you go directly to the WordPress Administration interface. If you don't have the cookies, or they're expired, or in some other way invalid (like you edited them manually for some reason), WordPress will require you to log in again, in order to obtain new cookies.
I wonder tho, how to bypass that "invalid" check, which probably is the reason it kills the CodeIgniter cookie(s)? Weirdly enough tho, it seems the session_ci value stays, although the session still seems killed.
You need to put your session start at the very top of config.php.
This is the only place a session will not be destroyed by WordPress.
if (!session_id())
session_start();
If your PHP installation does not have register_global enabled, the
above code should allow you to use session, however, if it does, you
will not be able to get the data that was set in previous request.
This is because WordPress will destroy all data contained inside
session variable when it does the initialization.
Here's why and troubleshooting on this -> kanasolution.com
EXPANDED ANSWERS:
Source: http://codex.wordpress.org/WordPress_Cookies
On login, wordpress uses the wordpress_[hash] cookie to store your
authentication details. Its use is limited to the admin console area,
/wp-admin/
After login, wordpress sets the wordpress_logged_in_[hash] cookie, which indicates when you're logged in, and who you are, for
most interface use.
So WordPress clearly dislikes the way that you're writing cookies, maybe their lack of 8 pass MD5 hash etc? WordPress encryption methods
The WordPress Environment
The next thing I would try is integrating your custom login page into the WordPress environment instead of just requiring the header. (lets stay away from editing core)
From WordPress & AJAX by Ronald Huereca page 78 explains manually loading the WordPress environment.
The use of the dirname functions depend on the hierarchy of your file. Adjust them as needed. Code should be used before the tag of your file.
$root = dirname(dirname(dirname(dirname(dirname(__FILE__)))));
if (file_exists($root.'/wp-load.php')) {
require_once($root.'/wp-load.php');
/*Run custom WordPress stuff here */
//Output header HTML, queue scripts and styles, and include BODY content
wp_enqueue_script('my_script', get_stylesheet_directory_uri() . '/my_script.js', array('jquery'), '1.0.0');
wp_print_scripts(array('my_script'));
}

Change user_nicename after registration

Say we have a a mother site. Then we have a user registration form on a 3rd party site and a user register system which is processing the whole registration process and in the end will send the user login details in the mother site's database (mysql insertion, again no user_register function). Since there are 2 completely different browser sessions, no actions can be hooked on the mother site during or after registration.
So, let's say we will have stored the users in the database with logins like aaa#bbb.cc (weird, yes) and having a name and the user_nicename appearing like aaa#bbb.cc
Question:
What is the best aproach, wp action/function to be hooked, that once the user is stored in the mother site's database, to write a function to change the user nicename in something like aaa-bbb Automatically of course.
Is there a function/hook suggested for such cases?
The below code didn't helped me, since as I told above, I think the user_register action can't be triggered when a 3rd party site registration is processed:
add_action( 'user_register', 'myplugin_registration_save' );
function myplugin_registration_save( $user_id ) {
$info = get_userdata( $user_id );
$args = array(
'ID' => $user_id,
'user_nicename' => $info->first_name . '-' . $info->last_name
);
wp_update_user( $args );
}
The question as worded is really hard to understand. If I'm reading it correctly, you have two websites. Site One is where people are registering. When they complete registration on Site One something runs that creates a new user in the Site Two database by doing a direct sql insert, not by using any native WP functions.
If that's the case, why don't you simply manipulate the user login before you insert it into the Site Two db? You can't do it via a WordPress hook b/c WordPress is never being called. Hooks are just callback functions sprinkled through the WordPress code. When something happens, like a new user is created, there is a hook that you can assign a function to -- something "Send me an email." If WordPress doesn't handle the new user creation then the hook never gets called.
If you have to do the manipulation after the data has been inserted you'll probably need to look at using a cron job that runs every X amount of time looking for new records in the wp_users table.

Drupal: access permissions for php scripts?

I'm writing a custom php code in my Drupal website. I need to load the content of specific pages from PHP.
These pages are visible only for authenticated users, and it seems I cannot access them from php, even if I trigger the script when I'm logged in as user.
Is there a way to simulate "a logged in" user from php, so I have access to all the content of the website ?
update:
global $user;
if (user_access('access content')) {
require_once("dompdf/dompdf_config.inc.php");
$html = file_get_contents('http://mywebsite.com/admin/store/orders/45/invoice/print');
$dompdf = new DOMPDF();
$dompdf->load_html($html);
//$dompdf->load_html_file('invoices/' . $file);
$dompdf->render();
$dompdf->stream("sample.pdf");
}
I've tried with relative path and it is the same...
And this is with impersonating the admin user
//access as administrator
global $user;
$original_user = $user;
session_save_session(FALSE);
$user = user_load(array('uid' => 1));
//generate pdf
require_once("dompdf/dompdf_config.inc.php");
$html = file_get_contents('http://mywebsite/admin/store/orders/45/invoice/print');
$dompdf = new DOMPDF();
$dompdf->load_html($html);
//$dompdf->load_html_file('invoices/' . $file);
$dompdf->render();
$dompdf->stream("sample.pdf");
//logout as administrator
$user = $original_user;
session_save_session(TRUE);
Still I get access denied as resulting page (and generated pdf).
thanks
The code to do so is:
<?php
if (user_access('access content')) {
print "You have the permission 'access content'";
}
?>
Running code that circumvents the permission system might seem simple and easy, but is really a serious security hole.
However, since that is what you ask:
<?php
global $user;
if ($user->uid) {
print "You are a registered user"
}
?>
But again, never use this as a replacement for permissions.
These pages are visible only for authenticated users, and it seems I cannot access them from php, even if I trigger the script when I'm logged in as user.
Drupal checks if the user has permission to view a node using the global variable $user. To do what you are trying to do, if you cannot trust that the currently logged in user have the permission to view the node you are interested in, you should read Safely Impersonating Another User.
I am not saying that you should be doing that. Before to impersonate another user, I would verify if the followed approach is the only possible one.
For example, if you just need to access a field contained in a node, then you can use node_load(), which doesn't verify if the current user can view the loaded node.
If you need to show the body of a node, you can use the following code:
$node = node_load($nid);
if ($node) {
$body = check_markup($node->body, $node->format, FALSE);
}
Showing information for which the current user doesn't have access is considered a security issue, though.
Update
The issue with your code is that you are using file_get_contents('http://mywebsite/admin/store/orders/45/invoice/print'); doing so, you are opening a new connection to the site, and the new connection is opened as anonymous user. That is the reason the node that authenticated users are able to see is not returned.
Even if the code would work, what you get is not the HTML to render the node only, but also the full page, including the blocks Drupal normally show on the top, and to the left/right sides.
If you are interested in rendering a node, then you should use the following code. (It's just a skeleton, and it's not complete.)
// $nid is the node ID.
// Check the result, in the case the node has been deleted, or there are other errors.
$node = node_load($nid);
if ($node) {
// The arguments tell the function that you don't want to render a teaser, that the node is
// rendered as it is the only node in the page, and that you don't want the additional
// links that are usually rendered after the node content.
$html = node_view($node, FALSE, TRUE, FALSE);
// This is your code.
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");
}
About the updated code.
Your file_get_contents will pull in the content as "anonymous user". That is just one reason why your code is a bad idea:
Whenever your code runs, it will open your own site and parse that code: resulting in at least two "Drupals" to be loaded: effectively at least two pageviews to show one page to a user. But many more problems with this approach are possible.
Instead, you should find the code/function that creates the page at http://mywebsite.com/admin/store/orders/45/invoice/print and use that as input for your PDF-creator.

Resources