Skip to content

Instantly share code, notes, and snippets.

@snrbrnjna
Last active November 24, 2020 18:02
Show Gist options
  • Save snrbrnjna/17ad4fcec0349c366cf1ce23f587fcac to your computer and use it in GitHub Desktop.
Save snrbrnjna/17ad4fcec0349c366cf1ce23f587fcac to your computer and use it in GitHub Desktop.
Config for Cachify Plugin in HDD mode delivering .br (brotli) or .gzip versions of the cached files
# BEGIN CACHIFY
<IfModule mod_rewrite.c>
# ENGINE ON
RewriteEngine on
RewriteBase /
# set hostname directory
RewriteRule .* - [E=CACHIFY_HOST:https-%{HTTP_HOST}]
# set Doument root - `DCOUMENT_ROOT` is set to ~/html - the virtual host config on uberspace
RewriteRule .* - [E=MY_DOCUMENT_ROOT:/var/www/virtual/user/html]
# set subdirectory
# sometimes %{REQUEST_URI} might be an empty string, so /$ won't match
RewriteCond %{REQUEST_URI} /$
RewriteRule .* - [E=CACHIFY_DIR:%{REQUEST_URI}]
RewriteCond %{REQUEST_URI} ^$
RewriteRule .* - [E=CACHIFY_DIR:/]
# gzip or brotli
RewriteRule .* - [E=CACHIFY_SUFFIX:]
<IfModule mod_mime.c>
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteRule .* - [E=CACHIFY_SUFFIX:.gz]
AddType text/html .gz
AddEncoding gzip .gz
RewriteCond %{HTTP:Accept-Encoding} br
RewriteCond %{ENV:MY_DOCUMENT_ROOT}/app/cache/cachify/%{ENV:CACHIFY_HOST}%{ENV:CACHIFY_DIR}index.html.br -f
RewriteRule .* - [E=CACHIFY_SUFFIX:.br]
AddType text/html .br
AddEncoding br .br
</IfModule>
# Main Rules
RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{QUERY_STRING} ^$
RewriteCond %{REQUEST_URI} !^/(wp-admin|wp/wp-admin|app/cache)/.*
RewriteCond %{HTTP_COOKIE} !(wp-postpass|wordpress_logged_in|comment_author)_
RewriteCond %{ENV:MY_DOCUMENT_ROOT}/app/cache/cachify/%{ENV:CACHIFY_HOST}%{ENV:CACHIFY_DIR}index.html -f
RewriteRule ^(.*) /app/cache/cachify/%{ENV:CACHIFY_HOST}%{ENV:CACHIFY_DIR}index.html%{ENV:CACHIFY_SUFFIX} [L]
</IfModule>
# END CACHIFY
<?php
namespace Brnjna\Sage;
/**
* update all cached files with wp-cron every night
*/
/*
* Get recursively Direntries
*/
function getDirContents($dir, &$results = array()){
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
$results[] = $path;
} else if($value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
function getIndexPaths($dirContents) {
return array_filter($dirContents, function($v) {
return preg_match('/index\.html$/', $v);
});
}
function curlUrls($urls) {
$exitCodes = array();
foreach ($urls as $key => $url) {
$cmd = 'curl -L '. $url . ' > /dev/null 2>&1 &';
exec($cmd, $output, $exit);
$exitCodes[$url] = $exit;
}
return $exitCodes;
}
/**
* get all cached urls, flush cache and curl every previously cached page again.
*/
function recache() {
$cacheDir = \CACHIFY_CACHE_DIR;
if (substr($cacheDir, -1) != '/') { $cacheDir = $cacheDir . '/'; }
$dirContents = getDirContents($cacheDir);
$indexFilePaths = getIndexPaths($dirContents);
$urls = preg_replace(array('/'.preg_replace('/\//', '\/', $cacheDir).'/', '/index\.html$/'), '', $indexFilePaths);
$urls = preg_replace('/^https-/', '', $urls);
if (has_action('cachify_flush_cache')) {
do_action('cachify_flush_cache');
// DEBUG
// debug_log('cachify cache flushed');
}
$exitCodes = curlUrls($urls);
// DEBUG
// debug_log($exitCodes);
}
add_action('recache_cachify', __NAMESPACE__.'\\recache');
// Register wp-cron for a daily recache at 2 am in the night.
if (defined('\CACHIFY_CACHE_DIR') && !empty(\CACHIFY_CACHE_DIR)) {
if (!wp_next_scheduled('recache_cachify')) {
$start_cron = strtotime('today') + 3600 *2;
wp_schedule_event(time(), 'daily', 'recache_cachify');
}
} else {
if (wp_next_scheduled('recache_cachify')) {
wp_clear_scheduled_hook('recache_cachify');
}
}
#!/bin/bash
# cron this and the delivered files from your cache shrink to less than 5% of its original size (gzip makes ~10%)
CACHIFY="/var/www/virtual/user/html/app/cache/cachify"
for x in `find $CACHIFY -type f -name '*.html'`; do
if [ ! -f $x.br ]; then
~/bin/brotli $x --output=$x.br
chmod 644 $x.br
fi;
done
/**
* function to reload the minicart and its cart count badge with an ajax call against the wp ajax hook from above
*/
function reloadMiniCart() {
var ajaxUrl = getAjaxUrl();
if (ajaxUrl) {
var data = {
'action': 'patcheko_theme_update_mini_cart'
};
$('.menu-item-cart .badge').html(0);
$.post(
ajaxUrl, // The AJAX URL
data, // Send our PHP function
function (response) {
if (response) {
$('.woocommerce.mini-cart').html(response.miniCart);
$('.menu-item-cart .badge').html(response.cartCount);
}
},
'json'
);
} else {
console.warn("CAUTION: Reloading of the minicart impossible!");
}
}
function getAjaxUrl() {
if (typeof update_minicart_params !== 'undefined' && update_minicart_params.ajaxurl)
return update_minicart_params.ajaxurl;
}
<?php
namespace Brnjna\Sage;
/**
* Register wp ajax response rendering the minicart html and the cart item count into a json response.
*/
/*
* Response to ajax call `patcheko_theme_update_mini_cart`: update mini-cart on cached pages
*/
function patcheko_theme_update_mini_cart() {
ob_start();
woocommerce_mini_cart();
$miniCart = ob_get_clean();
$cartCount = WC()->cart->get_cart_contents_count();
$json = array(
'miniCart' => trim($miniCart),
'cartCount' => $cartCount
);
wp_send_json($json);
}
add_filter( 'wp_ajax_nopriv_patcheko_theme_update_mini_cart', __NAMESPACE__ . '\\patcheko_theme_update_mini_cart' );
add_filter( 'wp_ajax_patcheko_theme_update_mini_cart', __NAMESPACE__ . '\\patcheko_theme_update_mini_cart' );
function render_update_minicart_localized_script() {
wp_enqueue_script('patcheko/update_minicart', '', ['jquery'], null, true);
wp_localize_script('patcheko/update_minicart', 'update_minicart_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
));
}
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\render_update_minicart_localized_script');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment