Plugin Directory

Changeset 2893345


Ignore:
Timestamp:
04/04/2023 07:11:27 AM (3 years ago)
Author:
Lugat
Message:

Added cache duration and GC. Optimized some code parts.

Location:
jinx-fast-cache/trunk
Files:
1 added
2 deleted
10 edited

Legend:

Unmodified
Added
Removed
  • jinx-fast-cache/trunk/assets/css/admin.css

    r2676361 r2893345  
    11.column-jinx-fast-cache {
    2   width: 2rem;
     2  width: 1.5rem;
    33};
  • jinx-fast-cache/trunk/assets/js/jinx-fast-cache.js

    r2676361 r2893345  
    1 document.querySelectorAll('[id^=jinx-fast-cache-inject-]').forEach(function(element) {
     1document.querySelectorAll('span.jinx-fast-cache-inject[data-id][data-path]').forEach(element => {
    22 
    33  fetch(jinx_fast_cache.ajax_url+'?'+new URLSearchParams({
    44    action: 'jinx-fast-cache-inject',
    55    path: element.dataset.path,
    6     id: element.dataset.id,
     6    id: element.dataset.id
    77  }).toString(), {
    8     method: 'GET',
    9   }).then(function(response) {
     8    method: 'GET'
     9  }).then(response => {
    1010    return response.text();
    11   }).then(function(html) {
     11  }).then(html => {
    1212    element.innerHTML = html;
    1313  });
  • jinx-fast-cache/trunk/index.php

    r2892826 r2893345  
    55   * Plugin URI: https://wordpress.org/plugins/jixn-fast-cache/
    66   * Description: Blazing fast full page cache.
    7    * Version: 0.6.2
     7   * Version: 0.7.0
    88   * Author: SquareFlower Websolutions (Lukas Rydygel) <hallo@squareflower.de>
    99   * Author URI: http://squareflower.de
     
    1212   */
    1313
    14   require_once 'src/Helper.php';
    15   require_once 'src/Url.php';
    16   require_once 'src/Plugin.php';
    17   require_once 'src/Queue.php';
    18   require_once 'src/Service.php';
    19   require_once 'src/Admin.php';
    20   require_once 'src/Front.php';
     14  require_once __DIR__.'/src/Helper.php';
     15  require_once __DIR__.'/src/Url.php';
     16  require_once __DIR__.'/src/Plugin.php';
     17  require_once __DIR__.'/src/Queue.php';
     18  require_once __DIR__.'/src/Service.php';
     19  require_once __DIR__.'/src/Admin.php';
     20  require_once __DIR__.'/src/Front.php';
     21  require_once __DIR__.'/src/GarbageCollector.php';
    2122 
     23  require_once ABSPATH.'wp-admin/includes/upgrade.php';
    2224  require_once ABSPATH.'wp-admin/includes/class-wp-filesystem-base.php';
    2325  require_once ABSPATH.'wp-admin/includes/class-wp-filesystem-direct.php';
     
    3032  add_action('init', ['Jinx\FastCache\Front', 'init']);
    3133  add_action('init', ['Jinx\FastCache\Queue', 'init']);
     34  add_action('init', ['Jinx\FastCache\GarbageCollector', 'init']);
  • jinx-fast-cache/trunk/readme.txt

    r2892826 r2893345  
    11=== Jinx Fast-Cache ===
    2 Contributors: Lugat
    3 Tags: cache, fullpage, pagecache, filecache, rewrite, htaccess
     2Contributors: Lukas Rydygel
     3Tags: cache, html, files, fullpage, pagecache, filecache, rewrite, htaccess
    44Requires at least: 5.0
    55Tested up to: 6.2.0
     
    99License URI: http://www.gnu.org/licenses/gpl-2.0.html
    1010
    11 Jinx Fast-Cache is a blazing fast full page cache for WordPress.
     11Jinx Fast-Cache is a blazing fast full page cache for WordPress, written for developers.
     12The goal was to create a caching plugin without the overhead in the WordPress backend. It will work with URLs, not PIDs.
    1213
    1314== Description ==
     
    22232. Upload `jinx-fast-cache` to the `/wp-content/plugins/` directory
    23243. Activate the plugin through the 'Plugins' menu in WordPress
     254. Optional: You may need to modify the rewrite rules
    2426
    2527== Usage ==
    2628
    27 After activating the plugin, it will modify your htaccess file. If this is not possible, make sure to enter the rules by yourself:
     29After activating the plugin, it will modify your .htaccess file. If this is not possible, make sure to enter the rules by yourself:
    2830
    2931    # BEGIN Jinx Fast-Cache
     
    4951By default all posts will be automatically warmed after they have been saved and flushed after they have been deleted or put on draft.
    5052
    51 The warm process will create a queue which will be handled in a scheduled task (cron). When warming up a single post, it will skip the queue.
     53The warm process will create a queue, which will be handled in a scheduled task (cron). When warming up a single post, it will skip the queue.
    5254
    5355The plugin will automatically flush and warm the cache after an update has been completed.
     
    5557== Developers ==
    5658
    57 === Filters ===
     59## Filters
    5860
    5961Jinx Fast-Cache is made for developers. So far no admin panel is available, but you may modify a lot of it's behaviors using filters.
    6062
    61 - **jinx_fast_cache**: Return true (default) or false to control, if a URL should be cache or not.
     63- **jinx_fast_cache_active**: Control if an URL should be cached (default true) or not.
    6264- **jinx_fast_cache_post_types**: Control the post types which should be cached. By default all post types which are "publicly_queryable" and "page" will be cached.
    6365- **jinx_fast_cache_posts**: Filter the posts which should be cached.
     
    6567- **jinx_fast_cache_terms**: Filter the terms which should be cached.
    6668- **jinx_fast_cache_output**: Use this to modify the HTML content written to your cache file.
    67 - **jinx_fast_cache_minify**: Return true (default) or false if you want the output to be minified.
     69- **jinx_fast_cache_minify**: Control if the output should be minified (default true) or not.
    6870- **jinx_fast_cache_flush**: Control which URLs should be flushed. This may be used to flush related URLs eg. your front page.
    6971- **jinx_fast_cache_warm**: Control which URLs should be warmed. This may be used to warm related URLs eg. your front page.
    70 - **jinx_fast_cache_interval**: Change the interval of the cron task (default 60).
     72- **jinx_fast_cache_queue_interval**: Change the interval of the queues cron task (default 60) to warm URLs.
    7173- **jinx_fast_cache_queue_size**: Change the number of URLs which should be handled durring a cron task (default 10). When setting it to <= 0, all URLs will be handled. This may cause a huge load when you have a lot of URLs.
    72 - **jinx_fast_cache_ignore_404**: Change if 404 error should not be cached (default true). A lot of 404 errors will create a lot of cache files on your server.
    73 - **jinx_fast_cache_query_params**: Change if and which query params will be accepted. You may pass '__return_empty_array' to allow no query params.
    74 - **jinx_fast_cache_refresh_on_upgrade**: Change if the cache should be refreshed on upgrade (default true).
     74- **jinx_fast_cache_gc_interval**: Change the interval of the GCs cron task (default 60) to flush invalid URLs.
     75- **jinx_fast_cache_ignore_404**: Control if 404 errors should be cached (default false) or not. Not that a lot of 404 errors will also create a lot of cache files on your server.
     76- **jinx_fast_cache_query_params**: Control if and which query params will be accepted. You may pass '__return_empty_array' to allow no query params at all.
     77- **jinx_fast_cache_refresh_on_upgrade**: Control if the cache should be refreshed on upgrade (default true).
     78- **jinx_fast_cache_duration**: Change the caches duration (default null). The cache of URLs without a duration will always be valid. You may use a numeric value eg. 3600 or something like '12 hours' or '1 week' etc.
    7579
    76 === Injections ===
     80## Injections
    7781
    78 Jinx Fast-Cache also provides the feature to inject dynamic content parts. If you eg. want to print the users name on the page, you may inject it via ajax.
    79 
    80 Note that the first parameter is the placeholder content. This will prevent any problems when calling the action without the plugin beeing active. You may load the template normally or print a note like "loading ...".
     82Jinx Fast-Cache also provides the feature to inject dynamic content into your pages. If you eg. want to print the users name on the page, you may inject it via ajax.
     83You may also use a placeholder to let your users know, that the content will be loading eg. "loading ...".
    8184
    8285Inject a template:
    8386
    8487    do_action('jinx_fast_cache_inject_template', 'user');
     88    do_action('jinx_fast_cache_inject_template', 'user', 'loading ...');
    8589
    86 This has the same result as:
     90This has the same effect as:
    8791
    8892    do_action('jinx_fast_cache_inject', 'get_template_part', ['user']);
     93    do_action('jinx_fast_cache_inject', 'get_template_part', ['user'], 'loading ...');
    8994
    90 You may call every public function of PHP, your theme or plugin:
     95You may call every public function of PHP, your theme or any plugin:
    9196
    9297    do_action('jinx_fast_cache_inject', 'date', ['Y']);
     
    95100    do_action('jinx_fast_cache_inject', ['namespace\MyClass', 'myMethod'], ['param1', 'param2']);
    96101
     102The first parameter is the function call, the second parameter is an array or arguments passed to this function and the third parameter is the placeholder.
     103
    97104Inside the editor, you may also use shortcodes to inject content.
    98105
    99106    [jinx_fast_cache_inject]My dynamic content or other shortcodes can be used here[/jinx_fast_cache_inject]
     107    [jinx_fast_cache_inject placeholder="loading..."]My dynamic content or other shortcodes can be used here[/jinx_fast_cache_inject]
    100108
     109Every shortcode or block between "jinx_fast_cache_inject" will be parsed and injected via ajax. Note that this may cause problems when working with JS events.
    101110
    102 === Tags ===
     111## Tags
    103112
    104 Even there are some filters to build a relation between URLs, tags are a easier way to do this. You may connect multiple pages with tags, so if one URL gets flushed, it will also flush the URLs with the same tag.
     113Even there are some filters to build a relation between URLs, tags are an easier way to do this.
     114You may connect multiple URLs with tags, so if one URL gets flushed, it will also flush URLs with the same tag.
    105115
    106116Tags can be used inside the editor by using the shortcode:
     
    110120Or you can use it inside your templates by calling the action:
    111121
    112     do_action('jinx_fast_cache_tags', ['foo', 'bar']);
     122    do_action('jinx_fast_cache', ['tags' => 'foo,bar']);
     123    do_action('jinx_fast_cache', ['tags' => ['foo', 'bar']]);
    113124
    114125A usecase for tags might be to connect single posts with your page for posts. So if a single post will be flushed, the page for posts and all other posts will also be flushed.
    115126
    116 == Roadmap ==
     127You may also add multiple tags by calling the shortcode or action multiple times. This will work very well when using blocks or other shortcodes.
    117128
    118 - [x] Release it
     129## Cache duration
     130
     131As you have seen already, you may set a cache duration globally by using the filter 'jinx_fast_cache_duration'.
     132However, if there is a specific URL eg. the front page, you may want to change the duration.
     133
     134You may use a shortcode like this:
     135
     136    [jinx_fast_cache duration="3600"]
     137    [jinx_fast_cache duration="12 hours"]
     138
     139Or you can use it inside your templates by calling the action:
     140
     141    do_action('jinx_fast_cache', ['duration' => 3600]);
     142
     143## Hits
     144
     145Be aware that you can set tags and the cache duration in just one call.
     146
     147    [jinx_fast_cache duration="3600" tags="foo,bar"]
     148
     149Or you can use it inside your templates by calling the action:
     150
     151    do_action('jinx_fast_cache', ['duration' => 3600, 'tags' => 'foo,bar']);
     152    do_action('jinx_fast_cache', ['duration' => 3600, 'tags' => ['foo', 'bar']]);
     153
     154Note that tags will accept a string or an array.
     155
     156## Roadmap
     157
     158- [x] Release the plugin
    119159- [x] Add HTML minification for output
    120160- [x] Allow injection of dynamic rendered templates using ajax requests
     
    125165- [x] Add multisite support
    126166- [x] Flush and warm after update complete
    127 - [x] Ignore 404
     167- [x] Add possibility to ignore 404
    128168- [x] Allow query params to be excluded or totally ignored
    129 - [ ] Provide cache timeout
     169- [x] Provide cache duration
    130170- [ ] Provide admin panel to change options
    131171- [x] Add tags to flush related pages
    132172- [x] Add shortcode for injects
     173
     174== Upgrade Notice ==
     175
     176When updating, by default the plugin will flush the cache. Anyway, it may be a good idea to deactivate and activate the plugin again, if there are any problems after an upgrade.
  • jinx-fast-cache/trunk/src/Admin.php

    r2892826 r2893345  
    2323      });
    2424     
    25       add_action('upgrader_process_complete', function($object, $options) {
     25      add_action('upgrader_process_complete', function() {
    2626       
    2727        if (apply_filters('jinx_fast_cache_refresh_on_upgrade', true)) {
     
    2929        }
    3030       
    31       }, 10, 2);
     31      }, PHP_INT_MAX);
    3232     
    3333      add_action('admin_bar_menu', [__CLASS__, 'addAdminBar'], 100);
  • jinx-fast-cache/trunk/src/Front.php

    r2892806 r2893345  
    1212    public static $tags = [];
    1313   
     14    // Duration of cache
     15    public static $duration = null;
     16   
    1417    /**
    1518     * Init the front
     
    2023      add_action('template_redirect', [__CLASS__, 'capture'], PHP_INT_MAX);
    2124     
    22       add_filter('jinx_fast_cache', function($cache) {
     25      add_filter('jinx_fast_cache_active', function($cache) {
    2326
    2427        if ($cache === true) {
     
    8891     
    8992      add_shortcode('jinx_fast_cache_inject', function($attr, $content) {
    90         return self::inject('do_shortcode', [$content]);
    91       });
    92      
    93       add_action('jinx_fast_cache_tags', function($tags) {
    94         self::$tags = array_merge(self::$tags, $tags);
     93        return self::inject('do_shortcode', [$content], $attr['placeholder'] ?? null);
     94      });
     95     
     96      add_action('jinx_fast_cache', function($attr) {
     97       
     98        $attr = shortcode_atts([
     99          'tags' => [],
     100          'duration' => null
     101        ], $attr);
     102                 
     103        if (is_string($attr['tags'])) {
     104          $attr['tags'] = explode(',', $attr['tags']);
     105          $attr['tags'] = array_map('trim', $attr['tags']);
     106        }
     107       
     108        self::$tags = array_merge(self::$tags, array_filter($attr['tags']));
     109        self::$duration = $attr['duration'];
     110       
    95111      });
    96112     
    97113      add_shortcode('jinx_fast_cache', function($attr, $content) {
    98                
    99         if (isset($attr['tags'])) {
    100          
    101           $tags = explode(',', $attr['tags']);
    102           $tags = array_map('trim', $tags);
    103           $tags = array_filter($tags);
    104          
    105           do_action('jinx_fast_cache_tags', $tags);
    106          
    107         }
    108        
    109         return null;
    110                
     114        do_action('jinx_fast_cache', $attr);
     115        return null;         
    111116      });
    112117     
     
    180185      $id = count(self::$injections);
    181186
    182       return '<span id="jinx-fast-cache-inject-'.$id.'" data-id="'.$id.'" data-path="'.$path.'">'.$placeholder.'</span>';
     187      return '<span class="jinx-fast-cache-inject" data-id="'.$id.'" data-path="'.$path.'">'.$placeholder.'</span>';
    183188
    184189    }
     
    193198                 
    194199      // check if the request should be cached
    195       $cache = apply_filters('jinx_fast_cache', true);
    196       if ($cache === true) {
     200      if (apply_filters('jinx_fast_cache_active', true)) {
    197201       
    198202        // start output buffer
     
    215219           
    216220            self::insertTags();
     221            self::setExpiry();
    217222           
    218223            return $html;
     
    226231    }
    227232   
     233    /**
     234     * Insert tags for URL into the DB table
     235     *
     236     * @global type $wpdb
     237     */
    228238    protected static function insertTags()
    229239    {
    230240     
    231       global $wp, $wpdb;
    232      
    233       $url = $_SERVER['HTTP_HOST'].'/'.$wp->request;
     241      global $wpdb;
     242     
     243      $url = Helper::getUrl();
    234244     
    235245      $tags = array_unique(self::$tags);
    236      
    237246      foreach ($tags as $tag) {
    238247       
     
    246255    }
    247256   
     257    /**
     258     * Set the URLs cache expiry date
     259     *
     260     * @global \Jinx\FastCache\type $wpdb
     261     */
     262    protected static function setExpiry()
     263    {
     264     
     265      global $wpdb;
     266     
     267      $duration = apply_filters('jinx_fast_cache_duration', self::$duration);
     268      if (isset($duration)) {
     269       
     270        $url = Helper::getUrl();
     271             
     272        $expire = new \DateTime('now');
     273
     274        if (is_numeric($duration)) {
     275          $duration .= ' seconds';
     276        }
     277               
     278        $expire->modify("+ {$duration}");
     279       
     280        $wpdb->insert(Helper::getTable('expiry'), [
     281          'url' => $url,
     282          'expire' => $expire->getTimestamp()
     283        ]);
     284       
     285      }
     286     
     287    }
     288   
    248289  }
  • jinx-fast-cache/trunk/src/Helper.php

    r2892806 r2893345  
    110110    public static function getCachePath(bool $relative = false) : string
    111111    {
    112      
    113       global $wp;
    114      
    115       $paths = [$_SERVER['HTTP_HOST'], $wp->request];
     112           
     113      $paths = [self::getUrl()];
    116114     
    117115      parse_str($_SERVER['QUERY_STRING'], $queryParams);
     
    179177    }
    180178   
     179    public static function getUrl() : string
     180    {
     181     
     182      global $wp;
     183     
     184      return $_SERVER['HTTP_HOST'].'/'.$wp->request;
     185     
     186    }
     187   
    181188  }
  • jinx-fast-cache/trunk/src/Plugin.php

    r2892806 r2893345  
    129129    protected static function createTables()
    130130    {
    131      
    132       require_once(ABSPATH.'wp-admin/includes/upgrade.php');
    133            
     131                 
    134132      $table = Helper::getTable('tags');
    135133     
     
    141139      \maybe_create_table($table, $sql);
    142140     
     141      $table = Helper::getTable('expiry');
     142     
     143      $sql = "CREATE TABLE {$table} (
     144        `url` VARCHAR(255) NOT NULL,
     145        `expire` INT(11) NOT NULL,
     146        PRIMARY KEY (`url`))";
     147     
     148      \maybe_create_table($table, $sql);
     149     
    143150    }
    144151   
  • jinx-fast-cache/trunk/src/Queue.php

    r2676361 r2893345  
    88    protected static $option = 'jinx_fast_cache_queue';
    99   
    10     protected static $recurrence = 'jinx-fast-cache';
     10    protected static $recurrence = 'jinx-fast-cache-queue';
    1111   
    1212    /**
     
    1818      add_filter('cron_schedules', function($schedules) {
    1919
    20         $seconds = apply_filters('jinx_fast_cache_interval', 60);
    21 
    2220        $schedules[self::$recurrence] = [
    23           'interval' => $seconds,
    24           'display' => Plugin::t('Jinx Fast-Cache')
     21          'interval' => apply_filters('jinx_fast_cache_queue_interval', 60),
     22          'display' => Plugin::t('Jinx Fast-Cache - Queue')
    2523        ];
    2624
  • jinx-fast-cache/trunk/src/Service.php

    r2892807 r2893345  
    133133      global $wpdb;
    134134     
    135       $table = Helper::getTable('tags');
     135      $tagsTable = Helper::getTable('tags');
     136      $expiryTable = Helper::getTable('expiry');
    136137     
    137138      if (empty($urls)) {
    138         $wpdb->query("TRUNCATE TABLE {$table}");
     139       
     140        $wpdb->query("TRUNCATE TABLE {$tagsTable}");
     141        $wpdb->query("TRUNCATE TABLE {$expiryTable}");
     142       
    139143      } else {
    140144       
    141145        foreach ($urls as $url) {
     146         
     147          $url = Url::normalize($url);
    142148                   
    143           $wpdb->delete($table, [
    144             'url' => Url::normalize($url)
     149          $wpdb->delete($tagsTable, [
     150            'url' => $url
     151          ]);
     152         
     153          $wpdb->delete($expiryTable, [
     154            'url' => $url
    145155          ]);
    146156         
Note: See TracChangeset for help on using the changeset viewer.