Fetching contributors…
Cannot retrieve contributors at this time
819 lines (754 sloc) 27.4 KB
<?php
/*
Plugin Name: CF Asset Optimizer
Plugin URI: http://crowdfavorite.com
Description: Used to serve optimized and concatenated JS and CSS files enqueued on a page.
Author: Crowd Favorite
Version: 1.2
Author URI: http://crowdfavorite.com
*/
if (is_admin()) {
include_once dirname(__file__).'/admin.php';
}
class CFAssetOptimizerScripts {
protected static $_CFAO_CACHE_DIR;
protected static $_CFAO_CACHE_URL;
protected static $_LOCKFILE = '';
public static function getCacheDir() {
if (empty(self::$_CFAO_CACHE_DIR)) {
$cache_dir = WP_CONTENT_DIR . '/cfao-cache/' . $_SERVER['HTTP_HOST'] . '/js/';
self::$_CFAO_CACHE_DIR = trailingslashit(apply_filters('cfao_script_cache_dir', $cache_dir));
}
return self::$_CFAO_CACHE_DIR;
}
public static function getCacheUrl() {
if (empty(self::$_CFAO_CACHE_URL)) {
$cache_url = WP_CONTENT_URL . '/cfao-cache/' . $_SERVER['HTTP_HOST'] . '/js/';
self::$_CFAO_CACHE_URL = trailingslashit(apply_filters('cfao_script_cache_url', $cache_url));
}
return self::$_CFAO_CACHE_URL;
}
public static function getLockFile() {
if (empty(self::$_LOCKFILE)) {
$lockfile = '.cfaojslock';
self::$_LOCKFILE = apply_filters('cfao_script_lockfile', $lockfile);
}
return self::$_LOCKFILE;
}
public static function enqueueConcatenatedFile($footer = false) {
global $wp_scripts;
if (!is_object($wp_scripts)) {
return;
}
$wp_scripts->all_deps($wp_scripts->queue);
$included_scripts = array();
$url = self::getConcatenatedScriptUrl($wp_scripts, $footer, $included_scripts);
if ($url) {
// We have a concatenated file matching this. Output each script's localizations,
// dequeue the script, then enqueue our concatenated file.
foreach ($wp_scripts->to_do as $handle) {
if (isset($included_scripts[$handle])) {
// We need to output the localization and deregister this script.
if (!empty($wp_scripts->registered[$handle]->extra['data'])) {
?>
<script type="text/javascript">
<?php echo $wp_scripts->registered[$handle]->extra['data']; ?>
</script>
<?php
}
$wp_scripts->done[] = $handle;
}
}
$script_name = 'cfao-script';
if ($footer) {
$script_name .= '-footer';
}
else {
$script_name .= '-header';
}
wp_enqueue_script($script_name, $url);
$wp_scripts->to_do = array();
}
else if (!get_option('cfao_using_cache') && !empty($included_scripts)) {
$directory = self::getCacheDir();
if (file_exists($directory.self::getLockFile())) {
// We're currently building. Don't overload the system.
$included_scripts = array();
return false;
}
// Not a cached environment, trigger rebuild asynchronously.
$build_args = array(
'key' => get_option('cfao_security_key'),
'referer' => $_SERVER['HTTP_HOST'] . '/' . $_SERVER['REQUEST_URI'],
'scripts' => $included_scripts,
);
$response = wp_remote_post(
admin_url('admin-ajax.php?action=concat-build-js'),
array(
'body' => $build_args,
'redirection' => 0,
'timeout' => 1,
)
);
}
}
public static function onWPPrintScripts() {
self::enqueueConcatenatedFile(false);
}
public static function onWPPrintFooterScripts() {
self::enqueueConcatenatedFile(true);
}
public static function buildConcatenatedScriptFile() {
$directory = trailingslashit(self::getCacheDir());
$security_key = get_option('cfao_security_key');
if ($security_key != $_POST['key']) {
exit();
}
if (!(file_exists($directory) && is_dir($directory))) {
// We need to attempt to make the directory.
if (!mkdir($directory, 0775, true)) {
error_log('Could not create directory: ' . $directory);
exit();
}
}
$lockfile = self::getLockFile();
if (file_exists($directory.$lockfile)) {
// We're currently running a build. Throttle it to avoid DDOS Attacks.
exit();
}
if (empty($_POST['scripts'])) {
exit('No scripts object received');
}
$scripts = $_POST['scripts'];
$lock = @fopen($directory.$lockfile, 'x');
if (!$lock) {
error_log('Could not create lockfile: ' . $directory.$lockfile);
exit();
}
fwrite($lock, time());
fclose($lock);
$site_scripts = get_option('cfao_scripts', array());
if (!is_array($site_scripts)) {
$site_scripts = array();
}
$included_scripts = array();
$script_file_header =
"/**\n" .
" * Included Files\n" .
" *\n";
$script_file_src = '';
$script_blocks = array();
$current_block = 0;
$my_domain = strtolower(untrailingslashit(preg_replace('#^http(s)?:#', '', site_url())));
$scripts_changed = false;
foreach ($scripts as $handle => $src) {
// We're going to be blind on this end, and let the front-end handle things except when a request can't happen.
if (empty($src)) {
$script_file_header .= ' * ' . $handle . " as empty script handle.\n";
$included_scripts[$handle] = $src;
continue;
}
else {
$request_url = $src;
if (strpos($request_url, '//') === 0) {
$request_url = 'http:'.$request_url;
}
if (!preg_match('|^https?://|', $request_url) && true) {
$request_url = 'http://'.$_SERVER['SERVER_NAME'].$request_url;
}
}
// This script is enabled and has not changed from the last approved version.
// Request the file
$request_url = $src;
if (strpos($request_url, '//') === 0) {
$request_url = 'http:'.$request_url;
}
if ( !preg_match('|^https?://|', $request_url) && ! ( $scripts_obj->content_url && 0 === strpos($request_url, $scripts_obj->content_url) ) ) {
$request_url = home_url($request_url);
}
$script_request = wp_remote_get(
$request_url
);
// Handle the response
if (is_wp_error($script_request)) {
$site_scripts[$handle]['enabled'] = false;
$site_scripts[$handle]['disable_reason'] = 'WP Error: ' . $script_request->get_error_message();
$scripts_changed = true;
}
else {
if ($script_request['response']['code'] < 200 || $script_request['response']['code'] >= 400) {
// There was an error requesting the file
$site_scripts[$handle]['enabled'] = false;
$site_scripts[$handle]['disable_reason'] = 'HTTP Error ' . $script_request['response']['code'] . ' requested as ' . $request_url . ' - ' . $script_request['response']['message'];
$scripts_changed = true;
}
else {
// We had a valid script to add to the list.
// Check to see if it can be concatenated.
if (empty($site_scripts[$handle]['minify_script'])) {
// This cannot be minified. It will need to be kept as is.
if (!empty($script_blocks[$current_block])) {
// We need to increment the script block first.
++$current_block;
}
$script_blocks[$current_block] = array(
'minify' => false,
'src' => $script_request['body'].";\n",
);
}
else {
// This can be minified. Allow it to be sent in a bundled minify request.
if (
!empty($script_blocks[$current_block])
&& !($script_blocks[$current_block]['minify'])
) {
// Increment current block first.
++$current_block;
}
if (empty($script_blocks[$current_block])) {
$script_blocks[$current_block] = array(
'minify' => true,
'src' => ''
);
}
$script_blocks[$current_block]['src'] .= $script_request['body'].";\n";
}
$included_scripts[$handle] = $src;
$script_file_header .= ' * ' . $handle . ' as ' . $request_url . "\n";
}
}
}
$script_file_header .= " **/\n";
if ($scripts_changed) {
// We'll be out of sync at this point, so just update and let it try again later.
update_option('cfao_scripts', $site_scripts);
}
else if (!empty($included_scripts)) {
// We have a file to write
$filename = self::_getConcatenatedScriptsFilename($included_scripts);
$file = @fopen($directory.$filename, 'w');
if (!$file === false) {
// We have a valid file pointer.
// Minify the file as dictated by user settings with Google Closure Compiler
$minify_level = get_option('cfao_minify_js_level', '');
$compiler_levels = array(
'whitespace' => 'WHITESPACE_ONLY',
'simple' => 'SIMPLE_OPTIMIZATIONS',
'advanced' => 'ADVANCED_OPTIMIZATIONS'
);
if (isset($compiler_levels[$minify_level])) {
foreach ($script_blocks as $block) {
$src = $block['src'];
if ($block['minify']) {
$args = array(
'js_code' => mb_convert_encoding($src, 'UTF-8'),
'compilation_level' => $compiler_levels[$minify_level],
'output_format' => 'text',
'output_info' => 'compiled_code'
);
$response = wp_remote_post(
'http://closure-compiler.appspot.com/compile',
array(
'body' => $args,
'timeout' => 60
)
);
if (
!empty($response)
&& !is_wp_error($response)
&& !empty($response['headers'])
&& !empty($response['response'])
&& $response['response']['code'] == 200
&& !empty($response['body'])
&& !(preg_match('/^Error\([\d]+\)/', $response['body']))
) {
$src = $response['body'];
}
}
$script_file_src .= $src;
}
}
else {
foreach ($script_blocks as $block) {
$script_file_src .= $block['src'];
}
}
$script_file_header = apply_filters('cfao_script_file_header', $script_file_header);
fwrite($file, $script_file_header.$script_file_src);
fclose($file);
}
else {
error_log('Could not create file: ' . $directory.$filename);
}
}
// Remove the lockfile.
unlink($directory.$lockfile);
exit();
}
private static function _getConcatenatedScriptsFilename($included_scripts) {
// Custom name is pairing of handles and URL with MD5.
$parts = array();
foreach ($included_scripts as $key => $val) {
$parts[] = "$key $val";
}
return md5(implode(',', $parts)) . '.js';
}
public static function getConcatenatedScriptUrl($wp_scripts, $footer, &$included_scripts) {
$directory = trailingslashit(self::getCacheDir());
$dir_url = trailingslashit(esc_url(self::getCacheUrl()));
$site_scripts = get_option('cfao_scripts', array());
if (!is_array($site_scripts)) {
$site_scripts = array();
}
$included_scripts = array();
$unknown_scripts = array();
$registered = $wp_scripts->registered;
$my_domain = strtolower(untrailingslashit(preg_replace('#^http(s)?:#', '', site_url())));
$update_scripts = false;
foreach ($wp_scripts->to_do as $handle) {
if ($wp_scripts->groups[$handle] == 1 && !$footer) {
// These are scripts to put together in the footer, not in the header.
continue;
}
if (!empty($site_scripts[$handle]) && !$site_scripts[$handle]['enabled']) {
// Script is explicitly disabled
continue;
}
$compare_src = $registered[$handle]->src;
$no_protocol = preg_replace('#^http(s)?:#', '', $compare_src);
if (strpos($no_protocol, $my_domain) === 0) {
// This is a local script. Use the $no_protocol version for enqueuing and management.
$compare_src = $no_protocol;
}
if (empty($site_scripts[$handle])) {
// Note that we have an unknown script, and thus should actually still make the back-end request.
// No longer true. We should do all registration from the front end now.
$update_scripts = true;
$src = $registered[$handle]->src;
if (empty($src) || $src === 1) {
$src = 'Placeholder script registration';
}
$site_scripts[$handle] = array(
'src' => $src,
'ver' => $registered[$handle]->ver,
'enabled' => true,
);
}
$can_include = true;
foreach ($wp_scripts->registered[$handle]->deps as $dep) {
// Ensure that it is not dependent on any disabled scripts
if (empty($site_scripts[$dep]) || !$site_scripts[$dep]['enabled']) {
// We've hit a disabled parent script.
$can_include = false;
$site_scripts[$handle]['enabled'] = false;
$site_scripts[$handle]['disable_reason'] = 'Dependent on disabled script: ' . $dep;
$update_scripts = true;
break;
}
}
if ($can_include) {
$included_scripts[$handle] = $registered[$handle]->src;
if (empty($registered[$handle]->src) || $registered[$handle]->src === 1) {
$included_scripts[$handle] = '';
}
if (!empty($included_scripts[$handle])) {
if ( !preg_match('|^(https?:)?//|', $registered[$handle]->src) && ! ( $wp_scripts->content_url && 0 === strpos($registered[$handle]->src, $wp_scripts->content_url) ) ) {
$included_scripts[$handle] = $wp_scripts->base_url . $included_scripts[$handle];
}
if (!empty($registered[$handle]->ver)) {
$included_scripts[$handle] = add_query_arg('ver', $registered[$handle]->ver, $included_scripts[$handle]);
}
$included_scripts[$handle] = esc_url(apply_filters('script_loader_src', $included_scripts[$handle], $handle));
}
}
}
if ($update_scripts) {
update_option('cfao_scripts', $site_scripts);
}
if (empty($included_scripts) && empty($unknown_scripts)) {
// All scripts are disabled on this site. Go no further.
return;
}
$filename = self::_getConcatenatedScriptsFilename($included_scripts);
if (file_exists($directory.$filename)) {
$url = apply_filters('cfao_script_file_url', $dir_url.$filename, $directory.$filename, $filename);
return esc_url($url);
}
else if (get_option('cfao_using_cache', false)) {
if (file_exists($directory.self::getLockFile())) {
// We're currently building. Don't overload the system.
$included_scripts = $unknown_scripts = array();
return false;
}
// We're in a cached environmentent, so run a synchronous request to build the concatenated
// file so that it gets cached properly without needing to do multiple invalidations.
$build_args = array(
'key' => get_option('cfao_security_key'),
'referer' => $_SERVER['HTTP_HOST'] . '/' . $_SERVER['REQUEST_URI'],
'scripts' => $included_scripts,
);
$response = wp_remote_post(
admin_url('admin-ajax.php?action=concat-build-js'),
array(
'body' => $build_args,
'redirection' => 0,
)
);
if (file_exists($directory.$filename)) {
$version = filemtime($directory.$filename);
$url = apply_filters('cfao_script_file_url', $dir_url.$filename, $directory.$filename, $filename);
return esc_url($url);
}
}
return false;
}
}
add_action('wp_ajax_concat-build-js', 'CFAssetOptimizerScripts::buildConcatenatedScriptFile');
add_action('wp_ajax_nopriv_concat-build-js', 'CFAssetOptimizerScripts::buildConcatenatedScriptFile');
if (!is_admin()) {
add_action('wp_print_scripts', 'CFAssetOptimizerScripts::onWPPrintScripts', 100);
add_action('wp_print_footer_scripts', 'CFAssetOptimizerScripts::onWPPrintFooterScripts', 9);
}
class CFAssetOptimizerStyles {
protected static $_CFAO_CACHE_DIR;
protected static $_CFAO_CACHE_URL;
protected static $_LOCKFILE = '';
public static function getCacheDir() {
if (empty(self::$_CFAO_CACHE_DIR)) {
$cache_dir = WP_CONTENT_DIR . '/cfao-cache/' . $_SERVER['HTTP_HOST'] . '/css/';
self::$_CFAO_CACHE_DIR = trailingslashit(apply_filters('cfao_style_cache_dir', $cache_dir));
}
return self::$_CFAO_CACHE_DIR;
}
public static function getCacheUrl() {
if (empty(self::$_CFAO_CACHE_URL)) {
$cache_url = WP_CONTENT_URL . '/cfao-cache/' . $_SERVER['HTTP_HOST'] . '/css/';
self::$_CFAO_CACHE_URL = trailingslashit(apply_filters('cfao_style_cache_url', $cache_url));
}
return self::$_CFAO_CACHE_URL;
}
public static function getLockFile() {
if (empty(self::$_LOCKFILE)) {
$lockfile = '.cfaocsslock';
self::$_LOCKFILE = apply_filters('cfao_css_lockfile', $lockfile);
}
return self::$_LOCKFILE;
}
public static function onWPPrintStyles() {
global $wp_styles;
if (!is_object($wp_styles)) {
return;
}
$wp_styles->all_deps($wp_styles->queue);
$included_styles = array();
$url = self::getConcatenatedStyleUrl($wp_styles, $included_styles);
if ($url) {
// We have a concatenated file matching this. Output each style's localizations,
// dequeue the style, then enqueue our concatenated file.
foreach ($wp_styles->to_do as $handle) {
if (in_array($handle, array_keys($included_styles))) {
// We need to output the localization and deregister this style.
$wp_styles->done[] = $handle;
}
}
$my_deps = array();
foreach ($included_styles as $handle => $src) {
$inc_deps = $wp_styles->registered[$handle]->deps;
$new_deps = array_diff($inc_deps, $included_styles, $my_deps);
foreach ($new_deps as $dep) {
$my_deps[] = $dep;
}
}
wp_enqueue_style('cfao-style', $url, $my_deps);
$wp_styles->to_do = array();
}
else if (!get_option('cfao_using_cache') && (!empty($included_styles) || !empty($unknown_styles)) ) {
if (file_exists(trailingslashit(self::getCacheDir()).self::getLockFile())) {
// Currently building. Don't overload the system.
return;
}
// We don't have the file built yet. Fire off an asynchronous request to build it
// and serve the styles normally.
$build_args = array(
'styles' => $included_styles,
'key' => get_option('cfao_security_key')
);
$response = wp_remote_post(
admin_url('admin-ajax.php?action=concat-build-css'),
array(
'body' => $build_args,
'timeout' => 1,
'redirection' => 0,
)
);
}
}
public static function buildConcatenatedStyleFile() {
$directory = trailingslashit(self::getCacheDir());
$security_key = get_option('cfao_security_key');
if ($security_key != $_POST['key']) {
exit();
}
if (!(file_exists($directory) && is_dir($directory))) {
// We need to attempt to make the directory.
if (!mkdir($directory, 0775, true)) {
error_log('Could not create directory: ' . $directory);
exit();
}
}
$lockfile = self::getLockFile();
if (file_exists($directory.$lockfile)) {
// We're currently running a build. Throttle it to avoid DDOS Attacks.
exit();
}
if (empty($_POST['styles'])) {
error_log('No styles received');
exit();
}
$lock = @fopen($directory.$lockfile, 'x');
if (!$lock) {
error_log('Could not create lockfile: ' . $directory.$lockfile);
exit();
}
fwrite($lock, time());
fclose($lock);
$site_styles = get_option('cfao_styles', array());
if (!is_array($site_styles)) {
$site_styles = array();
}
$included_styles = $_POST['styles'];
$style_file_header =
"/**\n" .
" * Included Files\n" .
" *\n";
$style_file_src = '';
$my_domain = strtolower(untrailingslashit(preg_replace('#^http(s)?:#', '', site_url())));
$styles_updated = false;
foreach ($included_styles as $handle => $url) {
if (empty($url) || $url === 1) {
$style_file_header .= ' * ' . $handle . " as empty script handle.\n";
continue;
}
else {
$request_url = $url;
if (strpos($request_url, '//') === 0) {
$request_url = 'http:'.$request_url;
}
if (!preg_match('|^https?://|', $request_url) && true) {
$request_url = 'http://'.$_SERVER['SERVER_NAME'].$request_url;
}
}
$style_request = wp_remote_get(
$request_url
);
// Handle the response
if (is_wp_error($style_request)) {
$site_styles[$handle]['enabled'] = false;
$site_styles[$handle]['disable_reason'] = 'WP Error: ' . $style_request->get_error_message();
$styles_updated = true;
}
else if ($style_request['response']['code'] < 200 || $style_request['response']['code'] >= 400) {
// There was an error requesting the file
$site_styles[$handle]['enabled'] = false;
$site_styles[$handle]['disable_reason'] = 'HTTP Error ' . $style_request['response']['code'] . ' - ' . $style_request['response']['message'];
$styles_updated = true;
}
else {
// We had a valid style to add to the list.
$style_file_header .= ' * ' . $handle . ' as ' . $url . "\n";
$src = $style_request['body'] . "\n";
// Convert relative URLs to absolute URLs.
// Get URL parts for this script.
$parts = array();
preg_match('#(https?://[^/]*)([^?]*/)([^?]*)(\?.*)?#', $request_url, $parts);
$parts[1] = apply_filters('cfao_styles_relative_domain', $parts[1]);
// Update paths that are based on web root.
if (count($parts) > 1) {
$regex = '~
url\s*\( # url( with optional internal whitespace
\s* # optional whitespace
( # begin group 1
["\']? # an optional single or double quote
) # end option group 1
\s* # optional whitespace
( # begin option group 2
/ # url starts with / for web root url
[^[:space:]] # one single non-space character
.+? # one or more (non-greedy) any character
) # end option group 2
\s* # optional whitespace
\1 # match opening delimiter
\s* # optional whitespace
\) # closing )
~x';
$src = preg_replace($regex,'url('.$parts[1].'$2)', $src);
}
// Update paths based on style location
if (count($parts) > 2) {
$regex = '~
url\s*\( # url( with optional internal whitespace
\s* # optional whitespace
( # begin group 1 (optional delimiter)
["\']? # an optional single or double quote
) # end group 1
\s* # optional whitespace
(?! # negative lookahead assertion: skip if...
(?: # noncapturing group (not needed with lookaheads)
[\'"] # keep optional quote out of url match
| # or
// # url starts with //
| # or
https?:// # url starts with http:// or https://
| # or
data: # url starts with data:
) # end noncapturing group
) # end negative lookahead
( # begin group 2 (relative URL)
/? # optional root /
[^[:space:]] # one single nonspace character
.+? # one or more (non-greedy) any character
) # end group 2
\s* # optional whitespace
\1 # match opening delimiter
\s* # optional whitespace
\) # closing )
~x';
$src = preg_replace($regex, 'url('.$parts[1].$parts[2].'$2)', $src);
}
$style_file_src .= $src . "\n";
}
}
$style_file_header .= " **/\n";
if ($styles_updated) {
// We're going to be out of sync, so don't serve up a file, just update the options.
update_option('cfao_styles', $site_styles);
}
else {
// We have a file to write
$filename = self::_getConcatenatedStylesFilename($included_styles);
$file = @fopen($directory.$filename, 'w');
if (!$file === false) {
// We have a valid file pointer.
// Minify the contents using Minify library
set_include_path(dirname(__file__).'/minify/min/lib');
include 'Minify/CSS.php';
$style_file_src = Minify_CSS::minify($style_file_src, array('preserveComments' => false));
restore_include_path();
$style_file_header = apply_filters('cfao_style_file_header', $style_file_header);
// Write the file and close it.
fwrite($file, $style_file_header.$style_file_src);
fclose($file);
}
else {
error_log('Could not create file: ' . $directory.$filename);
}
}
unlink($directory.$lockfile);
exit();
}
private static function _getConcatenatedStylesFilename($included_styles) {
// Custom name is pairing of handles and URL with MD5.
$parts = array();
foreach ($included_styles as $key => $val) {
$parts[] = "$key $val";
}
return md5(implode(',', $included_styles)) . '.css';
}
public static function getConcatenatedStyleUrl($wp_styles, &$included_styles) {
$directory = self::getCacheDir();;
$dir_url = esc_url(self::getCacheUrl());
$site_styles = get_option('cfao_styles', array());
if (!is_array($site_styles)) {
$site_styles = array();
}
$included_styles = array();
$registered = $wp_styles->registered;
$my_domain = strtolower(untrailingslashit(preg_replace('#^http(s)?:#', '', site_url())));
$update_styles = false;
foreach ($wp_styles->to_do as $handle) {
if (empty($registered[$handle]->src)) {
// This is a convenience wrapper enqueued style. Ignore it.
continue;
}
if (empty($site_styles[$handle])) {
// Let's register it now.
$update_styles = true;
$site_styles[$handle] = array(
'src' => $registered[$handle]->src,
'ver' => $registered[$handle]->ver,
'enabled' => true,
);
}
else if (!($site_styles[$handle]['enabled'])) {
// We shouldn't include this style, it's not enabled.
continue;
}
$can_include = true;
$style_update = false;
foreach ($wp_styles->registered[$handle]->deps as $dep) {
// Ensure that it is not dependent on any disabled styles
if (empty($site_styles[$dep]) || !$site_styles[$dep]['enabled']) {
// We've hit a disabled parent style.
$can_include = false;
$site_styles[$handle]['enabled'] = false;
$site_styles[$handle]['disable_reason'] = 'Dependent on disabled style: ' . $dep;
$update_styles = true;
break;
}
}
if ($can_include) {
$included_styles[$handle] = $registered[$handle]->src;
if ( !preg_match('|^(https?:)?//|', $registered[$handle]->src) && ! ( $wp_styles->content_url && 0 === strpos($registered[$handle]->src, $wp_styles->content_url) ) ) {
$included_scripts[$handle] = $wp_styles->base_url . $included_styles[$handle];
}
if (!empty($registered[$handle]->ver)) {
$included_styles[$handle] = add_query_arg('ver', $registered[$handle]->ver, $included_styles[$handle]);
}
$included_styles[$handle] = esc_url(apply_filters('script_loader_src', $included_styles[$handle], $handle));
}
}
if ($update_styles) {
update_option('cfao_styles', $site_styles);
}
if (empty($included_styles) && empty($unknown_styles)) {
return false;
}
$filename = self::_getConcatenatedStylesFilename($included_styles);
if (file_exists($directory.$filename)) {
$version = filemtime($directory.$filename);
$url = apply_filters('cfao_style_file_url', $dir_url.$filename, $directory.$filename, $filename);
return esc_url($url);
}
else if (get_option('cfao_using_cache', false)) {
if (file_exists($directory.self::getLockFile())) {
$included_styles = array();
return false;
}
// We're in a cached environment, so run a synchronous request to build the concatenated
// file so that it gets cached properly without needing to do multiple invalidations.
$build_args = array(
'styles' => $included_styles,
'key' => get_option('cfao_security_key')
);
$response = wp_remote_post(
admin_url('admin-ajax.php?action=concat-build-css'),
array(
'body' => $build_args,
'redirection' => 0,
)
);
if (file_exists($directory.$filename)) {
$version = filemtime($directory.$filename);
$url = apply_filters('cfao_style_file_url', $dir_url.$filename, $directory.$filename, $filename);
return esc_url($url);
}
}
return false;
}
}
add_action('wp_ajax_concat-build-css', 'CFAssetOptimizerStyles::buildConcatenatedStyleFile');
add_action('wp_ajax_nopriv_concat-build-css', 'CFAssetOptimizerStyles::buildConcatenatedStyleFile');
if (!is_admin()) {
add_action('wp_print_styles', 'CFAssetOptimizerStyles::onWPPrintStyles', 100);
}
?>