Skip to content

Instantly share code, notes, and snippets.

@gphg
Last active July 15, 2020 06:38
Show Gist options
  • Save gphg/1e59295aabcbc1a207239d5192424608 to your computer and use it in GitHub Desktop.
Save gphg/1e59295aabcbc1a207239d5192424608 to your computer and use it in GitHub Desktop.
A simple Pico CMS plugin for HTTP caching.
<?php
/**
* Pico HTTP page caching plugin
*
* Web server (well known are Apache2 and Nginx) come with
* mod_cache and mod_expires specialize for static files.
* Last-Modified HTTP header is part of it.
*
* This plugins gives more control on Pico http page caching.
*
* @author Hexat
* @license DBAD
* @version 0.0.2
*/
class HttpPageCaching extends AbstractPicoPlugin
{
const API_VERSION = 2;
public function onMetaParsed(array &$pageData)
{
// Should it be cached?
$doCache = isset($pageData['httpCaching']) ? $pageData['httpCaching'] : null;
if ($doCache !== true || (is_null($doCache) && ($this->getPluginConfig('global', false) !== true))) {
return;
}
// Get lastModification time
if (!isset($pageData['last_modified'])) {
if (isset($pageData['meta']['last_modified'])) {
$pageData['last_modified'] = $pageData['meta']['last_modified'];
} elseif (isset($pageData['httpCaching']['last_modified'])) {
$pageData['last_modified'] = $pageData['httpCaching']['last_modified'];
} if (is_file($this->getRequestFile())) {
$pageData['last_modified'] = filemtime($this->getRequestFile());
}
}
// Read client-side HTTP headers for cache
if (!is_null($pageData['last_modified']) && isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $pageData['last_modified'] <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
header('HTTP/1.1 304 Not Modified');
exit;
}
// Set headers
$pramaCache = (isset($pageData['httpCaching']['pragma'])) ? $pageData['httpCaching']['pragma'] : 'public';
header('Pragma: '. $pramaCache);
if (isset($pageData['httpCaching']['expiration'])) {
$maxAge = $pageData['httpCaching']['expiration'] - $_SERVER['REQUEST_TIME'];
header('Cache-Control: max-age='.$maxAge.', public');
header('Expires: '.gmdate('D, d M Y H:i:s', $pageData['httpCaching']['expiration']).' GMT');
}
if (isset($pageData['last_modified']) && !is_null($pageData['last_modified'])) {
header('Last-modified: '.gmdate('D, d M Y H:i:s', $pageData['last_modified']).' GMT');
}
}
}
@gphg
Copy link
Author

gphg commented Jul 15, 2020

Usage:

Cache individual page

# file: content/yourpage.md

# If it isn't defined, then it returns `null` which means disabled. Set true to cache.
httpCaching: true

Cache page globally by default

# file: config/config.yml

# Applies http cache on page with `httpCaching: null`.
HttpPageCaching:
  global: true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment