Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open pull requests and composer 2 compatibility #33

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/HtmlCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@
use craft\services\Plugins;
use craft\events\PluginEvent;
use craft\services\Elements;
use craft\services\Utilities;
use craft\web\UrlManager;
use craft\helpers\FileHelper;
use craft\helpers\UrlHelper;
use craft\events\RegisterUrlRulesEvent;
use bolden\htmlcache\services\HtmlcacheService;
use bolden\htmlcache\models\Settings;
use bolden\htmlcache\utilities\CacheUtility;


use yii\base\Event;
use craft\elements\db\ElementQuery;
Expand All @@ -35,6 +38,7 @@
use bolden\htmlcache\records\HtmlCacheElement;
use craft\elements\User;
use craft\elements\GlobalSet;
use craft\events\RegisterComponentTypesEvent;

/**
* Craft plugins are very much like little applications in and of themselves. We’ve made
Expand Down Expand Up @@ -117,7 +121,7 @@ public function init()
self::$plugin = $this;

// ignore console requests
if ($this->isInstalled && !\Craft::$app->request->getIsConsoleRequest()) {
if ($this->isInstalled && !\Craft::$app->getRequest()->getIsConsoleRequest()) {
$this->setComponents(
[
'htmlcacheService' => HtmlcacheService::class,
Expand All @@ -142,10 +146,14 @@ public function init()
if ($this->htmlcacheService->canCreateCacheFile()) {
$elementClass = get_class($event->element);
if (!in_array($elementClass, [User::class, GlobalSet::class])) {
$uri = \Craft::$app->request->getParam('p', '');
$uri = \Craft::$app->getRequest()->getPathInfo() ?: $event->element->uri;
$siteId = \Craft::$app->getSites()->getCurrentSite()->id;
$elementId = $event->element->id;


if (!$uri || strlen($uri) === 0) {
return;
}

// check if cache entry already exits otherwise create it
$cacheEntry = HtmlCacheCache::findOne(['uri' => $uri, 'siteId' => $siteId]);
if (!$cacheEntry) {
Expand Down Expand Up @@ -217,6 +225,17 @@ function (PluginEvent $event) {
}
}
);

if (Craft::$app->getRequest()->getIsCpRequest()) {
Event::on(
Utilities::class,
Utilities::EVENT_REGISTER_UTILITY_TYPES,
function(RegisterComponentTypesEvent $event) {
$event->types[] = CacheUtility::class;
}
);
}

parent::init();
}

Expand Down
35 changes: 35 additions & 0 deletions src/controllers/CacheController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace bolden\htmlcache\controllers;

use bolden\htmlcache\HtmlCache as Plugin;

use Craft;
use craft\web\Controller;
use yii\web\HttpException;
use yii\web\Response;

/**
* HtmlCache Controller
*
*
* @author Kurious Agency
* @package EmailEditor
* @since 1.0.0
*/
class CacheController extends Controller
{
public function actionClearCaches()
{
$this->requireLogin();
$this->requirePostRequest();
try {
Plugin::$plugin->htmlcacheService->clearCacheFiles();
Craft::$app->getSession()->setNotice(Craft::t('html-cache', 'Caches Cleared'));
} catch (\Throwable $th) {
Craft::$app->getSession()->setNotice(Craft::t('html-cache', 'Unable to Clear Caches'));
}
return;
}

}
1 change: 1 addition & 0 deletions src/icon-mask.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 3 additions & 1 deletion src/models/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ class Settings extends \craft\base\Model
public $optimizeContent = 0;
public $cacheDuration = 3600;
public $purgeCache = 0;
public $disablePreviewCache = 1;
public $excludedUrlPaths = [];
public $queryStringCaching = false;

public function rules() {
return [
[ ['enableGeneral', 'forceOn', 'optimizeContent', 'purgeCache' ], 'boolean' ],
[ ['enableGeneral', 'forceOn', 'optimizeContent', 'purgeCache', 'disablePreviewCache' ], 'boolean' ],
[ ['cacheDuration' ], 'integer' ],
];
}
Expand Down
File renamed without changes.
40 changes: 30 additions & 10 deletions src/services/HtmlcacheService.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class HtmlcacheService extends Component
*/
public function __construct()
{
$this->uri = \Craft::$app->request->getParam('p', '');
$this->uri = \Craft::$app->getRequest()->getPathInfo() ?: '__HOME__';
$this->siteId = \Craft::$app->getSites()->getCurrentSite()->id;
$this->settings = HtmlCache::getInstance()->getSettings();
}
Expand Down Expand Up @@ -77,6 +77,16 @@ public function checkForCacheFile()
*/
public function canCreateCacheFile()
{
// Skip if it's a preview url
if ($this->settings->disablePreviewCache && Craft::$app->getRequest()->getIsPreview()) {
return false;
}

// Skip if it has a query string and plugin is set to ignore urls with query strings
if (!$this->settings->queryStringCaching && Craft::$app->getRequest()->getQueryString()) {
return false;
}

// Skip if we're running in devMode and not in force mode
if (\Craft::$app->config->general->devMode === true && $this->settings->forceOn == false) {
return false;
Expand All @@ -93,25 +103,25 @@ public function canCreateCacheFile()
}

// Skip if it's a CP Request
if (\Craft::$app->request->getIsCpRequest()) {
if (\Craft::$app->getRequest()->getIsCpRequest()) {
return false;
}

// Skip if it's an action Request
if (\Craft::$app->request->getIsActionRequest()) {
if (\Craft::$app->getRequest()->getIsActionRequest()) {
return false;
}

// Skip if it's a preview request
if (\Craft::$app->request->getIsLivePreview()) {
if (\Craft::$app->getRequest()->getIsLivePreview()) {
return false;
}
// Skip if it's a post request
if (!\Craft::$app->request->getIsGet()) {
if (!\Craft::$app->getRequest()->getIsGet()) {
return false;
}
// Skip if it's an ajax request
if (\Craft::$app->request->getIsAjax()) {
if (\Craft::$app->getRequest()->getIsAjax()) {
return false;
}
// Skip if route from element api
Expand Down Expand Up @@ -157,7 +167,7 @@ private function isElementApiRoute()
private function isPathExcluded()
{
// determine currently requested URL path and the multi-site ID
$requestedPath = \Craft::$app->request->getFullPath();
$requestedPath = \Craft::$app->getRequest()->getFullPath();
$requestedSiteId = \Craft::$app->getSites()->getCurrentSite()->id;

// compare with excluded paths and sites from the settings
Expand Down Expand Up @@ -291,13 +301,23 @@ private function loadCache($file)
} elseif (!empty($this->settings->cacheDuration)) {
$settings = ['cacheDuration' => $this->settings->cacheDuration];
} else {
$settings = ['cacheDuration' => 3600];
$settings = ['cacheDuration' => 0];
}
if (time() - ($fmt = filemtime($file)) >= $settings['cacheDuration']) {
if ($settings['cacheDuration'] > 0 && time() - ($fmt = filemtime($file)) >= $settings['cacheDuration']) {
unlink($file);
return false;
}
\Craft::$app->response->data = file_get_contents($file);

$page = file_get_contents($file);

if (Craft::$app->config->general->devMode) {
$filename = array_slice(explode('/',$file),-1)[0];
$uri = Craft::$app->getRequest()->getFullUri();
$date = date("F d Y H:i:s",filemtime($file));
$page .= "<!-- HTMLCache Debugging. -->\n<!-- This is a cached version of '/{$uri}' -->\n<!--'{$filename}' created {$date} -->";
}

\Craft::$app->response->data = $page;
return true;
}

Expand Down
20 changes: 19 additions & 1 deletion src/templates/_settings.twig
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,24 @@
errors: settings.getErrors('honeypotField')
}) }}

{{ forms.lightswitchField({
label: "Enable Query String Caching" | t,
id: 'queryStringCaching',
name: 'queryStringCaching',
instructions: "Enable the caching of a urls with query strings" | t,
errors: settings.getErrors('queryStringCaching'),
on: settings.queryStringCaching
}) }}

{{ forms.lightswitchField({
label: "Disable Preview Cache" | t,
id: 'disablePreviewCache',
name: 'disablePreviewCache',
instructions: "Disable the caching of a preview url, this prevents a draft from being publicly accessible" | t,
errors: settings.getErrors('disablePreviewCache'),
on: settings.disablePreviewCache
}) }}

{{ forms.lightswitchField({
label: "Purge Cache now?" | t,
id: 'purgeCache',
Expand Down Expand Up @@ -72,7 +90,7 @@
cols: [
{
heading: 'Excluded paths' | t,
info: 'Enter precise URL paths or regular expressions without the <span class="code">siteURL</span> part as they are returned by <span class="code">\Craft::$app->request->getFullPath()</span>, like "any/page" insteadof "https://example.com/site-specific/path/any/page".' | t,
info: 'Enter precise URL paths or regular expressions without the <span class="code">siteURL</span> part as they are returned by <span class="code">\Craft::$app->getRequest()->getFullPath()</span>, like "any/page" insteadof "https://example.com/site-specific/path/any/page".' | t,
type: 'singleline',
placeholder: 'path/to/excluded/page OR regex like path/.*/excluded/.*',
},
Expand Down
12 changes: 12 additions & 0 deletions src/templates/_utility.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{% import "_includes/forms" as forms %}

<h1>{{ "Clear Caches"|t('html-cache') }}</h1>

<form id="db-backup" class="utility" method="post" accept-charset="UTF-8">
{{ actionInput('html-cache/cache/clear-caches') }}
{{ csrfInput() }}
<div class="buttons">
<input type="submit" class="btn submit" value="{{ "Clear Cache"|t('html-cache') }}" />
<div class="utility-status"></div>
</div>
</form>
52 changes: 52 additions & 0 deletions src/utilities/CacheUtility.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace bolden\htmlcache\utilities;

use Craft;
use craft\base\Utility;
use bolden\htmlcache\HtmlCache;

class CacheUtility extends Utility
{
// Static
// =========================================================================

/**
* @inheritdoc
*/
public static function displayName(): string
{
return Craft::t('html-cache', 'HTML Cache');
}

/**
* @inheritdoc
*/
public static function id(): string
{
return 'html-cache';
}

/**
* @inheritdoc
*/
public static function iconPath()
{
$iconPath = Craft::getAlias('@vendor/bolden/htmlcache/src/icon-mask.svg');

if (!is_string($iconPath)) {
return null;
}

return $iconPath;
}

/**
* @inheritdoc
*/
public static function contentHtml(): string
{
return Craft::$app->getView()->renderTemplate('html-cache/_utility');
}
}