index-wp-redis.php 9.6 KB
Newer Older
Benjamin Adams's avatar
Benjamin Adams committed
1
<?php
2 3 4 5 6 7 8 9 10
/**
 * WP REDIS CACHE
 */

/**
 * GLOBAL CONFIGURATION
 */
$GLOBALS['wp_redis_cache_config'] = array(
	'debug'         => false,
11
	'cache'         => false,
12 13 14 15 16 17 18
	'server_ip'     => '127.0.0.1',
	'redis_server'  => '127.0.0.1',
	'redis_port'    => 6379,
	'redis_db'      => 0,
	'secret_string' => 'changeme',
);

19 20 21
// Uncomment either option below to fix the values here and disable the admin UI
// $GLOBALS['wp_redis_cache_config']['cache_duration'] = 43200;
// $GLOBALS['wp_redis_cache_config']['unlimited']      = false;
22

23 24 25 26 27
// Modify this function to introduce custom handling when exceptions occur
function wp_redis_cache_exception_handler( $exception ) {
	return;
}

28
/**
29 30
 * END GLOBAL CONFIGURATION
 *
31 32
 * DO NOT EDIT BELOW THIS LINE!
 */
Erick Hitter's avatar
Erick Hitter committed
33
$GLOBALS['wp_redis_cache_config']['current_url'] = wp_redis_cache_get_clean_url( $GLOBALS['wp_redis_cache_config']['secret_string'] );
34
$GLOBALS['wp_redis_cache_config']['redis_key']   = md5( $GLOBALS['wp_redis_cache_config']['current_url'] );
Benjamin Adams's avatar
Benjamin Adams committed
35

Ulrich Block's avatar
Ulrich Block committed
36 37 38
// Start the timer so we can track the page load time
$start = microtime();

39 40 41 42 43 44 45
/**
 * MOBILE HANDLING
 */
if ( wp_redis_cache_is_mobile_request() ) {
	$GLOBALS['wp_redis_cache_config']['redis_key'] = 'MO-' . $GLOBALS['wp_redis_cache_config']['redis_key'];
}

46 47 48 49 50 51 52 53 54
/**
 * UTILITY FUNCTIONS
 */

/**
 * Compute microtime from a timestamp
 *
 * @return float
 */
Erick Hitter's avatar
Erick Hitter committed
55
function wp_redis_cache_get_micro_time( $time ) {
Erick Hitter's avatar
Erick Hitter committed
56 57
	list( $usec, $sec ) = explode( " ", $time );
	return ( (float) $usec + (float) $sec );
Ulrich Block's avatar
Ulrich Block committed
58 59
}

60 61 62 63 64
/**
 * Is the current request a refresh request with the correct secret key?
 *
 * @return bool
 */
Erick Hitter's avatar
Erick Hitter committed
65
function wp_redis_cache_refresh_has_secret( $secret ) {
Erick Hitter's avatar
Erick Hitter committed
66
	return isset( $_GET['refresh'] ) && $secret == $_GET['refresh'];
Benjamin Adams's avatar
merged  
Benjamin Adams committed
67
}
Ulrich Block's avatar
Ulrich Block committed
68

69 70 71 72 73
/**
 * Does current request include a refresh request?
 *
 * @return bool
 */
Erick Hitter's avatar
Erick Hitter committed
74
function wp_redis_cache_request_has_secret( $secret ) {
Erick Hitter's avatar
Erick Hitter committed
75
	return false !== strpos( $_SERVER['REQUEST_URI'], "refresh=${secret}" );
Benjamin Adams's avatar
merged  
Benjamin Adams committed
76
}
Hendrik Klemp's avatar
Hendrik Klemp committed
77

78 79 80 81 82
/**
 * Determine if request is from a server other than the one running this code
 *
 * @return bool
 */
Erick Hitter's avatar
Erick Hitter committed
83
function wp_redis_cache_is_remote_page_load( $current_url, $server_ip ) {
Erick Hitter's avatar
Erick Hitter committed
84
	return ( isset( $_SERVER['HTTP_REFERER'] )
85
			&& $_SERVER['HTTP_REFERER'] == $current_url
Erick Hitter's avatar
Erick Hitter committed
86
			&& $_SERVER['REQUEST_URI'] != '/'
87
			&& $_SERVER['REMOTE_ADDR'] != $server_ip );
Benjamin Adams's avatar
merged  
Benjamin Adams committed
88
}
Hendrik Klemp's avatar
Hendrik Klemp committed
89

90 91 92 93 94
/**
 * Set proper IP address for proxied requests
 *
 * @return null
 */
Erick Hitter's avatar
Erick Hitter committed
95
function wp_redis_cache_handle_cdn_remote_addressing() {
Erick Hitter's avatar
Erick Hitter committed
96
	// so we don't confuse the cloudflare server
Erick Hitter's avatar
Erick Hitter committed
97
	if ( isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) {
Erick Hitter's avatar
Erick Hitter committed
98 99
		$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
	}
Benjamin Adams's avatar
merged  
Benjamin Adams committed
100
}
101

102 103 104 105 106 107 108 109
/**
 * Prepare a URL for use as a cache key
 *
 * Strips secret key from URL
 *
 * @param string
 * @return string
 */
Erick Hitter's avatar
Erick Hitter committed
110
function wp_redis_cache_get_clean_url( $secret ) {
111
	$replace_keys = array( "?refresh=${secret}","&refresh=${secret}" );
112 113
	$url          = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	return str_replace( $replace_keys, '', $url );
Benjamin Adams's avatar
Benjamin Adams committed
114
}
Benjamin Adams's avatar
merged  
Benjamin Adams committed
115

116 117 118 119 120 121 122
/**
 *
 */
function wp_redis_cache_is_mobile_request() {
	return false;
}

123
/**
124 125 126 127 128
 * Establish a connection to the Redis server
 *
 * Will try the PECL module first, then fall back to PRedis
 *
 * @return object
129
 */
130
function wp_redis_cache_connect_redis() {
Erick Hitter's avatar
Erick Hitter committed
131
	// check if PECL Extension is available
Erick Hitter's avatar
Erick Hitter committed
132
	if ( class_exists( 'Redis' ) ) {
133
		if ( $GLOBALS['wp_redis_cache_config']['debug'] ) {
Erick Hitter's avatar
Erick Hitter committed
134 135
			echo "<!-- Redis PECL module found -->\n";
		}
Erick Hitter's avatar
Erick Hitter committed
136

Erick Hitter's avatar
Erick Hitter committed
137 138 139
		$redis = new Redis();

		// Sockets can be used as well. Documentation @ https://github.com/nicolasff/phpredis/#connection
140 141
		$redis->connect( $GLOBALS['wp_redis_cache_config']['redis_server'], $GLOBALS['wp_redis_cache_config']['redis_port'] );
		$redis->select( $GLOBALS['wp_redis_cache_config']['redis_db'] );
Erick Hitter's avatar
Erick Hitter committed
142
	} else { // Fallback to predis5.2.php
143
		if ( $GLOBALS['wp_redis_cache_config']['debug'] ) {
Erick Hitter's avatar
Erick Hitter committed
144 145
			echo "<!-- using predis as a backup -->\n";
		}
Erick Hitter's avatar
Erick Hitter committed
146

147
		include_once dirname( __FILE__ ) . '/wp-content/plugins/wp-redis-cache/predis5.2.php'; //we need this to use Redis inside of PHP
148
		$redis = new Predis_Client( array(
149 150 151
			'host'     => $GLOBALS['wp_redis_cache_config']['redis_server'],
			'port'     => $GLOBALS['wp_redis_cache_config']['redis_port'],
			'database' => $GLOBALS['wp_redis_cache_config']['redis_db'],
152
		) );
Erick Hitter's avatar
Erick Hitter committed
153 154
	}

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
	return $redis;
}

/**
 * BEGIN CACHING LOGIC
 */

// Set proper IP for proxied requests
wp_redis_cache_handle_cdn_remote_addressing();

// Ensure WP uses a theme (this is normally set in index.php)
if ( ! defined( 'WP_USE_THEMES' ) ) {
	define( 'WP_USE_THEMES', true );
}

try {
	// Establish connection with Redis server
	$redis = wp_redis_cache_connect_redis();

174 175 176
	// Whether we need to load WP
	$load_wp = true;

177 178 179 180
	// Relevant details on the current request
	$is_post   = (bool) 'POST' === $_SERVER['REQUEST_METHOD'];
	$logged_in = (bool) preg_match( "#(wordpress_(logged|sec)|comment_author)#", var_export( $_COOKIE, true ) );

181 182 183 184 185 186
	if ( $GLOBALS['wp_redis_cache_config']['debug'] ) {
		echo "<!-- POST request: . " . ( $is_post ? 'yes' : 'no' ) . "-->\n";
		echo "<!-- Logged in: . " . ( $logged_in ? 'yes' : 'no' ) . "-->\n";
	}

	// Refresh request, deletes cache: either manual refresh cache by adding ?refresh=secret_string after the URL or somebody posting a comment
Erick Hitter's avatar
Erick Hitter committed
187
	if ( wp_redis_cache_refresh_has_secret( $GLOBALS['wp_redis_cache_config']['secret_string'] ) || wp_redis_cache_request_has_secret( $GLOBALS['wp_redis_cache_config']['secret_string'] ) || wp_redis_cache_is_remote_page_load( $GLOBALS['wp_redis_cache_config']['current_url'], $GLOBALS['wp_redis_cache_config']['server_ip'] ) ) {
188
		if ( $GLOBALS['wp_redis_cache_config']['debug'] ) {
Erick Hitter's avatar
Erick Hitter committed
189 190
			echo "<!-- manual refresh was required -->\n";
		}
Erick Hitter's avatar
Erick Hitter committed
191

192
		$redis->del( $GLOBALS['wp_redis_cache_config']['redis_key'] );
Erick Hitter's avatar
Erick Hitter committed
193

194
		// require_once dirname( __FILE__ ) . '/wp-blog-header.php';
195
	// This page is cached, the user isn't logged in, and it isn't a POST request, so let's use the cache
196 197 198 199 200
	} elseif ( ! $is_post && ! $logged_in && $redis->exists( $GLOBALS['wp_redis_cache_config']['redis_key'] ) ) {
		if ( $GLOBALS['wp_redis_cache_config']['debug'] ) {
			echo "<!-- serving page from cache: key: " . $GLOBALS['wp_redis_cache_config']['redis_key'] . " -->\n";
		}

201 202
		// Page is served from cache, so we don't need WP
		$load_wp = false;
203 204
		$GLOBALS['wp_redis_cache_config']['cached'] = true;

205
		echo trim( $redis->get( $GLOBALS['wp_redis_cache_config']['redis_key'] ) );
Erick Hitter's avatar
Erick Hitter committed
206
	// If the cache does not exist lets display the user the normal page without cache, and then fetch a new cache page
207 208 209 210 211
	} elseif ( $_SERVER['REMOTE_ADDR'] != $GLOBALS['wp_redis_cache_config']['server_ip'] ) {
		if ( false === strstr( $GLOBALS['wp_redis_cache_config']['current_url'], 'preview=true' ) ) {
			if ( $GLOBALS['wp_redis_cache_config']['debug'] ) {
				echo "<!-- displaying page without cache -->\n";
			}
212

213 214 215 216 217 218 219
			// If user isn't logged in and this isn't a post request, render the requested page and cache if appropriate.
			if ( ! $is_post && ! $logged_in ) {
				// We load WP to generate the cached output, so no need to load again
				$load_wp = false;

				// Render page into an output buffer and display
				ob_start();
220
				require_once dirname( __FILE__ ) . '/wp-blog-header.php';
221 222 223 224 225 226 227 228
				$markup_to_cache = trim( ob_get_clean() );
				echo $markup_to_cache;

				// Cache rendered page if appropriate
				if ( ! is_404() && ! is_search() ) {
					// Is unlimited cache life requested?
					if ( isset( $GLOBALS['wp_redis_cache_config']['unlimited'] ) ) {
						$unlimited = $GLOBALS['wp_redis_cache_config']['unlimited'];
229
					} else {
230 231
						$unlimited = (bool) get_option( 'wp-redis-cache-debug', false );
						$GLOBALS['wp_redis_cache_config']['unlimited'] = $unlimited;
232 233
					}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
					// Cache the page for the chosen duration
					if ( $unlimited ) {
						$redis->set( $GLOBALS['wp_redis_cache_config']['redis_key'], $markup_to_cache );
					} else {
						if ( isset( $GLOBALS['wp_redis_cache_config']['cache_duration'] ) ) {
							$cache_duration = $GLOBALS['wp_redis_cache_config']['cache_duration'];
						} else {
							$cache_duration = (int) get_option( 'wp-redis-cache-seconds', 43200 );
							$GLOBALS['wp_redis_cache_config']['cache_duration'] = $cache_duration;
						}

						if ( ! is_numeric( $cache_duration ) ) {
							$cache_duration = $GLOBALS['wp_redis_cache_config']['cache_duration'] = 43200;
						}

						$redis->setex( $GLOBALS['wp_redis_cache_config']['redis_key'], $cache_duration, $markup_to_cache );
250
					}
Erick Hitter's avatar
Erick Hitter committed
251
				}
252
			} /*else {
253
				require_once dirname( __FILE__ ) . '/wp-blog-header.php';
254 255
			}*/
		} /*else {
256
			require_once dirname( __FILE__ ) . '/wp-blog-header.php';
257 258
		}*/
	} /*else {
259
		require_once dirname( __FILE__ ) . '/wp-blog-header.php';
260 261 262 263
	}*/

	// The current request wasn't served from cache or isn't cacheable, so we pass off to WP
	if ( $load_wp ) {
264
		require_once dirname( __FILE__ ) . '/wp-blog-header.php';
Erick Hitter's avatar
Erick Hitter committed
265
	}
Erick Hitter's avatar
Erick Hitter committed
266
} catch ( Exception $e ) {
267
	require_once dirname( __FILE__ ) . '/wp-blog-header.php';
268
	wp_redis_cache_exception_handler( $e );
Benjamin Adams's avatar
Benjamin Adams committed
269 270
}

Hendrik Klemp's avatar
Hendrik Klemp committed
271
$end  = microtime();
Erick Hitter's avatar
Erick Hitter committed
272
$time = @wp_redis_cache_get_micro_time( $end ) - @wp_redis_cache_get_micro_time( $start );
273
if ( $GLOBALS['wp_redis_cache_config']['debug'] ) {
Erick Hitter's avatar
Erick Hitter committed
274
	echo "<!-- Cache system by Benjamin Adams. Page generated in " . round($time, 5) . " seconds. -->\n";
275
	echo "<!-- Site was cached = " . $GLOBALS['wp_redis_cache_config']['cached'] . " -->\n";
276
	if ( isset( $GLOBALS['wp_redis_cache_config']['cache_duration'] ) ) {
Erick Hitter's avatar
Erick Hitter committed
277
		echo "<!-- wp-redis-cache-seconds = " . $GLOBALS['wp_redis_cache_config']['cache_duration'] . " -->\n";
Erick Hitter's avatar
Erick Hitter committed
278
	}
Erick Hitter's avatar
Erick Hitter committed
279
	echo "<!-- wp-redis-cache-ip = " . $GLOBALS['wp_redis_cache_config']['server_ip'] . "-->\n";
280 281
	if ( isset( $GLOBALS['wp_redis_cache_config']['unlimited'] ) ) {
		echo "<!-- wp-redis-cache-unlimited = " . $GLOBALS['wp_redis_cache_config']['unlimited'] . "-->\n";
Erick Hitter's avatar
Erick Hitter committed
282
	}
Erick Hitter's avatar
Erick Hitter committed
283
	echo "<!-- wp-redis-cache-debug = " . $GLOBALS['wp_redis_cache_config']['debug'] . "-->\n";
Benjamin Adams's avatar
Benjamin Adams committed
284
}