This commit is contained in:
2026-07-02 15:54:39 -06:00
commit 9883323161
17470 changed files with 4470592 additions and 0 deletions
@@ -0,0 +1,25 @@
# Pressable Cache Management — Developer Notes
## GitHub Auto-Updates
This plugin uses [YahnisElsts/plugin-update-checker v5.6](https://github.com/YahnisElsts/plugin-update-checker)
to deliver automatic updates directly from GitHub to WordPress sites running the plugin.
The library is **already bundled** at `includes/plugin-update-checker/` — no Composer or manual steps needed.
Only the files required for GitHub plugin updates are included (32 files). Excluded: DebugBar UI,
Theme update support, BitBucket/GitLab APIs.
---
## How to release an update
1. Bump `Version:` in `pressable-cache-management.php` — e.g. `5.2.4`
2. Update the `readme.txt` changelog
3. Commit and push to `main`
4. In GitHub → **Releases → Draft a new release**
5. Tag: `v5.2.4` (with the `v` prefix, matching the version number)
6. Attach the plugin `.zip` as a release asset
7. Publish
WordPress sites detect the new version within ~12 hours and show the standard
update notice. Clicking it installs exactly like a wordpress.org plugin.
@@ -0,0 +1,90 @@
<?php // Pressable Cache Management - Admin Menu
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
// add sub-level administrative menu
function pressable_cache_management_add_sublevel_menu()
{
/*
add_submenu_page(
'options-general.php',
string $parent_slug,
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
callable $function = ''
);
*/
add_submenu_page('admin.php', '', 'Pressable Cache Management', 'manage_options', 'pressable_cache_management', 'pressable_cache_management_display_settings_page');
}
add_action('admin_menu', 'pressable_cache_management_add_sublevel_menu');
// add top-level administrative menu
function pressable_cache_management_add_toplevel_menu()
{
/*
add_menu_page(
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
callable $function = '',
string $icon_url = '',
int $position = null
)
*/
//Check if branding Pressable branding is enabled or disabled
$remove_pressable_branding_tab_options = false;
$remove_pressable_branding_tab_options = get_option('remove_pressable_branding_tab_options');
if ($remove_pressable_branding_tab_options && 'disable' == $remove_pressable_branding_tab_options['branding_on_off_radio_button'] )
{
add_menu_page(esc_html__('Cache Management Settings', 'pressable_cache_management') , esc_html__('Cache Control', 'pressable_cache_management') , 'manage_options', 'pressable_cache_management', 'pressable_cache_management_display_settings_page',
plugin_dir_url(__FILE__) . '/assets/img/cache_control.png', 2);
} else {
add_menu_page(esc_html__('Pressable Cache Management Settings', 'pressable_cache_management') , esc_html__('Pressable CM', 'pressable_cache_management') , 'manage_options', 'pressable_cache_management', 'pressable_cache_management_display_settings_page',
plugin_dir_url(__FILE__) . '/assets/img/pressable-icon-primary.svg', 2);
}
}
add_action('admin_menu', 'pressable_cache_management_add_toplevel_menu');
//Display admin notices for top level menu
function plugin_admin_notice()
{
//get the current screen
$screen = get_current_screen();
//return if not plugin settings page
if ($screen->id !== 'toplevel_page_pressable_cache_management') return;
// Settings saved notice is handled by settings-page.php (pcm_branded_settings_saved_notice)
// which outputs a single branded card. This block intentionally left empty.
}
add_action('admin_notices', 'plugin_admin_notice');
Binary file not shown.

After

Width:  |  Height:  |  Size: 551 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 652 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72.31 72.31"><defs><style>.cls-1{fill:#fff;}</style></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><g id="pressable-icon-primary-reverse"><polygon class="cls-1" points="0 0 0 0.03 0.03 0 0 0"/><path class="cls-1" d="M37,15.8H26.25V35.57H37c8.57,0,10.63-1.78,10.63-9.29V25.06C47.59,17.58,45.53,15.8,37,15.8Z"/><path class="cls-1" d="M0,0,0,0V72.31H46.34l26-26V0ZM54.15,26.28c0,11.71-4.42,15-17.19,15H26.25V60.41a1.69,1.69,0,0,1-1.72,1.86c-1.5,0-4.7-.42-4.7-1.28V11.93c0-1.56.78-1.86,1.78-1.86H37c13,0,17.19,3.56,17.19,15Z"/></g></g></g></svg>

After

Width:  |  Height:  |  Size: 628 B

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="12pt" height="12pt" viewBox="0 0 12 12" version="1.1">
<g id="surface1">
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 0 0 L 0 0.0078125 L 0.0078125 0 Z M 0 0 "/>
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 6.140625 2.621094 L 4.355469 2.621094 L 4.355469 5.902344 L 6.140625 5.902344 C 7.5625 5.902344 7.902344 5.605469 7.902344 4.363281 L 7.902344 4.160156 C 7.898438 2.917969 7.554688 2.621094 6.140625 2.621094 Z M 6.140625 2.621094 "/>
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 0 0 L 0 12 L 7.691406 12 L 12.003906 7.683594 L 12.003906 0 Z M 8.984375 4.363281 C 8.984375 6.304688 8.253906 6.847656 6.136719 6.847656 L 4.355469 6.847656 L 4.355469 10.027344 C 4.363281 10.105469 4.339844 10.183594 4.285156 10.246094 C 4.226562 10.304688 4.152344 10.335938 4.074219 10.332031 C 3.824219 10.332031 3.289062 10.261719 3.289062 10.121094 L 3.289062 1.980469 C 3.289062 1.71875 3.417969 1.667969 3.585938 1.667969 L 6.140625 1.667969 C 8.296875 1.667969 8.996094 2.261719 8.996094 4.160156 Z M 8.984375 4.363281 "/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_2" data-name="Layer 2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 376.99 72.21">
<defs>
<style>
.cls-1 {
fill: #020124;
}
.cls-1, .cls-2 {
stroke-width: 0px;
}
.cls-2 {
fill: #dd3a03;
}
</style>
</defs>
<g id="Layer_1-2" data-name="Layer 1">
<g id="pressable-logo-v8">
<g>
<path class="cls-2" d="M40.07,24.08c-1.2-.94-3.05-1.4-5.54-1.4h-4.18v12.1h4.18c2.35,0,4.16-.46,5.44-1.37,1.27-.91,1.91-2.45,1.91-4.61s-.6-3.78-1.8-4.72Z"/>
<path class="cls-2" d="M68.69,0H3.52C1.58,0,0,1.58,0,3.52v65.18c0,1.94,1.58,3.52,3.52,3.52h37.89l30.81-30.81V3.52c0-1.94-1.58-3.52-3.52-3.52ZM49.03,40.64c-3.14,2.81-7.93,4.21-14.36,4.21h-4.32v13.82c0,.56-.45,1.01-1.01,1.01h-9.86c-.56,0-1.01-.45-1.01-1.01V13.53c0-.56.45-1.01,1.01-1.01h15.12c6.77,0,11.65,1.39,14.65,4.18,3,2.79,4.5,6.82,4.5,12.1s-1.57,9.04-4.72,11.84Z"/>
</g>
<g>
<path class="cls-1" d="M96.48,59.69c-.62,0-.94-.31-.94-.94V13.46c0-.62.31-.94.94-.94h14.26c6.53,0,11.28,1.34,14.26,4.03,2.98,2.69,4.46,6.62,4.46,11.81s-1.55,8.86-4.64,11.59c-3.1,2.74-7.76,4.1-14,4.1h-4.97v14.69c0,.62-.31.94-.94.94h-8.42ZM105.84,35.35h4.82c2.83,0,4.96-.54,6.37-1.62,1.42-1.08,2.12-2.84,2.12-5.29s-.7-4.37-2.09-5.47c-1.39-1.1-3.53-1.66-6.41-1.66h-4.82v14.04Z"/>
<path class="cls-1" d="M134.57,59.69c-.62,0-.94-.31-.94-.94v-25.63c0-1.49-.04-2.89-.11-4.21-.07-1.32-.18-2.6-.32-3.85-.1-.67.22-1.01.94-1.01h7.13c.53,0,.86.26,1.01.79.19.82.33,1.75.43,2.81.1,1.06.17,2.04.22,2.95l.72,4.39v23.76c0,.62-.31.94-.94.94h-8.14ZM142.92,38.88l-.58-8.35c.96-1.39,2.06-2.64,3.31-3.74,1.25-1.1,2.51-1.98,3.78-2.63,1.27-.65,2.46-.97,3.56-.97.77,0,1.39.1,1.87.29.48.14.74.48.79,1.01,0,1.25-.01,2.62-.04,4.1-.03,1.49-.11,2.88-.25,4.18-.1.72-.46,1.01-1.08.86-.29-.09-.65-.17-1.08-.22-.43-.05-.84-.07-1.22-.07-1.01,0-2.04.22-3.1.65-1.06.43-2.1,1.04-3.13,1.84-1.03.79-1.98,1.81-2.84,3.06Z"/>
<path class="cls-1" d="M174.38,60.55c-5.57,0-9.68-1.19-12.35-3.56s-4-5.89-4-10.55v-8.28c0-4.9,1.33-8.62,4-11.16,2.66-2.54,6.73-3.82,12.2-3.82s9.35,1.22,12.06,3.67,4.07,6.05,4.07,10.8v5.62c0,.62-.31.94-.94.94h-21.46v2.16c0,2.21.49,3.85,1.48,4.93.98,1.08,2.6,1.62,4.86,1.62,1.73,0,3.1-.28,4.1-.83s1.51-1.38,1.51-2.48c0-.62.31-.94.94-.94h7.85c.58,0,.89.31.94.94.1,3.65-1.13,6.38-3.67,8.21-2.54,1.83-6.41,2.74-11.59,2.74ZM167.98,38.16h12.6v-.36c0-2.4-.5-4.15-1.51-5.26-1.01-1.1-2.57-1.66-4.68-1.66-2.26,0-3.89.56-4.9,1.69-1.01,1.13-1.51,2.89-1.51,5.29v.29Z"/>
<path class="cls-1" d="M207.65,60.55c-5.04,0-8.7-.94-10.98-2.81-2.28-1.87-3.3-4.8-3.06-8.78.05-.58.36-.86.94-.86h7.63c.58,0,.86.29.86.86,0,1.49.37,2.59,1.12,3.31.74.72,1.91,1.08,3.49,1.08,1.68,0,2.93-.26,3.74-.79.82-.53,1.22-1.34,1.22-2.45,0-.86-.29-1.57-.86-2.12-.58-.55-1.54-1.12-2.88-1.69l-8.28-3.53c-2.4-1.01-4.13-2.24-5.18-3.71-1.06-1.46-1.58-3.37-1.58-5.72,0-3.41,1.12-5.95,3.35-7.63,2.23-1.68,5.7-2.52,10.4-2.52s8.44.88,10.76,2.63c2.33,1.75,3.49,4.36,3.49,7.81,0,.62-.31.94-.94.94h-7.56c-.62,0-.94-.38-.94-1.15,0-1.01-.37-1.76-1.12-2.27-.75-.5-1.84-.76-3.28-.76s-2.5.24-3.17.72c-.67.48-1.01,1.22-1.01,2.23,0,.72.24,1.3.72,1.73.48.43,1.39.94,2.74,1.51l8.21,3.46c2.5,1.01,4.31,2.26,5.44,3.74,1.13,1.49,1.69,3.46,1.69,5.9,0,3.6-1.27,6.31-3.82,8.14-2.54,1.83-6.26,2.74-11.16,2.74Z"/>
<path class="cls-1" d="M239.83,60.55c-5.04,0-8.7-.94-10.98-2.81-2.28-1.87-3.3-4.8-3.06-8.78.05-.58.36-.86.94-.86h7.63c.58,0,.86.29.86.86,0,1.49.37,2.59,1.12,3.31.74.72,1.91,1.08,3.49,1.08,1.68,0,2.93-.26,3.74-.79.82-.53,1.22-1.34,1.22-2.45,0-.86-.29-1.57-.86-2.12-.58-.55-1.54-1.12-2.88-1.69l-8.28-3.53c-2.4-1.01-4.13-2.24-5.18-3.71-1.06-1.46-1.58-3.37-1.58-5.72,0-3.41,1.12-5.95,3.35-7.63,2.23-1.68,5.7-2.52,10.4-2.52s8.44.88,10.76,2.63c2.33,1.75,3.49,4.36,3.49,7.81,0,.62-.31.94-.94.94h-7.56c-.62,0-.94-.38-.94-1.15,0-1.01-.37-1.76-1.12-2.27-.75-.5-1.84-.76-3.28-.76s-2.5.24-3.17.72c-.67.48-1.01,1.22-1.01,2.23,0,.72.24,1.3.72,1.73.48.43,1.39.94,2.74,1.51l8.21,3.46c2.5,1.01,4.31,2.26,5.44,3.74,1.13,1.49,1.69,3.46,1.69,5.9,0,3.6-1.27,6.31-3.82,8.14-2.54,1.83-6.26,2.74-11.16,2.74Z"/>
<path class="cls-1" d="M267.62,60.55c-2.88,0-5.11-.88-6.7-2.63s-2.38-4.24-2.38-7.45c0-2.5.47-4.52,1.4-6.08.94-1.56,2.5-2.78,4.68-3.67,2.18-.89,5.1-1.48,8.75-1.76l6.7-.65-.07,5.47-5.33.5c-2.45.24-4.14.73-5.08,1.48-.94.74-1.4,1.93-1.4,3.56,0,1.3.26,2.23.79,2.81.53.58,1.32.86,2.38.86,1.34,0,2.69-.41,4.03-1.22,1.34-.82,2.98-2.26,4.9-4.32l.43,5.98c-1.34,1.39-2.68,2.63-4,3.71-1.32,1.08-2.71,1.92-4.18,2.52-1.46.6-3.11.9-4.93.9ZM281.45,59.69c-.29,0-.5-.08-.65-.25-.14-.17-.26-.4-.36-.68-.1-.53-.22-1.33-.36-2.41s-.26-2.15-.36-3.2l-.72-3.02v-14.47c0-1.82-.35-3.11-1.04-3.85-.7-.74-1.93-1.12-3.71-1.12-3.26,0-4.82,1.22-4.68,3.67.05.62-.26.94-.94.94h-7.56c-.58,0-.91-.38-1.01-1.15-.29-3.5.83-6.2,3.35-8.1,2.52-1.9,6.25-2.84,11.2-2.84s8.7,1.02,10.98,3.06c2.28,2.04,3.42,5.27,3.42,9.68v14.62c0,1.54.04,2.96.11,4.28.07,1.32.18,2.6.32,3.85.1.67-.22,1.01-.94,1.01h-7.06Z"/>
<path class="cls-1" d="M310.24,60.55c-1.97,0-3.79-.11-5.47-.32-1.68-.22-3.37-.46-5.08-.72-1.7-.26-3.54-.47-5.51-.61V11.45c0-.62.31-.94.94-.94h8.14c.62,0,.94.31.94.94v40.32c.86.14,1.74.28,2.63.4.89.12,1.74.18,2.56.18,2.21,0,3.84-.61,4.9-1.84,1.05-1.22,1.58-3.04,1.58-5.44v-7.42c0-2.06-.36-3.55-1.08-4.46-.72-.91-1.83-1.37-3.31-1.37-1.2,0-2.46.35-3.78,1.04-1.32.7-2.89,1.81-4.72,3.35l.22-7.49c2.02-1.87,4.03-3.26,6.05-4.18,2.02-.91,4.08-1.37,6.19-1.37,3.5,0,6.12,1.02,7.85,3.06,1.73,2.04,2.59,5.17,2.59,9.4v10.3c0,4.94-1.27,8.62-3.82,11.02-2.54,2.4-6.48,3.6-11.81,3.6Z"/>
<path class="cls-1" d="M331.27,59.69c-.62,0-.94-.31-.94-.94V11.45c0-.62.31-.94.94-.94h8.14c.62,0,.94.31.94.94v47.3c0,.62-.31.94-.94.94h-8.14Z"/>
<path class="cls-1" d="M361,60.55c-5.57,0-9.68-1.19-12.35-3.56s-4-5.89-4-10.55v-8.28c0-4.9,1.33-8.62,4-11.16,2.66-2.54,6.73-3.82,12.2-3.82s9.35,1.22,12.06,3.67,4.07,6.05,4.07,10.8v5.62c0,.62-.31.94-.94.94h-21.46v2.16c0,2.21.49,3.85,1.48,4.93.98,1.08,2.6,1.62,4.86,1.62,1.73,0,3.1-.28,4.1-.83s1.51-1.38,1.51-2.48c0-.62.31-.94.94-.94h7.85c.58,0,.89.31.94.94.1,3.65-1.13,6.38-3.67,8.21-2.54,1.83-6.41,2.74-11.59,2.74ZM354.59,38.16h12.6v-.36c0-2.4-.5-4.15-1.51-5.26-1.01-1.1-2.57-1.66-4.68-1.66-2.26,0-3.89.56-4.9,1.69-1.01,1.13-1.51,2.89-1.51,5.29v.29Z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 6.2 KiB

@@ -0,0 +1,75 @@
<?php //Pressable Cache Purge Adds a Cache Purge button to the admin bar
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
add_action( 'admin_bar_menu', 'cache_add_item', 100 );
function cache_add_item( $admin_bar ) {
if ( is_admin() ) {
global $pagenow;
$admin_bar->add_menu(
array(
'id' => 'cache-purge',
'title' => 'Object Cache Purge',
'href' => '#',
)
);
// $admin_bar->add_menu( array( 'id'=>'settings','title'=>'Cache Settings', 'parent'=> 'cache-purge', 'href'=>'admin.php?page=pressable_cache_management' ) );
}
}
add_action( 'admin_footer', 'cache_purge_action_js' );
function cache_purge_action_js() { ?>
<script type="text/javascript" >
jQuery("li#wp-admin-bar-cache-purge .ab-item").on( "click", function() {
var data = {
'action': 'pressable_cache_purge',
};
jQuery.post(ajaxurl, data, function(response) {
alert( response );
});
});
</script>
<style type="text/css">
/*#wp-admin-bar-cache-purge .ab-item {
background-color: #0AD8C7;
}
*/
</style>
<?php
}
add_action( 'wp_ajax_pressable_cache_purge', 'pressable_cache_purge_callback' );
function pressable_cache_purge_callback() {
wp_cache_flush();
//Save time stamp to database if cache is flushed.
$object_cache_flush_time = date( ' jS F Y g:ia' ) . "\nUTC";
update_option( 'flush-obj-cache-time-stamp', $object_cache_flush_time );
$response = 'Object Cache Purged';
echo $response;
wp_die();
}
@@ -0,0 +1,117 @@
<?php // Pressable Cache Management - Enable Caching for pages which has wpp_ cookies
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
$options = get_option('pressable_cache_management_options');
if (isset($options['cache_wpp_cookies_pages']) && !empty($options['cache_wpp_cookies_pages']))
{
//Create the pressable-cache-management mu-plugin index file
$pcm_mu_plugins_index = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management.php';
if (!file_exists($pcm_mu_plugins_index))
{
// Copy pressable-cache-management.php from plugin directory to mu-plugins directory
copy(plugin_dir_path(__FILE__) . '/pressable_cache_management_mu_plugin_index.php', $pcm_mu_plugins_index);
}
// Check if the pressable-cache-management directory exists or create the folder
if (!file_exists(WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/'))
{
//create the directory
wp_mkdir_p(WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/');
}
//Add the option from the textbox into the database
update_option('cache_wpp_cookies_pages', $options['cache_wpp_cookies_pages']);
$obj_cache_wpp_cookies_pages = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_cache_wpp_cookies_pages.php';
if (file_exists($obj_cache_wpp_cookies_pages))
{
}
else
{
$obj_cache_wpp_cookies_pages = plugin_dir_path(__FILE__) . '/cache_wpp_cookie_page_mu_plugin.php';
$obj_cache_wpp_cookies_pages_active = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_cache_wpp_cookies_pages.php';
//Flush cache to enable activation take effect immediately
wp_cache_flush();
if (!copy($obj_cache_wpp_cookies_pages, $obj_cache_wpp_cookies_pages_active))
{
}
else
{
}
}
//Display admin notice
function cache_wpp_cookies_pages_admin_notice($message = '', $classes = 'notice-success')
{
if (!empty($message))
{
printf('<div class="notice %2$s">%1$s</div>', $message, $classes);
}
}
function pcm_cache_wpp_cookies_pages_admin_notice()
{
$cache_wpp_cookies_pages_activate_display_notice = get_option('cache_wpp_cookies_pages_activate_notice', 'activating');
if ('activating' === $cache_wpp_cookies_pages_activate_display_notice && current_user_can('manage_options'))
{
add_action('admin_notices', function ()
{
$screen = get_current_screen();
//Display admin notice for this plugin page only
if ($screen->id !== 'toplevel_page_pressable_cache_management') return;
$user = $GLOBALS['current_user'];
$message = sprintf('<p>Batcache will now cache pages with wpp_ cookies.</p>');
cache_wpp_cookies_pages_admin_notice($message, 'notice notice-success is-dismissible');
});
update_option('cache_wpp_cookies_pages_activate_notice', 'activated');
}
}
add_action('init', 'pcm_cache_wpp_cookies_pages_admin_notice');
}
else
{
/**Update option from the database if the option is deactivated
used by admin notice to display and remove notice**/
update_option('cache_wpp_cookies_pages_activate_notice', 'activating');
$obj_cache_wpp_cookies_pages = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_cache_wpp_cookies_pages.php';
if (file_exists($obj_cache_wpp_cookies_pages))
{
unlink($obj_cache_wpp_cookies_pages);
//Flush cache to enable deactivation take effect immediately
wp_cache_flush();
}
else
{
// File not found.
}
}
@@ -0,0 +1,35 @@
<?php // Pressable Cache Management - Cache pages which sets wpp_ cookies
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
/**
* Batcache by default ignore all cookies starting with wp so
* we have to add cookies to skip list if we want batcache to
* cache certain pages with cookies.
*
* Wonder plugin sets cookies starting with wpp which was preventing pages
* getting cached. We collect all the cookies starting with wpp_ below
* and adds it to the list that can be cached
*/
$all_wpp_cookies = array();
if ( is_array( $_COOKIE) && ! empty( $_COOKIE ) ) {
foreach ( array_keys( $_COOKIE ) as $maybe_wpp ) {
if ( substr( $maybe_wpp, 0, 4 ) == 'wpp_' ) {
$all_wpp_cookies[] = $maybe_wpp;
}
}
}
// Only add cookies to noskip if we found any starting with wpp_
// The wordpress_test_cookies is the default one
if( count($all_wpp_cookies) > 0 ){
global $batcache;
$batcache['noskip_cookies'] = array_merge( array('wordpress_test_cookie'), $all_wpp_cookies );
}
@@ -0,0 +1,229 @@
<?php
/**
* Pressable Cache Management - Edge Cache Defensive Mode
*
* Mirrors the exact pattern used in edge_cache_admin_action_handler():
* query_ec_backend( $endpoint, array( 'body' => $data ) )
*
* Enable: POST to ddos_until with body timestamp = time() + duration_seconds
* Disable: POST to ddos_until with body timestamp = 0
* Status: get_ec_ddos_until() — returns the Unix timestamp or 0 if off
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// ─── Duration map: slug => [ label, seconds ] ────────────────────────────────
function pcm_defensive_mode_durations() {
return [
'30-minutes' => [ 'label' => '30 minutes', 'seconds' => 30 * MINUTE_IN_SECONDS ],
'45-minutes' => [ 'label' => '45 minutes', 'seconds' => 45 * MINUTE_IN_SECONDS ],
'1-hour' => [ 'label' => '1 hour', 'seconds' => HOUR_IN_SECONDS ],
'2-hours' => [ 'label' => '2 hours', 'seconds' => 2 * HOUR_IN_SECONDS ],
'3-hours' => [ 'label' => '3 hours', 'seconds' => 3 * HOUR_IN_SECONDS ],
'4-hours' => [ 'label' => '4 hours', 'seconds' => 4 * HOUR_IN_SECONDS ],
'5-hours' => [ 'label' => '5 hours', 'seconds' => 5 * HOUR_IN_SECONDS ],
'6-hours' => [ 'label' => '6 hours', 'seconds' => 6 * HOUR_IN_SECONDS ],
'7-hours' => [ 'label' => '7 hours', 'seconds' => 7 * HOUR_IN_SECONDS ],
'8-hours' => [ 'label' => '8 hours', 'seconds' => 8 * HOUR_IN_SECONDS ],
'9-hours' => [ 'label' => '9 hours', 'seconds' => 9 * HOUR_IN_SECONDS ],
'10-hours' => [ 'label' => '10 hours', 'seconds' => 10 * HOUR_IN_SECONDS ],
'11-hours' => [ 'label' => '11 hours', 'seconds' => 11 * HOUR_IN_SECONDS ],
'12-hours' => [ 'label' => '12 hours', 'seconds' => 12 * HOUR_IN_SECONDS ],
'13-hours' => [ 'label' => '13 hours', 'seconds' => 13 * HOUR_IN_SECONDS ],
'14-hours' => [ 'label' => '14 hours', 'seconds' => 14 * HOUR_IN_SECONDS ],
'15-hours' => [ 'label' => '15 hours', 'seconds' => 15 * HOUR_IN_SECONDS ],
'16-hours' => [ 'label' => '16 hours', 'seconds' => 16 * HOUR_IN_SECONDS ],
'17-hours' => [ 'label' => '17 hours', 'seconds' => 17 * HOUR_IN_SECONDS ],
'18-hours' => [ 'label' => '18 hours', 'seconds' => 18 * HOUR_IN_SECONDS ],
'19-hours' => [ 'label' => '19 hours', 'seconds' => 19 * HOUR_IN_SECONDS ],
'20-hours' => [ 'label' => '20 hours', 'seconds' => 20 * HOUR_IN_SECONDS ],
'21-hours' => [ 'label' => '21 hours', 'seconds' => 21 * HOUR_IN_SECONDS ],
'22-hours' => [ 'label' => '22 hours', 'seconds' => 22 * HOUR_IN_SECONDS ],
'23-hours' => [ 'label' => '23 hours', 'seconds' => 23 * HOUR_IN_SECONDS ],
'1-day' => [ 'label' => '1 day', 'seconds' => DAY_IN_SECONDS ],
'2-days' => [ 'label' => '2 days', 'seconds' => 2 * DAY_IN_SECONDS ],
'3-days' => [ 'label' => '3 days', 'seconds' => 3 * DAY_IN_SECONDS ],
'4-days' => [ 'label' => '4 days', 'seconds' => 4 * DAY_IN_SECONDS ],
'5-days' => [ 'label' => '5 days', 'seconds' => 5 * DAY_IN_SECONDS ],
'6-days' => [ 'label' => '6 days', 'seconds' => 6 * DAY_IN_SECONDS ],
'7-days' => [ 'label' => '7 days', 'seconds' => 7 * DAY_IN_SECONDS ],
];
}
// ─── Enable Defensive Mode ────────────────────────────────────────────────────
function pcm_pressable_enable_defensive_mode() {
if ( ! isset( $_POST['enable_defensive_mode_nonce'] ) ) {
return;
}
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['enable_defensive_mode_nonce'] ) ), 'enable_defensive_mode_nonce' ) ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$durations = pcm_defensive_mode_durations();
$slug = isset( $_POST['defensive_mode_duration'] )
? sanitize_text_field( wp_unslash( $_POST['defensive_mode_duration'] ) )
: '30-minutes';
if ( ! array_key_exists( $slug, $durations ) ) {
$slug = '30-minutes';
}
if ( ! class_exists( 'Edge_Cache_Plugin' ) ) {
add_action( 'admin_notices', function() {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( esc_html__( 'Error: Edge Cache Plugin is not active.', 'pressable_cache_management' ), '#dd3a03' );
}
} );
return;
}
$expires_at = time() + $durations[ $slug ]['seconds'];
$edge_cache = Edge_Cache_Plugin::get_instance();
$result = $edge_cache->query_ec_backend( 'ddos_until', array(
'body' => array(
'timestamp' => $expires_at,
'wp_action' => 'manual_dashboard_set',
),
) );
if ( false === $result['success'] ) {
$err = ! empty( $result['error'] ) ? $result['error'] : esc_html__( 'Unknown error enabling Defensive Mode.', 'pressable_cache_management' );
add_action( 'admin_notices', function() use ( $err ) {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( $err, '#dd3a03' );
}
} );
} else {
update_option( 'edge-cache-defensive-mode-active', 'yes' );
update_option( 'edge-cache-defensive-mode-slug', $slug );
update_option( 'edge-cache-defensive-mode-expires-at', $expires_at );
update_option( 'edge-cache-defensive-mode-set-at', gmdate( 'j M Y, g:ia' ) . ' UTC' );
delete_transient( 'pcm_ec_status_cache' );
do_action( 'pcm_after_defensive_mode_change' );
$label = $durations[ $slug ]['label'];
add_action( 'admin_notices', function() use ( $label ) {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice(
sprintf( esc_html__( 'Defensive Mode enabled for %s.', 'pressable_cache_management' ), $label ),
'#03fcc2'
);
}
} );
}
}
add_action( 'init', 'pcm_pressable_enable_defensive_mode' );
// ─── Disable Defensive Mode ───────────────────────────────────────────────────
function pcm_pressable_disable_defensive_mode() {
if ( ! isset( $_POST['disable_defensive_mode_nonce'] ) ) {
return;
}
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['disable_defensive_mode_nonce'] ) ), 'disable_defensive_mode_nonce' ) ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
if ( ! class_exists( 'Edge_Cache_Plugin' ) ) {
add_action( 'admin_notices', function() {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( esc_html__( 'Error: Edge Cache Plugin is not active.', 'pressable_cache_management' ), '#dd3a03' );
}
} );
return;
}
$edge_cache = Edge_Cache_Plugin::get_instance();
$result = $edge_cache->query_ec_backend( 'ddos_until', array(
'body' => array(
'timestamp' => 0,
'wp_action' => 'manual_dashboard_set',
),
) );
if ( false === $result['success'] ) {
$err = ! empty( $result['error'] ) ? $result['error'] : esc_html__( 'Unknown error disabling Defensive Mode.', 'pressable_cache_management' );
add_action( 'admin_notices', function() use ( $err ) {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( $err, '#dd3a03' );
}
} );
} else {
update_option( 'edge-cache-defensive-mode-active', 'no' );
update_option( 'edge-cache-defensive-mode-slug', '' );
update_option( 'edge-cache-defensive-mode-expires-at', 0 );
update_option( 'edge-cache-defensive-mode-set-at', '' );
delete_transient( 'pcm_ec_status_cache' );
do_action( 'pcm_after_defensive_mode_change' );
add_action( 'admin_notices', function() {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( esc_html__( 'Defensive Mode disabled.', 'pressable_cache_management' ), '#03fcc2' );
}
} );
}
}
add_action( 'init', 'pcm_pressable_disable_defensive_mode' );
// ─── AJAX: check defensive mode status from server ───────────────────────────
// Uses get_ec_ddos_until() which calls query_ec_backend( 'ddos_until' ) as a
// GET (no body args) and returns the ddos_until Unix timestamp, or 0 if off.
function pcm_ajax_check_defensive_mode_status() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( [ 'message' => 'Unauthorized' ], 403 );
return;
}
if ( ! class_exists( 'Edge_Cache_Plugin' ) ) {
wp_send_json_error( [ 'message' => 'Edge Cache Plugin not available.' ] );
return;
}
$edge_cache = Edge_Cache_Plugin::get_instance();
$ddos_until = $edge_cache->get_ec_ddos_until(); // returns int timestamp or EC_ERROR (-1)
// EC_ERROR means the API call failed
if ( Edge_Cache_Plugin::EC_ERROR === $ddos_until ) {
wp_send_json_error( [ 'message' => 'Could not retrieve Defensive Mode status from server.' ] );
return;
}
$is_defensive = $ddos_until > time();
if ( $is_defensive ) {
// Sync local flag if mode was activated externally (WP-CLI, direct API)
update_option( 'edge-cache-defensive-mode-active', 'yes' );
update_option( 'edge-cache-defensive-mode-expires-at', $ddos_until );
$set_at = get_option( 'edge-cache-defensive-mode-set-at', '' );
$expires_str = gmdate( 'j M Y, g:ia', $ddos_until ) . ' UTC';
wp_send_json_success( [
'defensive_active' => true,
'set_at' => $set_at,
'expires_at' => $expires_str,
] );
} else {
// Server says off — sync local options
update_option( 'edge-cache-defensive-mode-active', 'no' );
update_option( 'edge-cache-defensive-mode-slug', '' );
update_option( 'edge-cache-defensive-mode-expires-at', 0 );
update_option( 'edge-cache-defensive-mode-set-at', '' );
wp_send_json_success( [
'defensive_active' => false,
'set_at' => '',
'expires_at' => '',
] );
}
}
add_action( 'wp_ajax_pcm_check_defensive_mode_status', 'pcm_ajax_check_defensive_mode_status' );
@@ -0,0 +1,73 @@
<?php // Pressable Cache Management - Exclude pages from Batcache
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
$options = get_option('pressable_cache_management_options');
if (isset($options['exempt_from_batcache']) && !empty($options['exempt_from_batcache']))
{
//Create the pressable-cache-management mu-plugin index file
$pcm_mu_plugins_index = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management.php';
if (!file_exists($pcm_mu_plugins_index)) {
// Copy pressable-cache-management.php from plugin directory to mu-plugins directory
copy( plugin_dir_path(__FILE__) . '/pressable_cache_management_mu_plugin_index.php', $pcm_mu_plugins_index);
}
// Check if the pressable-cache-management directory exists or create the folder
if (!file_exists(WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/')) {
//create the directory
wp_mkdir_p(WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/');
}
//Add the option from the textbox into the database
update_option('exempt_from_batcache', $options['exempt_from_batcache']);
// Exclude pages from Batcache
$obj_exclude_pages_from_batcache = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_exclude_pages_from_batcache.php';
if (file_exists($obj_exclude_pages_from_batcache))
{
}
else
{
$obj_exclude_pages_from_batcache = plugin_dir_path(__FILE__) . '/exclude_pages_from_batcache_mu_plugin.php';
$obj_exclude_pages_from_batcache_active = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_exclude_pages_from_batcache.php';
//Flush cache to enable activation take effect immediately
wp_cache_flush();
if (!copy($obj_exclude_pages_from_batcache, $obj_exclude_pages_from_batcache_active))
{
}
else
{
}
}
}
else
{
$obj_exclude_pages_from_batcache = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_exclude_pages_from_batcache.php';
if (file_exists($obj_exclude_pages_from_batcache))
{
unlink($obj_exclude_pages_from_batcache);
//Flush cache to enable deactivation take effect immediately
wp_cache_flush();
}
else
{
// File not found.
}
}
@@ -0,0 +1,48 @@
<?php
// Plugin Name: Exclude website pages from the Batcache and Edge Cache
if (!defined('IS_PRESSABLE')) {
return;
}
add_action('init', 'cancel_the_cache');
function cancel_the_cache() {
if (!function_exists('batcache_cancel')) {
return;
}
$options = get_option('pressable_cache_management_options');
$exempted_pages = isset($options['exempt_from_batcache']) ? $options['exempt_from_batcache'] : '';
if (empty($exempted_pages)) {
return;
}
// Convert stored options into an array and trim spaces
$exempted_pages = array_map('trim', explode(',', $exempted_pages));
// Get current URI without query parameters
$uri = strtok($_SERVER["REQUEST_URI"], '?');
// Always exclude homepage if listed or explicitly requested
if ($uri === '/' && in_array('/', $exempted_pages)) {
batcache_cancel();
disable_edge_cache();
return;
}
// Loop through exempted pages
foreach ($exempted_pages as $page) {
// Match exact page or paginated versions (e.g., /about/, /about/page/2/)
if ($uri === $page || preg_match("#^" . preg_quote($page, '#') . "(/page/\d+/?)?$#i", $uri)) {
batcache_cancel();
disable_edge_cache();
return;
}
}
}
function disable_edge_cache() {
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
}
@@ -0,0 +1,122 @@
<?php // Pressable Cache Management - Exclude Google Ads URL's with query string gclid from Batcache
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
$options = get_option('pressable_cache_management_options');
if (isset($options['exclude_query_string_gclid_checkbox']) && !empty($options['exclude_query_string_gclid_checkbox']))
{
//Create the pressable-cache-management mu-plugin index file
$pcm_mu_plugins_index = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management.php';
if (!file_exists($pcm_mu_plugins_index)) {
// Copy pressable-cache-management.php from plugin directory to mu-plugins directory
copy( plugin_dir_path(__FILE__) . '/pressable_cache_management_mu_plugin_index.php', $pcm_mu_plugins_index);
}
// Check if the pressable-cache-management directory exists or create the folder
if (!file_exists(WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/')) {
//create the directory
wp_mkdir_p(WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/');
}
//Declear variable so that it can be accessed from
$exclude_query_string_gclid = get_option('exclude_query_string_gclid');
// Exclude Google Ads URL's with query string gclid from Batcache
$obj_exclude_query_string_gclid = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_exclude_query_string_gclid.php';
if (file_exists($obj_exclude_query_string_gclid))
{
}
else
{
$obj_exclude_query_string_gclid = plugin_dir_path(__FILE__) . '/exclude_query_string_gclid_from_cache_mu_plugin.php';
$obj_exclude_query_string_gclid_active = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_exclude_query_string_gclid.php';
//Flush cache to enable activation take effect immediately
wp_cache_flush();
if (!copy($obj_exclude_query_string_gclid, $obj_exclude_query_string_gclid_active))
{
}
else
{
}
}
//Display admin notice
function exclude_query_string_gclid_admin_notice($message = '', $classes = 'notice-success')
{
if (!empty($message))
{
printf('<div class="notice %2$s">%1$s</div>', $message, $classes);
}
}
function pcm_exclude_query_string_gclid_admin_notice()
{
$exclude_query_string_gclid_activate_display_notice = get_option('exclude_query_string_gclid_activate_notice', 'activating');
if ('activating' === $exclude_query_string_gclid_activate_display_notice && current_user_can('manage_options'))
{
add_action('admin_notices', function ()
{
$screen = get_current_screen();
//Display admin notice for this plugin page only
if ($screen->id !== 'toplevel_page_pressable_cache_management') return;
$user = $GLOBALS['current_user'];
$message = sprintf('<p> Google Ads URL with query string (gclid) will be excluded from Batcache.</p>', $user->display_name);
exclude_query_string_gclid_admin_notice($message, 'notice notice-success is-dismissible');
});
update_option('exclude_query_string_gclid_activate_notice', 'activated');
}
}
add_action('init', 'pcm_exclude_query_string_gclid_admin_notice');
}
else
{
/**Update option from the database if the option is deactivated
used by admin notice to display and remove notice**/
update_option('exclude_query_string_gclid_activate_notice', 'activating');
$obj_exclude_query_string_gclid = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_exclude_query_string_gclid.php';
if (file_exists($obj_exclude_query_string_gclid))
{
unlink($obj_exclude_query_string_gclid);
//Flush cache to enable deactivation take effect immediately
wp_cache_flush();
}
else
{
// File not found.
}
}
@@ -0,0 +1,25 @@
<?php // Pressable Cache Management - Exclude Google Ads URL with query string gclid from Batcache
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
/**
* Batcache by default will create a new cached page for each query parameter
* But we want to ignore Google Ads with the URL Param of gclid
**/
if (!function_exists('exclude_gclid_from_batcache')) {
function exclude_gclid_from_batcache() {
global $batcache;
if ( is_object( $batcache ) ) {
$batcache->ignored_query_args = array( 'gclid' );
}
}
}
add_action( 'plugins_loaded', 'exclude_gclid_from_batcache' );
@@ -0,0 +1,50 @@
<?php
// Pressable Cache Management - Extend batcache by 24 hours
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$options = get_option( 'pressable_cache_management_options' );
if ( isset( $options['extend_batcache_checkbox'] ) && ! empty( $options['extend_batcache_checkbox'] ) ) {
update_option( 'extend_batcache_checkbox', $options['extend_batcache_checkbox'] );
$extend_batcache = get_option( 'extend_batcache_checkbox' );
// Create the mu-plugin index file if it doesn't exist
$pcm_mu_plugins_index = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management.php';
if ( ! file_exists( $pcm_mu_plugins_index ) ) {
copy( plugin_dir_path( __FILE__ ) . '/pressable_cache_management_mu_plugin_index.php', $pcm_mu_plugins_index );
}
// Ensure mu-plugins directory exists
if ( ! file_exists( WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/' ) ) {
wp_mkdir_p( WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/' );
}
$obj_extend_batcache = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_extend_batcache.php';
$obj_extend_batcache_source = plugin_dir_path( __FILE__ ) . '/extend_batcache_mu_plugin.php';
$obj_extend_batcache_active = $obj_extend_batcache;
if ( ! file_exists( $obj_extend_batcache ) ) {
// mu-plugin doesn't exist yet — this is a FRESH enable, copy file and queue notice
wp_cache_flush();
if ( copy( $obj_extend_batcache_source, $obj_extend_batcache_active ) ) {
// Mark notice as pending — will show ONCE on next admin page load, then clear itself
update_option( 'pcm_extend_batcache_notice_pending', '1' );
}
}
// If file already exists: checkbox was already on before this load — do NOT re-queue notice
} else {
// Checkbox is OFF — clear the notice flag and remove the mu-plugin
delete_option( 'pcm_extend_batcache_notice_pending' );
$obj_extend_batcache = WP_CONTENT_DIR . '/mu-plugins/pressable-cache-management/pcm_extend_batcache.php';
if ( file_exists( $obj_extend_batcache ) ) {
unlink( $obj_extend_batcache );
wp_cache_flush();
}
}
@@ -0,0 +1,18 @@
<?php // Extend Batcache for Pressable site
if (!defined('IS_PRESSABLE'))
{
return;
}
//Batcache Customizations
global $batcache;
//Check is batcache params are in an object or an array, apply customizations accordingly
if ( is_object( $batcache ) ) {
$batcache->max_age = 86400; // Seconds the cached render of a page will be stored
$batcache->seconds = 1200; // The amount of time at least 2 people are required to
} elseif ( is_array( $batcache ) ) {
$batcache['max_age'] = 86400; // Seconds the cached render of a page will be stored
$batcache['seconds'] = 1200;// The amount of time at least 2 people are required to
}
@@ -0,0 +1,139 @@
<?php
/**
* Pressable Cache Management - Flush cache for a particular page (column link)
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$options = get_option( 'pressable_cache_management_options' );
if ( isset( $options['flush_object_cache_for_single_page'] ) && ! empty( $options['flush_object_cache_for_single_page'] ) ) {
add_action( 'init', 'pcm_show_flush_cache_column' );
function pcm_show_flush_cache_column() {
if ( current_user_can('administrator') || current_user_can('editor') || current_user_can('manage_woocommerce') ) {
$column = new FlushObjectCachePageColumn();
$column->add();
}
}
function flush_object_cache_for_single_page_notice() {
$state = get_option( 'flush-object-cache-for-single-page-notice', 'activating' );
if ( 'activating' === $state &&
( current_user_can('administrator') || current_user_can('editor') || current_user_can('manage_woocommerce') )
) {
add_action( 'admin_notices', function() {
$screen = get_current_screen();
if ( ! isset( $screen ) || $screen->id !== 'toplevel_page_pressable_cache_management' ) return;
$wrap = 'display:flex;align-items:center;justify-content:space-between;gap:12px;'
. 'border-left:4px solid #03fcc2;background:#fff;border-radius:0 8px 8px 0;'
. 'padding:14px 18px;box-shadow:0 2px 8px rgba(4,0,36,.07);'
. 'margin:10px 0;font-family:sans-serif;';
$btn = 'background:none;border:none;cursor:pointer;color:#94a3b8;font-size:18px;line-height:1;padding:0;';
$pcm_nid = 'pcm-sp-notice-' . substr( md5( microtime() ), 0, 8 );
echo '<div style="max-width:1120px;margin:0 auto;padding:0 20px;box-sizing:border-box;">';
echo '<div id="' . $pcm_nid . '" style="' . $wrap . '">';
echo '<p style="margin:0;font-size:13px;color:#040024;">'
. esc_html__( 'You can Flush Cache for Individual page or post from page preview.', 'pressable_cache_management' )
. '</p>';
echo '<button type="button" onclick="document.getElementById(\'' . $pcm_nid . '\').remove();" style="' . $btn . '">&#x2297;</button>';
echo '</div>';
echo '</div>';
});
update_option( 'flush-object-cache-for-single-page-notice', 'activated' );
}
}
add_action( 'init', 'flush_object_cache_for_single_page_notice' );
} else {
update_option( 'flush-object-cache-for-single-page-notice', 'activating' );
}
// ─── FlushObjectCachePageColumn class ────────────────────────────────────────
if ( ! class_exists( 'FlushObjectCachePageColumn' ) ) {
class FlushObjectCachePageColumn {
public function __construct() {}
public function add() {
add_filter( 'post_row_actions', array( $this, 'add_flush_object_cache_link' ), 10, 2 );
add_filter( 'page_row_actions', array( $this, 'add_flush_object_cache_link' ), 10, 2 );
add_action( 'admin_enqueue_scripts', array( $this, 'load_js' ) );
add_action( 'wp_ajax_pcm_flush_object_cache_column', array( $this, 'flush_object_cache_column' ) );
}
public function add_flush_object_cache_link( $actions, $post ) {
if ( current_user_can('administrator') || current_user_can('editor') || current_user_can('manage_woocommerce') ) {
$actions['flush_object_cache_url'] =
'<a data-id="' . esc_attr( $post->ID ) . '"'
. ' data-nonce="' . wp_create_nonce( 'flush-object-cache_' . $post->ID ) . '"'
. ' id="flush-object-cache-url-' . esc_attr( $post->ID ) . '"'
. ' style="cursor:pointer;">'
. esc_html__( 'Flush Cache', 'pressable_cache_management' ) . '</a>';
}
return $actions;
}
public function flush_object_cache_column() {
if ( ! ( current_user_can('administrator') || current_user_can('editor') || current_user_can('manage_woocommerce') ) ) {
die( json_encode( array( 'success' => false, 'message' => 'Unauthorized' ) ) );
}
if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'flush-object-cache_' . intval( $_GET['id'] ) ) ) {
die( json_encode( array( 'success' => false, 'message' => 'Nonce verification failed' ) ) );
}
$url_key = get_permalink( intval( $_GET['id'] ) );
$page_title = get_the_title( intval( $_GET['id'] ) );
update_option( 'page-title', $page_title );
global $batcache, $wp_object_cache;
if ( ! isset( $batcache ) || ! is_object( $batcache ) || ! method_exists( $wp_object_cache, 'incr' ) ) {
die( json_encode( array( 'success' => false ) ) );
}
$batcache->configure_groups();
$url = apply_filters( 'batcache_manager_link', $url_key );
if ( empty( $url ) ) {
die( json_encode( array( 'success' => false ) ) );
}
do_action( 'batcache_manager_before_flush', $url );
$url = set_url_scheme( $url, 'http' );
$url_key = md5( $url );
wp_cache_add( "{$url_key}_version", 0, $batcache->group );
wp_cache_incr( "{$url_key}_version", 1, $batcache->group );
if ( property_exists( $wp_object_cache, 'no_remote_groups' ) ) {
$k = array_search( $batcache->group, (array) $wp_object_cache->no_remote_groups );
if ( false !== $k ) {
unset( $wp_object_cache->no_remote_groups[ $k ] );
wp_cache_set( "{$url_key}_version", $batcache->group );
$wp_object_cache->no_remote_groups[ $k ] = $batcache->group;
}
}
do_action( 'batcache_manager_after_flush', $url );
update_option( 'flush-object-cache-for-single-page-time-stamp', gmdate( 'j M Y, g:ia' ) . ' UTC' );
// Also store the flushed URL so it shows on the settings page
update_option( 'single-page-url-flushed', $url );
die( json_encode( array( 'success' => true ) ) );
}
public function load_js() {
wp_enqueue_script(
'flush-object-cache-column',
plugin_dir_url( dirname( __FILE__ ) ) . 'public/js/column.js',
array(), time(), true
);
}
}
}
@@ -0,0 +1,100 @@
<?php
/**
* Pressable Cache Management — Flush Batcache for WooCommerce Individual Pages
*
* When enabled, copies pcm_batcache_manager.php into mu-plugins so that Batcache
* is flushed automatically for any individual page/product updated via WooCommerce API.
* When disabled, removes the mu-plugin file and restores the previous state.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$options = get_option( 'pressable_cache_management_options' );
$enabled = ! empty( $options['flush_batcache_for_woo_product_individual_page_checkbox'] );
$mu_plugin_dest = WP_CONTENT_DIR . '/mu-plugins/pcm_batcache_manager.php';
$mu_plugin_src = plugin_dir_path( __FILE__ ) . 'pcm_batcache_manager.php';
if ( $enabled ) {
// ── Feature ON ───────────────────────────────────────────────────────────
// Always sync the source file into mu-plugins so that any updates to
// pcm_batcache_manager.php (e.g. targeted flush fixes) take effect immediately.
// Previously this only copied on first enable, meaning edits to the source
// were never deployed to the live mu-plugin copy.
$needs_update = ! file_exists( $mu_plugin_dest )
|| ( file_exists( $mu_plugin_src ) && md5_file( $mu_plugin_src ) !== md5_file( $mu_plugin_dest ) );
if ( $needs_update && file_exists( $mu_plugin_src ) && @copy( $mu_plugin_src, $mu_plugin_dest ) ) {
if ( ! file_exists( $mu_plugin_dest ) ) {
// Only flush and show notice on fresh enable, not on every update
wp_cache_flush();
update_option( 'flush_batcache_for_woo_product_individual_page_activate_notice', 'activating' );
}
}
// ── Show branded activation notice (once, on next page load) ─────────────
add_action( 'init', 'pcm_woo_individual_page_activation_notice' );
function pcm_woo_individual_page_activation_notice() {
$state = get_option( 'flush_batcache_for_woo_product_individual_page_activate_notice', 'activated' );
if ( 'activating' !== $state || ! current_user_can( 'manage_options' ) ) {
return;
}
add_action( 'admin_notices', 'pcm_woo_individual_page_render_notice' );
update_option( 'flush_batcache_for_woo_product_individual_page_activate_notice', 'activated' );
}
function pcm_woo_individual_page_render_notice() {
$screen = get_current_screen();
if ( ! $screen || $screen->id !== 'toplevel_page_pressable_cache_management' ) {
return;
}
$nid = 'pcm-woo-notice-' . substr( md5( microtime() ), 0, 8 );
$wrap = 'display:flex;align-items:center;justify-content:space-between;gap:12px;'
. 'border-left:4px solid #03fcc2;background:#fff;border-radius:0 8px 8px 0;'
. 'padding:14px 18px;box-shadow:0 2px 8px rgba(4,0,36,.07);'
. 'margin:10px 0;font-family:sans-serif;';
$icon_wrap = 'display:flex;align-items:center;gap:10px;';
$icon = '<span style="display:inline-flex;align-items:center;justify-content:center;'
. 'width:32px;height:32px;border-radius:50%;background:#f0fdf9;flex-shrink:0;">'
. '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">'
. '<path d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8z" fill="#03fcc2"/>'
. '<path d="M8 7a1 1 0 011 1v3a1 1 0 11-2 0V8a1 1 0 011-1zM8 5.5a1 1 0 100-2 1 1 0 000 2z" fill="#03fcc2"/>'
. '</svg></span>';
$btn = 'background:none;border:none;cursor:pointer;color:#94a3b8;font-size:18px;'
. 'line-height:1;padding:0;flex-shrink:0;margin-top:2px;';
echo '<div style="max-width:1120px;margin:0 auto;padding:0 20px;box-sizing:border-box;">';
echo '<div id="' . esc_attr( $nid ) . '" style="' . $wrap . '">';
echo '<div style="' . $icon_wrap . '">' . $icon;
echo '<div>';
echo '<p style="margin:0 0 2px;font-size:13px;font-weight:600;color:#040024;">'
. esc_html__( 'Flush Batcache for WooCommerce Product Pages — Enabled', 'pressable_cache_management' )
. '</p>';
echo '<p style="margin:0;font-size:12px;color:#64748b;">'
. esc_html__( 'Automatically flush individual pages, including product pages updated via the WooCommerce API.', 'pressable_cache_management' )
. '</p>';
echo '</div></div>';
echo '<button type="button" onclick="document.getElementById(\'' . esc_js( $nid ) . '\').remove();" style="' . $btn . '">&#x2297;</button>';
echo '</div>';
echo '</div>';
}
} else {
// ── Feature OFF ──────────────────────────────────────────────────────────
// Reset so notice shows again next time it is re-enabled
update_option( 'flush_batcache_for_woo_product_individual_page_activate_notice', 'activating' );
if ( file_exists( $mu_plugin_dest ) ) {
@unlink( $mu_plugin_dest );
wp_cache_flush();
}
}
@@ -0,0 +1,28 @@
<?php // Pressable Cache Management - Flush cache when comment is deleted
$options = get_option('pressable_cache_management_options');
if (isset($options['flush_cache_on_comment_delete_checkbox']) && !empty($options['flush_cache_on_comment_delete_checkbox']))
{
add_action( 'trash_comment', 'pcm_trash_comment_action', 10, 2 );
/**
* Function for `trash_comment` action-hook.
*
* @param string $comment_id The comment ID as a numeric string.
* @param WP_Comment $comment The comment to be trashed.
*
* @return void
*/
function pcm_trash_comment_action( $comment_id, $comment ){
wp_cache_flush();
//Save time stamp to database if cache is flushed when comment is deleted.
$object_cache_flush_time = date(' jS F Y g:ia') . "\nUTC";
update_option('flush-cache-on-comment-delete-time-stamp', $object_cache_flush_time);
}
}
@@ -0,0 +1,96 @@
<?php
/**
* Pressable Cache Management — Flush Batcache for the individual page/post on edit.
*
* Instead of flushing the entire object cache on every save, this targets only
* the Batcache entry for the URL of the post that was just saved — the same
* technique used by flush_batcache_for_particular_page.php (column link) and
* flush_single_page_toolbar.php (toolbar button).
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$options = get_option( 'pressable_cache_management_options' );
if ( isset( $options['flush_cache_page_edit_checkbox'] ) && ! empty( $options['flush_cache_page_edit_checkbox'] ) ) {
/**
* Flush Batcache only for the URL of the post that was just saved.
*
* Fires on save_post (covers pages, posts, and all custom post types,
* including WooCommerce products saved via the REST API).
*
* @param int $post_id The saved post ID.
* @param WP_Post $post The saved post object.
* @param bool $update True if this is an update, false for a new post.
*/
function pcm_flush_batcache_on_page_edit( $post_id, $post, $update ) {
// Skip auto-saves, revisions, and non-published posts
if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
return;
}
if ( $post->post_status !== 'publish' ) {
return;
}
// Get the public URL for this post
$url = get_permalink( $post_id );
if ( empty( $url ) ) {
return;
}
global $batcache, $wp_object_cache;
// Batcache must be loaded and the object cache must support incr()
if ( ! isset( $batcache ) || ! is_object( $batcache ) || ! method_exists( $wp_object_cache, 'incr' ) ) {
return;
}
$batcache->configure_groups();
$url = apply_filters( 'batcache_manager_link', $url );
if ( empty( $url ) ) {
return;
}
do_action( 'batcache_manager_before_flush', $url );
// Batcache keys off the http:// version of the URL
$url = set_url_scheme( $url, 'http' );
$url_key = md5( $url );
// Increment the version key — Batcache treats the cached copy as stale
wp_cache_add( "{$url_key}_version", 0, $batcache->group );
wp_cache_incr( "{$url_key}_version", 1, $batcache->group );
// Handle sites where the Batcache group is excluded from remote sync
if ( property_exists( $wp_object_cache, 'no_remote_groups' ) ) {
$k = array_search( $batcache->group, (array) $wp_object_cache->no_remote_groups );
if ( false !== $k ) {
unset( $wp_object_cache->no_remote_groups[ $k ] );
wp_cache_set( "{$url_key}_version", $batcache->group );
$wp_object_cache->no_remote_groups[ $k ] = $batcache->group;
}
}
do_action( 'batcache_manager_after_flush', $url );
// Record the flush for display on the settings page
$post_type_obj = get_post_type_object( $post->post_type );
$post_type_name = $post_type_obj ? $post_type_obj->labels->singular_name : $post->post_type;
$stamp = gmdate( 'j M Y, g:ia' ) . ' UTC'
. '<b> — cache flushed for ' . esc_html( $post_type_name )
. ' edit: ' . esc_html( $post->post_title ) . '</b>';
update_option( 'flush-cache-page-edit-time-stamp', $stamp );
// Also write the flushed URL so the settings page can show it
update_option( 'single-page-url-flushed', $url );
}
add_action( 'save_post', 'pcm_flush_batcache_on_page_edit', 10, 3 );
}
@@ -0,0 +1,40 @@
<?php // Custom function - Add custom functions to flush cache when page or post is deleted
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
$options = get_option('pressable_cache_management_options');
if (isset($options['flush_cache_on_page_post_delete_checkbox']) && !empty($options['flush_cache_on_page_post_delete_checkbox']))
{
function fire_on_page_post_delete( $post_ID, $post_after, $post_before ) {
if ( $post_after->post_status == 'trash' && $post_before->post_status == 'publish' ) {
// Flush site cache if post or page is trashed after publishing
wp_cache_flush();
}
if ( $post_after->post_status == 'publish' && $post_before->post_status == 'trash' ) {
// Flush site cache if post or page is published after being trash (post undelete)
wp_cache_flush();
}
// Save time stamp to database if cache is flushed when a post or page was daleted.
$object_cache_flush_time = date(' jS F Y g:ia') . "\nUTC";
update_option('flush-cache-on-page-post-delete-time-stamp', $object_cache_flush_time);
//Set transient for admin notice for 9 seconds
set_transient('pcm-page-post-delete-notice', true, 9);
}
add_action( 'post_updated', 'fire_on_page_post_delete', 10, 3 );
}
@@ -0,0 +1,76 @@
<?php
// Custom function - Flush cache automatically on themes and plugins update
if ( ! defined( 'ABSPATH' ) ) {
exit();
}
$options = get_option( 'pressable_cache_management_options' );
if ( isset( $options['flush_cache_theme_plugin_checkbox'] ) && ! empty( $options['flush_cache_theme_plugin_checkbox'] ) ) {
function pcm_plugins_themes_update_completed( $upgrader_object, $hook_extra ) {
$type = isset( $hook_extra['type'] ) ? $hook_extra['type'] : '';
if ( ! in_array( $type, array( 'plugin', 'theme' ), true ) ) {
return;
}
wp_cache_flush();
// ── Resolve the name of the updated item ────────────────────────────
$name = '';
// Multiple plugins updated at once
if ( $type === 'plugin' && isset( $hook_extra['plugins'] ) && is_array( $hook_extra['plugins'] ) ) {
$names = array();
foreach ( $hook_extra['plugins'] as $plugin_file ) {
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin_file, false, false );
if ( ! empty( $plugin_data['Name'] ) ) {
$names[] = $plugin_data['Name'];
}
}
$name = ! empty( $names ) ? implode( ', ', $names ) : 'Unknown plugin';
}
// Single plugin
if ( $type === 'plugin' && empty( $name ) ) {
if ( isset( $hook_extra['plugin'] ) ) {
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $hook_extra['plugin'], false, false );
$name = ! empty( $plugin_data['Name'] ) ? $plugin_data['Name'] : $hook_extra['plugin'];
} elseif ( isset( $upgrader_object->skin->plugin_info['Name'] ) ) {
$name = $upgrader_object->skin->plugin_info['Name'];
} else {
$name = 'Unknown plugin';
}
}
// Theme
if ( $type === 'theme' ) {
if ( isset( $hook_extra['themes'] ) && is_array( $hook_extra['themes'] ) ) {
$theme_names = array();
foreach ( $hook_extra['themes'] as $stylesheet ) {
$theme = wp_get_theme( $stylesheet );
if ( $theme->exists() ) {
$theme_names[] = $theme->get('Name');
}
}
$name = ! empty( $theme_names ) ? implode( ', ', $theme_names ) : 'Unknown theme';
} elseif ( isset( $hook_extra['theme'] ) ) {
$theme = wp_get_theme( $hook_extra['theme'] );
$name = $theme->exists() ? $theme->get('Name') : $hook_extra['theme'];
} elseif ( isset( $upgrader_object->skin->theme_info['Name'] ) ) {
$name = $upgrader_object->skin->theme_info['Name'];
} else {
$name = 'Unknown theme';
}
}
// ── Build timestamp with bold item name ──────────────────────────────
$timestamp = gmdate( 'j M Y, g:ia' ) . ' UTC — <b>' . esc_html( $name ) . ' ' . esc_html( $type ) . ' was updated</b>';
update_option( 'flush-cache-theme-plugin-time-stamp', $timestamp );
}
add_action( 'upgrader_process_complete', 'pcm_plugins_themes_update_completed', 10, 2 );
}
@@ -0,0 +1,70 @@
<?php
/**
* Pressable Cache Management - Flush Object Cache + Page Cache
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( isset( $_POST['flush_object_cache_nonce'] ) ) {
function pressable_cache_button() {
if ( ! wp_verify_nonce(
sanitize_text_field( wp_unslash( $_POST['flush_object_cache_nonce'] ) ),
'flush_object_cache_nonce'
) || ! current_user_can( 'manage_options' ) ) {
return;
}
// Flush WP Object Cache (Redis / Memcached)
wp_cache_flush();
// Flush Batcache page cache if available
if ( function_exists( 'batcache_clear_cache' ) ) {
batcache_clear_cache();
}
// WP Super Cache
if ( function_exists( 'wp_cache_clear_cache' ) ) {
wp_cache_clear_cache();
}
// W3 Total Cache
if ( function_exists( 'w3tc_flush_all' ) ) {
w3tc_flush_all();
}
// WP Rocket
if ( function_exists( 'rocket_clean_domain' ) ) {
rocket_clean_domain();
}
// Custom hook for other integrations
do_action( 'pcm_flush_all_cache' );
// Clear the cached Batcache status so the badge refreshes on next page load
do_action( 'pcm_after_object_cache_flush' );
delete_transient( 'pcm_batcache_status' );
}
add_action( 'wp_before_admin_bar_render', 'pressable_cache_button', 999 );
// Branded success notice - only show ONE (remove WP default)
function flush_cache_notice__success() {
$pcm_nid = 'pcm-obj-notice-' . substr( md5( microtime() ), 0, 8 );
$wrap = 'display:flex;align-items:center;justify-content:space-between;gap:12px;'
. 'border-left:4px solid #03fcc2;background:#fff;border-radius:0 8px 8px 0;'
. 'padding:14px 18px;box-shadow:0 2px 8px rgba(4,0,36,.07);'
. 'margin:10px 20px 10px 0;font-family:sans-serif;';
$btn = 'background:none;border:none;cursor:pointer;color:#94a3b8;font-size:18px;line-height:1;padding:0;';
echo '<div id="' . $pcm_nid . '" style="' . $wrap . '">';
echo '<p style="margin:0;font-size:13px;color:#040024;">'
. esc_html__( 'Object Cache Flushed Successfully.', 'pressable_cache_management' )
. '</p>';
echo '<button type="button" onclick="document.getElementById(\'' . $pcm_nid . '\').remove();" style="' . $btn . '">&#x2297;</button>';
echo '</div>';
}
add_action( 'admin_notices', 'flush_cache_notice__success' );
update_option( 'flush-obj-cache-time-stamp', gmdate( 'j M Y, g:ia' ) . ' UTC' );
}
@@ -0,0 +1,214 @@
<?php
/**
* Pressable Cache Management - Flush Batcache for Individual Page from toolbar
* Sourced from official repo flush_single_page_toolbar.php with branded notices.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$options = get_option( 'pressable_cache_management_options' );
if ( isset( $options['flush_object_cache_for_single_page'] ) && ! empty( $options['flush_object_cache_for_single_page'] ) ) {
if ( ! class_exists( 'PcmFlushCacheAdminbar' ) ) {
class PcmFlushCacheAdminbar {
public function __construct() {}
public function add() {
if ( is_admin() ) {
add_action( 'wp_before_admin_bar_render', array( $this, 'PcmFlushCacheAdminbar' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'load_toolbar_js' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'load_remove_branding_toolbar_js' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'load_toolbar_css' ) );
} else {
if ( is_admin() || is_admin_bar_showing() ) {
add_action( 'wp_before_admin_bar_render', array( $this, 'pcm_toolbar_for_page_preview' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'load_toolbar_js' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'load_remove_branding_toolbar_js' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'load_toolbar_css' ) );
add_action( 'wp_footer', array( $this, 'print_my_inline_script' ) );
}
}
// AJAX: flush batcache for current page
add_action( 'wp_ajax_pcm_delete_current_page_cache', array( $this, 'pcm_delete_current_page_cache' ) );
// AJAX: purge edge cache for current page
add_action( 'wp_ajax_pcm_purge_current_page_edge_cache', array( $this, 'pcm_purge_current_page_edge_cache' ) );
}
public function pcm_delete_current_page_cache() {
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'pcm_nonce' ) ) {
die( json_encode( array( 'Security Error!', 'error', 'alert' ) ) );
}
global $batcache, $wp_object_cache;
if ( ! isset( $batcache ) || ! is_object( $batcache ) || ! method_exists( $wp_object_cache, 'incr' ) ) {
return;
}
$batcache->configure_groups();
$path = urldecode( esc_url_raw( wp_unslash( $_GET['path'] ) ) );
if ( preg_match( '/\.{2,}/', $path ) ) {
die( 'Suspected Directory Traversal Attack' );
}
$url = get_home_url() . $path;
$url = apply_filters( 'batcache_manager_link', $url );
if ( empty( $url ) ) return false;
do_action( 'batcache_manager_before_flush', $url );
$url = set_url_scheme( $url, 'http' );
update_option( 'single-page-url-flushed', $url );
$url_key = md5( $url );
if ( is_object( $batcache ) ) {
wp_cache_add( "{$url_key}_version", 0, $batcache->group );
wp_cache_incr( "{$url_key}_version", 1, $batcache->group );
}
if ( property_exists( $wp_object_cache, 'no_remote_groups' ) ) {
$k = array_search( $batcache->group, (array) $wp_object_cache->no_remote_groups );
if ( false !== $k ) {
unset( $wp_object_cache->no_remote_groups[ $k ] );
wp_cache_set( "{$url_key}_version", $batcache->group );
$wp_object_cache->no_remote_groups[ $k ] = $batcache->group;
}
}
do_action( 'batcache_manager_after_flush', $url );
update_option( 'flush-object-cache-for-single-page-time-stamp', gmdate( 'j M Y, g:ia' ) . ' UTC' );
wp_send_json_success( array( 'flushed' => 'batcache' ) );
}
public function pcm_purge_current_page_edge_cache() {
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['nonce'] ) ), 'pcm_nonce' ) ) {
die( json_encode( array( 'Security Error!', 'error', 'alert' ) ) );
}
$path = urldecode( esc_url_raw( wp_unslash( $_GET['path'] ) ) );
if ( preg_match( '/\.{2,}/', $path ) ) {
die( 'Suspected Directory Traversal Attack' );
}
$url = get_home_url() . $path;
update_option( 'edge-cache-single-page-url-purged', $url );
if ( empty( $url ) ) return false;
if ( class_exists( 'Edge_Cache_Plugin' ) ) {
$edge_cache = Edge_Cache_Plugin::get_instance();
$result = $edge_cache->purge_uris_now( array( $url ) );
update_option( 'single-page-edge-cache-purge-time-stamp', gmdate( 'j M Y, g:ia' ) . ' UTC' );
wp_send_json_success( array( 'flushed' => 'edge-cache' ) );
}
wp_send_json_error( array( 'reason' => 'Edge_Cache_Plugin not available' ) );
}
public function load_toolbar_css() {
wp_enqueue_style( 'pressable-cache-management-toolbar',
plugin_dir_url( dirname( __FILE__ ) ) . 'public/css/toolbar.css',
array(), time(), 'all' );
}
public function load_toolbar_js() {
wp_enqueue_script( 'pcm-toolbar',
plugin_dir_url( dirname( __FILE__ ) ) . 'public/js/toolbar.js',
array( 'jquery' ), time(), true );
// Pass nonce and edge-cache state to JS for BOTH admin and frontend contexts.
// pcm_nonce from print_my_inline_script() only runs on wp_footer (frontend).
// wp_localize_script covers both admin and frontend reliably.
$edge_on = ( get_option('edge-cache-enabled') === 'enabled' ) ? '1' : '0';
wp_localize_script( 'pcm-toolbar', 'pcmToolbarData', array(
'nonce' => wp_create_nonce( 'pcm_nonce' ),
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'flushEdge'=> $edge_on,
) );
}
public function load_remove_branding_toolbar_js() {
wp_enqueue_script( 'pcm-toolbar-branding',
plugin_dir_url( dirname( __FILE__ ) ) . 'public/js/toolbar_remove_branding.js',
array( 'jquery' ), time(), true );
}
public function print_my_inline_script() { ?>
<script>
var pcm_ajaxurl = "<?php echo esc_url( admin_url('admin-ajax.php') ); ?>";
var pcm_nonce = "<?php echo wp_create_nonce('pcm_nonce'); ?>";
</script>
<?php
}
public function pcm_toolbar_for_page_preview() {
global $wp_admin_bar;
$branding_opts = get_option( 'remove_pressable_branding_tab_options' );
$branding_disabled = $branding_opts && 'disable' == $branding_opts['branding_on_off_radio_button'];
$edge_cache_on = ( get_option('edge-cache-enabled') === 'enabled' );
// Single label: include Edge Cache in the title when it is active
$flush_label = $edge_cache_on
? __( 'Flush Cache for This Page', 'pressable_cache_management' )
: __( 'Flush Batcache for This Page', 'pressable_cache_management' );
if ( $branding_disabled ) {
$parent = 'pcm-toolbar-parent-remove-branding';
$wp_admin_bar->add_node( array(
'id' => $parent,
'title' => __( 'Flush Cache', 'pressable_cache_management' ),
'class' => 'pcm-toolbar-child',
));
// Combined item — JS fires both Batcache + Edge Cache flushes in sequence
$wp_admin_bar->add_menu( array(
'id' => 'pcm-toolbar-parent-remove-branding-flush-cache-of-this-page',
'title' => $flush_label,
'parent' => $parent,
'meta' => array( 'class' => 'pcm-toolbar-child' ),
));
} else {
$parent = 'pcm-toolbar-parent';
$wp_admin_bar->add_node( array(
'id' => $parent,
'title' => __( 'Flush Cache', 'pressable_cache_management' ),
));
// Combined item — JS fires both Batcache + Edge Cache flushes in sequence
$wp_admin_bar->add_menu( array(
'id' => 'pcm-toolbar-parent-flush-cache-of-this-page',
'title' => $flush_label,
'parent' => $parent,
'meta' => array( 'class' => 'pcm-toolbar-child' ),
));
}
}
// Empty admin-side toolbar (handled by object_cache_admin_bar.php)
public function PcmFlushCacheAdminbar() {}
}
}
add_action( 'init', 'pcm_show_flush_cache_option_for_single_page' );
function pcm_show_flush_cache_option_for_single_page() {
$current_user = wp_get_current_user();
if ( current_user_can('manage_woocommerce') || current_user_can('administrator') ) {
$toolbar = new PcmFlushCacheAdminbar();
$toolbar->add();
} else {
if ( ! function_exists('load_admin_toolbar_css') ) {
function load_admin_toolbar_css() {
wp_enqueue_style( 'pressable-cache-management-toolbar',
plugin_dir_url( dirname( __FILE__ ) ) . 'public/css/toolbar.css',
array(), time(), 'all' );
}
}
add_action( 'init', 'load_admin_toolbar_css' );
}
}
}
@@ -0,0 +1,240 @@
<?php
/**
* Pressable Cache Management - Admin Bar Cache Buttons
* Branded popup notices matching plugin theme (#dd3a03, #040024, #03fcc2)
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// ─── Branded modal popup (replaces browser alert) ─────────────────────────
add_action( 'admin_footer', 'pcm_abar_modal_html' );
function pcm_abar_modal_html() {
if ( ! pcm_abar_can_view() ) return;
?>
<div id="pcm-modal-overlay" style="display:none;position:fixed;inset:0;background:rgba(4,0,36,.45);z-index:999999;align-items:center;justify-content:center;">
<div style="background:#fff;border-radius:12px;padding:28px 32px;max-width:440px;width:90%;box-shadow:0 8px 40px rgba(4,0,36,.18);font-family:sans-serif;position:relative;">
<div style="width:48px;height:4px;background:#03fcc2;border-radius:4px;margin-bottom:18px;"></div>
<div id="pcm-modal-message" style="font-size:14px;color:#040024;line-height:1.6;white-space:pre-line;margin-bottom:22px;"></div>
<button id="pcm-modal-ok" style="background:#dd3a03;color:#fff;border:none;border-radius:8px;padding:10px 28px;font-size:13.5px;font-weight:700;cursor:pointer;font-family:sans-serif;letter-spacing:.4px;transition:background .2s;">OK</button>
</div>
</div>
<script>
(function($){
function pcmShowModal(msg) {
$('#pcm-modal-message').text(msg);
$('#pcm-modal-overlay').css('display','flex');
}
$('#pcm-modal-ok, #pcm-modal-overlay').on('click', function(e){
if (e.target === this) $('#pcm-modal-overlay').hide();
});
$('#pcm-modal-ok').hover(
function(){ $(this).css('background','#b82f00'); },
function(){ $(this).css('background','#dd3a03'); }
);
window.pcmShowModal = pcmShowModal;
})(jQuery);
</script>
<?php
}
// ─── JS: Flush Object Cache ────────────────────────────────────────────────
add_action( 'admin_footer', 'pcm_abar_object_js' );
function pcm_abar_object_js() { ?>
<script>
jQuery(document).ready(function($){
$('li#wp-admin-bar-cache-purge .ab-item').on('click', function(e){
e.preventDefault();
$.post(ajaxurl, { action: 'flush_pressable_cache' }, function(r){
window.pcmShowModal(r.trim());
});
});
});
</script>
<?php }
// ─── JS: Purge Edge Cache ──────────────────────────────────────────────────
add_action( 'admin_footer', 'pcm_abar_edge_js' );
function pcm_abar_edge_js() { ?>
<script>
jQuery(document).ready(function($){
$('li#wp-admin-bar-edge-purge .ab-item').on('click', function(e){
e.preventDefault();
$.ajax({ url: ajaxurl, type: 'POST', data: { action: 'pressable_edge_cache_purge' },
success: function(r){ window.pcmShowModal(r.trim()); },
error: function(){ window.pcmShowModal('An error occurred during the Edge Cache purge request.'); }
});
});
});
</script>
<?php }
// ─── JS: Flush Object + Edge Cache ────────────────────────────────────────
add_action( 'admin_footer', 'pcm_abar_combined_js' );
function pcm_abar_combined_js() { ?>
<script>
jQuery(document).ready(function($){
$('li#wp-admin-bar-combined-cache-purge .ab-item').on('click', function(e){
e.preventDefault();
$.ajax({ url: ajaxurl, type: 'POST', data: { action: 'flush_combined_cache' },
success: function(r){ window.pcmShowModal(r.trim()); },
error: function(){ window.pcmShowModal('An error occurred during the combined cache flush.'); }
});
});
});
</script>
<?php }
// ─── Enqueue toolbar CSS ───────────────────────────────────────────────────
function pcm_abar_load_css() {
wp_enqueue_style( 'pressable-cache-management-toolbar',
plugin_dir_url( dirname( __FILE__ ) ) . 'public/css/toolbar.css',
array(), time(), 'all' );
}
add_action( 'init', 'pcm_abar_load_css' );
// ─── AJAX Hooks ───────────────────────────────────────────────────────────
add_action( 'wp_ajax_flush_pressable_cache', 'pcm_abar_flush_object_callback' );
add_action( 'wp_ajax_pressable_edge_cache_purge', 'pcm_abar_purge_edge_callback' );
add_action( 'wp_ajax_flush_combined_cache', 'pcm_abar_flush_combined_callback' );
function pcm_abar_flush_object_callback() {
if ( ! current_user_can('administrator') && ! current_user_can('editor') && ! current_user_can('manage_woocommerce') ) {
echo 'You do not have permission to flush the Object Cache.';
wp_die();
}
wp_cache_flush();
if ( function_exists('batcache_clear_cache') ) batcache_clear_cache();
update_option( 'flush-obj-cache-time-stamp', gmdate('j M Y, g:ia') . ' UTC' );
echo esc_html__( 'Object Cache Flushed successfully.', 'pressable_cache_management' );
wp_die();
}
function pcm_abar_purge_edge_callback() {
if ( ! current_user_can('administrator') && ! current_user_can('editor') && ! current_user_can('manage_woocommerce') ) {
echo 'You do not have permission to purge the Edge Cache.';
wp_die();
}
if ( ! class_exists('Edge_Cache_Plugin') ) {
echo esc_html__( 'Error: Edge Cache Plugin is not active. Purge aborted.', 'pressable_cache_management' );
wp_die();
}
$edge_cache = Edge_Cache_Plugin::get_instance();
if ( ! method_exists( $edge_cache, 'purge_domain_now' ) ) {
echo esc_html__( 'Error: Edge Cache purge method unavailable.', 'pressable_cache_management' );
wp_die();
}
$result = $edge_cache->purge_domain_now( 'admin-bar-edge-purge' );
if ( $result ) {
update_option( 'edge-cache-purge-time-stamp', gmdate('j M Y, g:ia') . ' UTC' );
echo esc_html__( 'Edge Cache purged successfully.', 'pressable_cache_management' );
} else {
echo esc_html__( 'Edge Cache purge failed. It might be disabled or rate-limited.', 'pressable_cache_management' );
}
wp_die();
}
function pcm_abar_flush_combined_callback() {
if ( ! current_user_can('administrator') && ! current_user_can('editor') && ! current_user_can('manage_woocommerce') ) {
echo 'You do not have permission to flush the combined cache.';
wp_die();
}
$messages = array();
// Object cache
wp_cache_flush();
if ( function_exists('batcache_clear_cache') ) batcache_clear_cache();
update_option( 'flush-obj-cache-time-stamp', gmdate('j M Y, g:ia') . ' UTC' );
$messages[] = esc_html__( 'Object Cache Flushed successfully.', 'pressable_cache_management' );
// Edge cache
if ( class_exists('Edge_Cache_Plugin') ) {
$edge_cache = Edge_Cache_Plugin::get_instance();
if ( method_exists( $edge_cache, 'purge_domain_now' ) ) {
$result = $edge_cache->purge_domain_now( 'admin-bar-combined-purge' );
if ( $result ) {
update_option( 'edge-cache-purge-time-stamp', gmdate('j M Y, g:ia') . ' UTC' );
$messages[] = esc_html__( 'Edge Cache Purged successfully.', 'pressable_cache_management' );
} else {
$messages[] = esc_html__( 'Edge Cache purge failed (possibly disabled or rate-limited).', 'pressable_cache_management' );
}
} else {
$messages[] = esc_html__( 'Edge Cache Plugin active, but purge method unavailable.', 'pressable_cache_management' );
}
} else {
$messages[] = esc_html__( 'Edge Cache Plugin not found; skipping Edge Cache purge.', 'pressable_cache_management' );
}
echo '- ' . implode( "\n- ", $messages );
wp_die();
}
// ─── Permission check ─────────────────────────────────────────────────────
if ( ! function_exists('pcm_abar_can_view') ) {
function pcm_abar_can_view() {
return current_user_can('administrator') || current_user_can('editor') || current_user_can('manage_woocommerce');
}
}
// ─── Admin Bar Menu ───────────────────────────────────────────────────────
add_action( 'admin_bar_menu', 'pcm_abar_add_menu', 100 );
function pcm_abar_add_menu( $wp_admin_bar ) {
if ( is_network_admin() || ! pcm_abar_can_view() ) return;
$branding_opts = get_option('remove_pressable_branding_tab_options');
$branding_disabled = $branding_opts && 'disable' == $branding_opts['branding_on_off_radio_button'];
$parent_id = $branding_disabled ? 'pcm-wp-admin-toolbar-parent-remove-branding' : 'pcm-wp-admin-toolbar-parent';
$parent_title = $branding_disabled ? 'Cache Control' : 'Cache Management';
// Detect Edge Cache state
$edge_cache_is_enabled = false;
if ( class_exists('Edge_Cache_Plugin') ) {
$ec = Edge_Cache_Plugin::get_instance();
$server_status = method_exists($ec,'get_ec_status') ? $ec->get_ec_status() : null;
if ( defined('Edge_Cache_Plugin::EC_ENABLED') && $server_status === Edge_Cache_Plugin::EC_ENABLED ) {
$edge_cache_is_enabled = true;
} elseif ( get_option('edge-cache-enabled') === 'enabled' ) {
$edge_cache_is_enabled = true;
}
}
// Parent
$wp_admin_bar->add_node( array( 'id' => $parent_id, 'title' => $parent_title ) );
// Flush Object Cache
$wp_admin_bar->add_menu( array(
'id' => 'cache-purge',
'title' => __( 'Flush Object Cache', 'pressable_cache_management' ),
'parent' => $parent_id,
'meta' => array( 'class' => 'pcm-wp-admin-toolbar-child' ),
));
// Edge Cache options (only if enabled)
if ( $edge_cache_is_enabled ) {
$wp_admin_bar->add_menu( array(
'id' => 'edge-purge',
'title' => __( 'Purge Edge Cache', 'pressable_cache_management' ),
'parent' => $parent_id,
'meta' => array( 'class' => 'pcm-wp-admin-toolbar-child' ),
));
$wp_admin_bar->add_menu( array(
'id' => 'combined-cache-purge',
'title' => __( 'Flush Object & Edge Cache', 'pressable_cache_management' ),
'parent' => $parent_id,
'meta' => array( 'class' => 'pcm-wp-admin-toolbar-child' ),
));
}
// Cache Settings (admin only)
if ( current_user_can('administrator') ) {
$wp_admin_bar->add_menu( array(
'id' => 'settings',
'title' => __( 'Cache Settings', 'pressable_cache_management' ),
'parent' => $parent_id,
'href' => admin_url('admin.php?page=pressable_cache_management'),
'meta' => array( 'class' => 'pcm-wp-admin-toolbar-child' ),
));
}
}
@@ -0,0 +1,486 @@
<?php
/*
* Plugin name: Batcache Manager
* Plugin URI: http://www.github.com/spacedmonkey/batcache-manager
* Description: Cache clearing for batcache
* Author: Jonathan Harris
* Author URI: http://www.jonathandavidharris.co.uk
* Version: 2.0.2
*/
/**
* Class Batcache_Manager
*/
class Batcache_Manager {
/**
* List of feeds
*
* @since 2.0.0
*
* @var array
*/
private $feeds = array( 'rss', 'rss2', 'rdf', 'atom' );
/**
* List of links to process
*
* @since 2.0.0
*
* @var array
*/
private $links = array();
/**
* Instance of this class.
*
* @since 2.0.0
*
* @var object
*/
protected static $instance = null;
/**
*
*/
private function __construct() {
global $batcache, $wp_object_cache;
// Do not load if our advanced-cache.php isn't loaded
if ( ! isset( $batcache ) || ! is_object( $batcache ) || ! method_exists( $wp_object_cache, 'incr' ) ) {
return;
}
$batcache->configure_groups();
// Posts
add_action( 'clean_post_cache', array( $this, 'action_clean_post_cache' ), 15 );
// Terms
add_action( 'clean_term_cache', array( $this, 'action_clean_term_cache' ), 10, 3 );
//Comments
add_action( 'clean_comment_cache', array( $this, 'action_update_comment' ) ); // Only supported in 4.5
add_action( 'comment_post', array( $this, 'action_update_comment' ) );
add_action( 'wp_set_comment_status', array( $this, 'action_update_comment' ) );
add_action( 'edit_comment', array( $this, 'action_update_comment' ) );
// Users
add_action( 'clean_user_cache', array( $this, 'action_update_user' ) );
add_action( 'profile_update', array( $this, 'action_update_user' ) );
// Widgets
add_filter( 'widget_update_callback', array( $this, 'action_update_widget' ), 50 );
// Customiser
add_action( 'customize_save_after', array( $this, 'flush_all' ) );
// Theme
add_action( 'switch_theme', array( $this, 'flush_all' ) );
// Nav
add_action( 'wp_update_nav_menu', array( $this, 'flush_all' ) );
// Add site aliases to list of links
add_filter( 'batcache_manager_links', array( $this, 'add_site_alias' ) );
// Do the flush of the urls on shutdown
add_action( 'shutdown', array( $this, 'clear_urls' ) );
}
/**
* Return an instance of this class.
*
* @since 2.0.0
*
* @return object A single instance of this class.
*/
public static function get_instance() {
// If the single instance hasn't been set, set it now.
if ( null == self::$instance ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Determines whether a post type is considered "viewable".
*
* For built-in post types such as posts and pages, the 'public' value will be evaluated.
* For all others, the 'publicly_queryable' value will be used.
*
*
* @param string $post_type Post type.
*
* @return bool Whether the post type should be considered viewable.
*/
public function is_post_type_viewable( $post_type ) {
$post_type_object = get_post_type_object( $post_type );
if ( empty( $post_type_object ) ) {
return false;
}
return $post_type_object->publicly_queryable || ( $post_type_object->_builtin && $post_type_object->public );
}
/**
* Whether the taxonomy object is public.
*
* Checks to make sure that the taxonomy is an object first. Then Gets the
* object, and finally returns the public value in the object.
*
* A false return value might also mean that the taxonomy does not exist.
*
* @since 2.0.0
*
* @param string $taxonomy Name of taxonomy object.
*
* @return bool Whether the taxonomy is public.
*/
function is_taxonomy_viewable( $taxonomy ) {
if ( ! taxonomy_exists( $taxonomy ) ) {
return false;
}
$taxonomy = get_taxonomy( $taxonomy );
return $taxonomy->public;
}
/**
* Clear post on post update
*
* @param $post_id
*/
public function action_clean_post_cache( $post_id ) {
$post = get_post( $post_id );
if ( $post && $post->post_type && ! $this->is_post_type_viewable( $post->post_type ) || ! in_array( get_post_status( $post_id ), array( 'publish', 'trash' ) ) ) {
return;
}
// Only flush the permalink of the specific post that changed.
// Date archives, author archives, feeds, and the homepage are intentionally
// NOT flushed here — those shared URLs should only be invalidated on a
// full manual flush, not on every individual page save.
$permalink = get_permalink( $post );
if ( ! empty( $permalink ) ) {
$this->links[] = $permalink;
}
// --- START OF MODIFIED CODE ---
// Check if the updated post is a WooCommerce product
if ( 'product' === $post->post_type ) {
$product_url = get_permalink( $post );
// 1. Flush the specific product URL (Batcache)
self::clear_url( $product_url );
// 2. Store the product URL in the option table
update_option( 'edge-cache-single-page-url-purged', $product_url );
// 3. Purge Edge Cache for the specific URL
if (class_exists('Edge_Cache_Plugin')) {
// Set the default timezone to UTC before calling date()
$timezone_backup = date_default_timezone_get();
date_default_timezone_set('UTC');
$edge_cache = Edge_Cache_Plugin::get_instance();
$urls = array($product_url);
// Use the correct method to purge URIs
$result = $edge_cache->purge_uris_now($urls);
// Save time stamp to database if edge cache is purged for particular page
$edge_cache_purge_time = date('jS F Y g:ia') . "\nUTC";
update_option('single-page-edge-cache-purge-time-stamp', $edge_cache_purge_time);
// Restore the original timezone
date_default_timezone_set($timezone_backup);
}
}
// --- END OF MODIFIED CODE ---
}
/**
* Clear terms on term update
*
* @param array $ids Single or list of Term IDs.
* @param string $taxonomy
* @param bool $clean_taxonomy Optional. Whether to clean taxonomy wide caches (true), or just individual
* term object caches (false). Default true. Only support in WP 4.5
*/
public function action_clean_term_cache( $ids, $taxonomy, $clean_taxonomy = true ) {
// Clear taxonomy global caches. If false, lets not both.
if ( ! $clean_taxonomy ) {
return;
}
// If not a public taxonomy, don't clear caches.
if ( ! $this->is_taxonomy_viewable( $taxonomy ) ) {
return;
}
foreach ( $ids as $term ) {
$this->setup_term_urls( $term, $taxonomy );
}
}
/**
* Clear post page on comment update
*
* @param $comment_id
*/
public function action_update_comment( $comment_id ) {
$comment = get_comment( $comment_id );
$post_id = $comment->comment_post_ID;
$this->setup_post_urls( $post_id );
$this->setup_post_comment_urls( $post_id, $comment_id );
}
/**
* Clear author links on update user.
*
* @param $user_id
*/
public function action_update_user( $user_id ) {
$this->setup_author_urls( $user_id );
}
public function flush_all() {
if ( function_exists( 'batcache_flush_all' ) ) {
batcache_flush_all();
}
}
/**
* Flush all of the caches when a widget is updated.
*
* @param array $instance The current widget instance's settings.
*
* @return array $instance
*/
public function action_update_widget( $instance ) {
$this->flush_all();
return $instance;
}
/**
* Get term archive and feed links for each term
*
* @param $term
* @param $taxonomy
*/
public function setup_term_urls( $term, $taxonomy ) {
$term_link = get_term_link( $term, $taxonomy );
if ( ! is_wp_error( $term_link ) ) {
$this->links[] = $term_link;
}
foreach ( $this->feeds as $feed ) {
$term_link_feed = get_term_feed_link( $term, $taxonomy, $feed );
if ( $term_link_feed ) {
$this->links[] = $term_link_feed;
}
}
$taxonomy_object = get_taxonomy( $taxonomy );
if ( $taxonomy_object->show_in_rest && $taxonomy_object->rest_base ) {
$base = $taxonomy_object->rest_base;
$this->links[] = get_rest_url( null, '/wp/v2/' . $base );
$this->links[] = get_rest_url( null, '/wp/v2/' . $base . '/'. $term );
}
}
/**
* Home page / blog page and feed links
*/
public function setup_site_urls() {
if ( get_option( 'show_on_front' ) == 'page' ) {
$this->links[] = get_permalink( get_option( 'page_for_posts' ) );
}
$this->links[] = home_url( '/' );
foreach ( $this->feeds as $feed ) {
$this->links[] = get_feed_link( $feed );
}
}
/**
* Get permalink, date archives and custom post type links
*
* @param $post
*/
public function setup_post_urls( $post ) {
$post = get_post( $post );
$this->links[] = get_permalink( $post );
if ( $post->post_type == 'post' ) {
$year = get_the_time( "Y", $post );
$month = get_the_time( "m", $post );
$day = get_the_time( "d", $post );
$this->links[] = get_year_link( $year );
$this->links[] = get_month_link( $year, $month );
$this->links[] = get_day_link( $year, $month, $day );
} else if ( ! in_array( $post->post_type, get_post_types( array( 'public' => true ) ) ) ) {
if ( $archive_link = get_post_type_archive_link( $post->post_type ) ) {
$this->links[] = $archive_link;
}
foreach ( $this->feeds as $feed ) {
if ( $archive_link_feed = get_post_type_archive_feed_link( $post->post_type, $feed ) ) {
$this->links[] = $archive_link_feed;
}
}
}
$post_type = get_post_type_object( $post->post_type );
if ( $post_type->show_in_rest && $post_type->rest_base ) {
$base = $post_type->rest_base;
$this->links[] = get_rest_url( null, '/wp/v2/' . $base );
$this->links[] = get_rest_url( null, '/wp/v2/' . $base . '/'. $post->ID );
}
}
/**
* Author profile and feed links
*
* @param $author_id
*/
public function setup_author_urls( $author_id ) {
$this->links[] = get_author_posts_url( $author_id );
foreach ( $this->feeds as $feed ) {
$this->links[] = get_author_feed_link( $author_id, $feed );
}
$this->links[] = get_rest_url( null, '/wp/v2/users' );
$this->links[] = get_rest_url( null, '/wp/v2/users/' . $author_id );
}
/**
* Get feed urls for comments for single posts
*
* @param $post_id
*/
public function setup_post_comment_urls( $post_id, $comment_id = 0 ) {
foreach ( $this->feeds as $feed ) {
$this->links[] = get_post_comments_feed_link( $post_id, $feed );
}
foreach ( $this->feeds as $feed ) {
$this->links[] = get_feed_link( "comments_" . $feed );
}
$this->links[] = get_rest_url( null, '/wp/v2/comments' );
$this->links[] = get_rest_url( null, '/wp/v2/comments/' . $comment_id );
}
/**
* Work around for those using Domain mapping or have CMS on different url.
*
* @param $links
*/
public function add_site_alias( $links ) {
$home = parse_url( home_url(), PHP_URL_HOST );
$compare_urls = array(
parse_url( get_option( 'home' ), PHP_URL_HOST ),
parse_url( get_option( 'siteurl' ), PHP_URL_HOST ),
parse_url( site_url(), PHP_URL_HOST )
);
// Compare home, site urls with filtered home url
foreach ( $compare_urls as $compare_url ) {
if ( $compare_url != $home ) {
foreach ( $links as $url ) {
$links[] = str_replace( $home, $compare_url, $url );
}
}
}
return $links;
}
/**
* Loop around all urls and clear
*/
public function clear_urls() {
if ( empty ( $this->get_links() ) ) {
return;
}
foreach ( $this->get_links() as $url ) {
self::clear_url( $url );
}
// Clear out links
$this->links = array();
// --- START OF MODIFIED CODE ---
// Set the default timezone to UTC before calling date()
$timezone_backup = date_default_timezone_get();
date_default_timezone_set('UTC');
// Update the timestamp option with the specified format
$batcache_flush_time = date('jS F Y g:ia') . "\nUTC";
update_option( 'flush-object-cache-for-single-page-time-stamp', $batcache_flush_time );
// Restore the original timezone
date_default_timezone_set($timezone_backup);
// --- END OF MODIFIED CODE ---
}
/**
*
* @param $url
*
* @return bool|false|int
*/
public static function clear_url( $url ) {
global $batcache, $wp_object_cache;
$url = apply_filters( 'batcache_manager_link', $url );
if ( empty( $url ) ) {
return false;
}
do_action( 'batcache_manager_before_flush', $url );
// Force to http
$url = set_url_scheme( $url, 'http' );
$url_key = md5( $url );
wp_cache_add( "{$url_key}_version", 0, $batcache->group );
$retval = wp_cache_incr( "{$url_key}_version", 1, $batcache->group );
// $batcache_no_remote_group_key = array_search( $batcache->group, (array) $wp_object_cache->no_remote_groups );
$batcache_no_remote_group_key = property_exists($wp_object_cache, 'no_remote_groups') ? array_search( $batcache->group, (array) $wp_object_cache->no_remote_groups ) : false;
if ( false !== $batcache_no_remote_group_key ) {
// The *_version key needs to be replicated remotely, otherwise invalidation won't work.
// The race condition here should be acceptable.
unset( $wp_object_cache->no_remote_groups[ $batcache_no_remote_group_key ] );
$retval = wp_cache_set( "{$url_key}_version", $retval, $batcache->group );
$wp_object_cache->no_remote_groups[ $batcache_no_remote_group_key ] = $batcache->group;
}
do_action( 'batcache_manager_after_flush', $url, $retval );
return $retval;
}
/**
* Filter links
*
* @return array
*/
public function get_links() {
$this->links = apply_filters( 'batcache_manager_links', $this->links );
return array_unique( $this->links );
}
}
global $batcache_manager;
$batcache_manager = Batcache_Manager::get_instance();
@@ -0,0 +1,64 @@
<?php // Pressable Cache Management mu-plugins index
// disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
/*****
* This file references the Pressable Cache Management mu-plugins
* https://wordpress.org/documentation/article/must-use-plugins/
******/
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_extend_batcache.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_extend_batcache.php';
}
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/cdn_exclude_specific_file.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/cdn_exclude_specific_file.php';
}
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_cdn_extender.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_cdn_extender.php';
}
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/cdn_exclude_jpg_png_webp.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/cdn_exclude_jpg_png_webp.php';
}
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/cdn_exclude_css.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/cdn_exclude_css.php';
}
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/cdn_exclude_js_json.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/cdn_exclude_js_json.php';
}
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_exclude_font_files_from_cdn.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_exclude_font_files_from_cdn.php';
}
// if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/batcache_manager.php')) {
// require WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_batcache_manager.php.php';
// }
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_cache_wpp_cookies_pages.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_cache_wpp_cookies_pages.php';
}
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_exclude_query_string_gclid.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_exclude_query_string_gclid.php';
}
if(file_exists(WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_exclude_pages_from_batcache.php')) {
require WPMU_PLUGIN_DIR.'/pressable-cache-management/pcm_exclude_pages_from_batcache.php';
}
@@ -0,0 +1,122 @@
<?php
/**
* Pressable Edge Cache Purge Functionality
* Mirrors the official repo's purge-edge-cache.php exactly,
* with branded admin notices applied.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( isset( $_POST['purge_edge_cache_nonce'] ) ) {
if ( ! function_exists( 'pcm_pressable_edge_cache_purge_local' ) ) {
function pcm_pressable_edge_cache_purge_local() {
// 1. Verify nonce + capability
if (
! isset( $_POST['purge_edge_cache_nonce'] ) ||
! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['purge_edge_cache_nonce'] ) ), 'purge_edge_cache_nonce' ) ||
! current_user_can( 'manage_options' )
) {
return;
}
// 2. Ensure Edge Cache Plugin exists
if ( ! class_exists( 'Edge_Cache_Plugin' ) ) {
add_action( 'admin_notices', function() {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( esc_html__( 'Error: Edge Cache Plugin is not active.', 'pressable_cache_management' ), '#dd3a03' );
} else {
printf( '<div class="notice notice-error is-dismissible"><p>%s</p></div>', esc_html__( 'Error: Edge Cache Plugin is not active.', 'pressable_cache_management' ) );
}
});
return;
}
// 3. Get Edge Cache instance and current status
$edge_cache = Edge_Cache_Plugin::get_instance();
$status_method = method_exists( $edge_cache, 'get_ec_status' ) ? 'get_ec_status' : null;
$enable_method = method_exists( $edge_cache, 'enable_ec' ) ? 'enable_ec' : null;
$server_status = $status_method ? $edge_cache->$status_method() : null;
$auto_enabled = false;
// 4. If disabled, handle based on availability of enable_ec()
if ( Edge_Cache_Plugin::EC_DISABLED === $server_status ) {
if ( null !== $enable_method ) {
$enabled = $edge_cache->$enable_method();
if ( $enabled ) {
$auto_enabled = true;
sleep( 2 );
} else {
add_action( 'admin_notices', function() {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( esc_html__( 'Edge Cache was disabled and could not be auto-enabled. Purge aborted.', 'pressable_cache_management' ), '#dd3a03' );
} else {
printf( '<div class="notice notice-error is-dismissible"><p>%s</p></div>', esc_html__( 'Edge Cache was disabled and could not be auto-enabled. Purge aborted.', 'pressable_cache_management' ) );
}
});
return;
}
} else {
add_action( 'admin_notices', function() {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( esc_html__( 'Edge Cache is disabled on the server. Enable Edge Cache.', 'pressable_cache_management' ), '#f59e0b' );
} else {
printf( '<div class="notice notice-warning is-dismissible"><p>%s</p></div>', esc_html__( 'Edge Cache is disabled on the server. Enable Edge Cache.', 'pressable_cache_management' ) );
}
});
return;
}
}
// 5. Purge domain cache
$result = method_exists( $edge_cache, 'purge_domain_now' )
? $edge_cache->purge_domain_now( 'dashboard-auto-purge' )
: false;
if ( $result ) {
update_option( 'edge-cache-purge-time-stamp', gmdate( 'jS F Y g:ia' ) . ' UTC' );
// Clear the Batcache status transient so the badge re-probes immediately.
// Without this the badge can sit on 'active' for up to 90s after a purge
// even though Batcache is now in a transitional broken state.
do_action( 'pcm_after_edge_cache_purge' );
$message = $auto_enabled
? esc_html__( 'Edge Cache was disabled on the server. It has been automatically enabled and purged successfully.', 'pressable_cache_management' )
: esc_html__( 'Edge Cache purged successfully.', 'pressable_cache_management' );
add_action( 'admin_notices', function() use ( $message ) {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( $message, '#03fcc2' );
} else {
printf( '<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html( $message ) );
}
});
} else {
add_action( 'admin_notices', function() {
if ( function_exists( 'pcm_branded_notice' ) ) {
pcm_branded_notice( esc_html__( 'Edge Cache purge failed. Please try again.', 'pressable_cache_management' ), '#dd3a03' );
} else {
printf( '<div class="notice notice-error is-dismissible"><p>%s</p></div>', esc_html__( 'Edge Cache purge failed. Please try again.', 'pressable_cache_management' ) );
}
});
}
}
add_action( 'init', 'pcm_pressable_edge_cache_purge_local' );
}
}
// Prevent duplicate section callback declarations
if ( ! function_exists( 'pressable_cache_management_callback_section_edge_cache' ) ) {
function pressable_cache_management_callback_section_edge_cache() {
echo '<p>' . esc_html__( 'These settings enable you to manage Edge Cache.', 'pressable_cache_management' ) . '</p>';
}
}
if ( ! function_exists( 'pressable_cache_management_callback_section_cache' ) ) {
function pressable_cache_management_callback_section_cache() {
echo '<p>' . esc_html__( 'These settings enable you to manage the object cache.', 'pressable_cache_management' ) . '</p>';
}
}
@@ -0,0 +1,63 @@
<?php //Pressable Cache Management - Custom function to turn on/off Pressable branding
/******************************
* Show branding Option
*******************************/
$pressable_branding = false;
$hide_pressable_branding_tab_options = get_option('remove_pressable_branding_tab_options');
//Check if options are set before processing
if (isset($hide_pressable_branding_tab_options['branding_on_off_radio_button']) && !empty($hide_pressable_branding_tab_options['branding_on_off_radio_button']))
{
$hide_pressable_branding_tab_options = sanitize_text_field($hide_pressable_branding_tab_options['branding_on_off_radio_button']);
}
//Set radion button state to defualt
if ('enable' === $hide_pressable_branding_tab_options)
{
$hide_pressable_branding_tab_options = get_option('remove_pressable_branding_tab_options');
// echo 'Show Branding';
//run your functions here if radio button is enabled
}
/******************************
* Hide branding Option
*******************************/
else
{
$pressable_branding = false;
$pressable_branding = get_option('remove_pressable_branding_tab_options');
//Check if options are set before processing
if (isset($hide_pressable_branding_tab_options['branding_on_off_radio_button']) && !empty($hide_pressable_branding_tab_options['branding_on_off_radio_button']))
{
$hide_pressable_branding_tab_options = sanitize_text_field($hide_pressable_branding_tab_options['branding_on_off_radio_button']);
}
//Set radio button state to defualt
if ('disable' === $hide_pressable_branding_tab_options)
{
$hide_pressable_branding_tab_options = get_option('remove_pressable_branding_tab_options');
// echo 'Hide Branding';
//run your functions here if radio button is disbaled
}
}
@@ -0,0 +1,146 @@
<?php
/**
* Pressable Cache Management - Turn On/Off Edge Cache
* Based directly on the official repo's turn-on-off-edge-cache.php
* with branded admin notices applied.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// ─── Shared branded notice helper (defined once here) ──────────────────────
if ( ! function_exists( 'pcm_branded_notice' ) ) {
function pcm_branded_notice( $message, $border_color = '#03fcc2', $is_html = false ) {
$id = 'pcm-notice-' . substr( md5( $message . $border_color . microtime() ), 0, 8 );
$wrap = 'display:inline-flex;align-items:flex-start;justify-content:space-between;gap:16px;'
. 'border-left:4px solid ' . esc_attr( $border_color ) . ';background:#fff;'
. 'border-radius:0 8px 8px 0;padding:14px 18px;'
. 'box-shadow:0 2px 8px rgba(4,0,36,.07);margin:10px 20px 10px 0;font-family:sans-serif;'
. 'min-width:260px;max-width:520px;';
$btn = 'background:none;border:none;cursor:pointer;color:#94a3b8;font-size:18px;'
. 'line-height:1;padding:0;flex-shrink:0;margin-top:2px;';
echo '<div id="' . esc_attr( $id ) . '" style="' . $wrap . '">';
echo '<div style="flex:1;">';
if ( $is_html ) {
echo $message; // caller already escaped
} else {
echo '<p style="margin:0;font-size:13px;color:#040024;">' . esc_html( $message ) . '</p>';
}
echo '</div>';
echo '<button type="button" onclick="document.getElementById(\'' . esc_js( $id ) . '\').remove();" style="' . $btn . '">&#x2297;</button>';
echo '</div>';
}
}
// ─── Notice: Edge Cache Enabled ─────────────────────────────────────────────
if ( ! function_exists( 'pressable_edge_cache_notice_success_enable' ) ) {
function pressable_edge_cache_notice_success_enable() {
$screen = get_current_screen();
if ( isset( $screen ) && 'toplevel_page_pressable_cache_management' !== $screen->id ) return;
$html = '<h3 style="margin:0 0 8px;font-size:14px;font-weight:700;color:#040024;">'
. '&#x1F389; ' . esc_html__( 'Edge Cache Enabled!', 'pressable_cache_management' ) . '</h3>';
$html .= '<p style="margin:0 0 6px;font-size:13px;color:#475569;">'
. esc_html__( 'Edge Cache provides performance improvements, particularly for Time to First Byte (TTFB), by serving page cache from the nearest server to your website visitors.', 'pressable_cache_management' )
. '</p>';
$html .= '<a href="https://pressable.com/knowledgebase/edge-cache/" target="_blank" '
. 'rel="noopener noreferrer" style="font-size:13px;color:#dd3a03;font-weight:600;text-decoration:none;">'
. esc_html__( 'Learn more about Edge Cache.', 'pressable_cache_management' ) . '</a>';
$nid = 'pcm-ec-enabled-' . substr( md5( microtime() ), 0, 8 );
$wrap = 'display:flex;align-items:flex-start;justify-content:space-between;gap:16px;'
. 'border-left:4px solid #03fcc2;background:#fff;'
. 'border-radius:0 8px 8px 0;padding:14px 18px;'
. 'box-shadow:0 2px 8px rgba(4,0,36,.07);margin:10px 0;font-family:sans-serif;';
$btn = 'background:none;border:none;cursor:pointer;color:#94a3b8;font-size:18px;'
. 'line-height:1;padding:0;flex-shrink:0;margin-top:2px;';
echo '<div style="max-width:920px;margin:0 20px;">';
echo '<div id="' . esc_attr( $nid ) . '" style="' . $wrap . '">';
echo '<div style="flex:1;">' . $html . '</div>';
echo '<button type="button" onclick="document.getElementById(\'' . esc_js( $nid ) . '\').remove();" style="' . $btn . '">&#x2297;</button>';
echo '</div>';
echo '</div>';
}
}
// ─── Notice: Edge Cache Disabled ────────────────────────────────────────────
if ( ! function_exists( 'pressable_edge_cache_notice_success_disable' ) ) {
function pressable_edge_cache_notice_success_disable() {
$screen = get_current_screen();
if ( isset( $screen ) && 'toplevel_page_pressable_cache_management' !== $screen->id ) return;
pcm_branded_notice( esc_html__( 'Edge Cache Deactivated.', 'pressable_cache_management' ), '#03fcc2' );
}
}
// ─── Notice: Error ───────────────────────────────────────────────────────────
if ( ! function_exists( 'pcm_pressable_edge_cache_error_msg' ) ) {
function pcm_pressable_edge_cache_error_msg( $error_message = '' ) {
$screen = get_current_screen();
if ( isset( $screen ) && 'toplevel_page_pressable_cache_management' !== $screen->id ) return;
$msg = empty( $error_message )
? esc_html__( 'Something went wrong trying to communicate with the Edge Cache system. Try again.', 'pressable_cache_management' )
: esc_html( $error_message );
pcm_branded_notice( $msg, '#dd3a03' );
}
}
// ─── Enable Edge Cache (mirrors repo exactly, adds branded notices) ─────────
function pcm_pressable_enable_edge_cache() {
if ( isset( $_POST['enable_edge_cache_nonce'] ) &&
wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['enable_edge_cache_nonce'] ) ), 'enable_edge_cache_nonce' ) ) {
if ( class_exists( 'Edge_Cache_Plugin' ) ) {
$edge_cache = Edge_Cache_Plugin::get_instance();
$result = $edge_cache->query_ec_backend( 'on', array( 'wp_action' => 'manual_dashboard_set' ) );
if ( is_wp_error( $result ) ) {
update_option( 'edge-cache-status', 'Error' );
update_option( 'edge-cache-enabled', 'disabled' );
add_action( 'admin_notices', function() use ( $result ) {
pcm_pressable_edge_cache_error_msg( $result->get_error_message() );
});
} else {
update_option( 'edge-cache-status', 'Success' );
update_option( 'edge-cache-enabled', 'enabled' );
delete_transient( 'pcm_ec_status_cache' ); // force fresh status on next page load
add_action( 'admin_notices', 'pressable_edge_cache_notice_success_enable' );
}
} else {
add_action( 'admin_notices', function() {
pcm_pressable_edge_cache_error_msg( 'Required Edge Cache dependency is not available.' );
});
}
}
}
add_action( 'init', 'pcm_pressable_enable_edge_cache' );
// ─── Disable Edge Cache (mirrors repo exactly, adds branded notices) ────────
function pcm_pressable_disable_edge_cache() {
if ( isset( $_POST['disable_edge_cache_nonce'] ) &&
wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['disable_edge_cache_nonce'] ) ), 'disable_edge_cache_nonce' ) ) {
if ( class_exists( 'Edge_Cache_Plugin' ) ) {
$edge_cache = Edge_Cache_Plugin::get_instance();
$result = $edge_cache->query_ec_backend( 'off', array( 'wp_action' => 'manual_dashboard_set' ) );
if ( is_wp_error( $result ) ) {
update_option( 'edge-cache-status', 'Error' );
update_option( 'edge-cache-enabled', 'enabled' ); // stays enabled on failure
add_action( 'admin_notices', function() use ( $result ) {
pcm_pressable_edge_cache_error_msg( $result->get_error_message() );
});
} else {
update_option( 'edge-cache-status', 'Success' );
update_option( 'edge-cache-enabled', 'disabled' );
delete_transient( 'pcm_ec_status_cache' ); // force fresh status on next page load
add_action( 'admin_notices', 'pressable_edge_cache_notice_success_disable' );
}
} else {
add_action( 'admin_notices', function() {
pcm_pressable_edge_cache_error_msg( 'Required Edge Cache dependency is not available.' );
});
}
}
}
add_action( 'init', 'pcm_pressable_disable_edge_cache' );
@@ -0,0 +1,181 @@
<?php
function pressable_cache_extend()
{
}
// http://www.php.net/is_writable
function is_writeable_wp_config($path)
{
if ((defined('PHP_OS_FAMILY') && 'Windows' !== constant('PHP_OS_FAMILY')) || stristr(PHP_OS, 'DAR') || !stristr(PHP_OS, 'WIN'))
{
return is_writeable($path);
}
// PHP's is_writable does not work with Win32 NTFS
if ($path[strlen($path) - 1] == '/')
{ // recursively return a temporary file path
return is_writeable_wp_config($path . uniqid(mt_rand()) . '.tmp');
}
elseif (is_dir($path))
{
return is_writeable_wp_config($path . '/' . uniqid(mt_rand()) . '.tmp');
}
// check tmp file for read/write capabilities
$rm = file_exists($path);
$f = @fopen($path, 'a');
if ($f === false) return false;
fclose($f);
if (!$rm)
{
unlink($path);
}
return true;
}
// function wp_cache_setting( $field, $value ) {
// global $wp_cache_config_file;
// $GLOBALS[ $field ] = $value;
// if ( is_numeric( $value ) ) {
// return wp_config_file_replace_line( '^ *\$' . $field, "\$$field = $value;", $wp_cache_config_file );
// } elseif ( is_bool( $value ) ) {
// $output_value = $value === true ? 'true' : 'false';
// return wp_config_file_replace_line( '^ *\$' . $field, "\$$field = $output_value;", $wp_cache_config_file );
// } elseif ( is_object( $value ) || is_array( $value ) ) {
// $text = var_export( $value, true );
// $text = preg_replace( '/[\s]+/', ' ', $text );
// return wp_config_file_replace_line( '^ *\$' . $field, "\$$field = $text;", $wp_cache_config_file );
// } else {
// return wp_config_file_replace_line( '^ *\$' . $field, "\$$field = '$value';", $wp_cache_config_file );
// }
// }
function wp_config_file_replace_line($old, $new, $my_file)
{
if (@is_file($my_file) == false)
{
if (function_exists('set_transient'))
{
set_transient('wpsc_config_error', 'config_file_missing', 10);
}
return false;
}
if (!is_writeable_wp_config($my_file))
{
if (function_exists('set_transient'))
{
set_transient('wpsc_config_error', 'config_file_ro', 10);
}
trigger_error("Error: file $my_file is not writable.");
return false;
}
$found = false;
$loaded = false;
$c = 0;
$lines = array();
while (!$loaded)
{
$lines = file($my_file);
if (!empty($lines) && is_array($lines))
{
$loaded = true;
}
else
{
$c++;
if ($c > 100)
{
if (function_exists('set_transient'))
{
set_transient('wpsc_config_error', 'config_file_not_loaded', 10);
}
trigger_error("wp_config_file_replace_line: Error - file $my_file could not be loaded.");
return false;
}
}
}
foreach ((array)$lines as $line)
{
if (trim($new) != '' && trim($new) == trim($line))
{
pressable_cache_extend("wp_config_file_replace_line: setting not changed - $new");
return true;
}
elseif (preg_match("/$old/", $line))
{
pressable_cache_extend("wp_config_file_replace_line: changing line " . trim($line) . " to *$new*");
$found = true;
}
}
global $cache_path;
$tmp_config_filename = tempnam($GLOBALS['cache_path'], 'wpsc');
rename($tmp_config_filename, $tmp_config_filename . ".php");
$tmp_config_filename .= ".php";
pressable_cache_extend('wp_config_file_replace_line: writing to ' . $tmp_config_filename);
$fd = fopen($tmp_config_filename, 'w');
if (!$fd)
{
if (function_exists('set_transient'))
{
set_transient('wpsc_config_error', 'config_file_ro', 10);
}
trigger_error("wp_config_file_replace_line: Error - could not write to $my_file");
return false;
}
if ($found)
{
foreach ((array)$lines as $line)
{
if (!preg_match("/$old/", $line))
{
fputs($fd, $line);
}
elseif ($new != '')
{
fputs($fd, "$new\n");
}
}
}
else
{
$done = false;
foreach ((array)$lines as $line)
{
// if ( $done || ! preg_match( '/\brequire_once\b/i', $line ) ) {
if ($done || !preg_match('/\b(require_once)\b/', $line))
{
fputs($fd, $line);
}
else
{
//add fputs($fd, "$new\n"); here to write function above require_once
fputs($fd, $line);
//Write function at the button of require_once
fputs($fd, "$new\n");
$done = true;
}
}
}
fclose($fd);
rename($tmp_config_filename, $my_file);
pressable_cache_extend('wp_config_file_replace_line: moved ' . $tmp_config_filename . ' to ' . $my_file);
// if (function_exists("opcache_invalidate"))
// {
// @opcache_invalidate($my_file);
// }
if (function_exists("wp_opcache_invalidate"))
{
wp_opcache_invalidate($my_file);
}
return true;
}
@@ -0,0 +1 @@
<?php // Silence is golden
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 551 B

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="12pt" height="12pt" viewBox="0 0 12 12" version="1.1">
<g id="surface1">
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 0 0 L 0 0.0078125 L 0.0078125 0 Z M 0 0 "/>
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 6.140625 2.621094 L 4.355469 2.621094 L 4.355469 5.902344 L 6.140625 5.902344 C 7.5625 5.902344 7.902344 5.605469 7.902344 4.363281 L 7.902344 4.160156 C 7.898438 2.917969 7.554688 2.621094 6.140625 2.621094 Z M 6.140625 2.621094 "/>
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 0 0 L 0 12 L 7.691406 12 L 12.003906 7.683594 L 12.003906 0 Z M 8.984375 4.363281 C 8.984375 6.304688 8.253906 6.847656 6.136719 6.847656 L 4.355469 6.847656 L 4.355469 10.027344 C 4.363281 10.105469 4.339844 10.183594 4.285156 10.246094 C 4.226562 10.304688 4.152344 10.335938 4.074219 10.332031 C 3.824219 10.332031 3.289062 10.261719 3.289062 10.121094 L 3.289062 1.980469 C 3.289062 1.71875 3.417969 1.667969 3.585938 1.667969 L 6.140625 1.667969 C 8.296875 1.667969 8.996094 2.261719 8.996094 4.160156 Z M 8.984375 4.363281 "/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1 @@
<?php // Silence is golden
@@ -0,0 +1,91 @@
/**
* Pressable Cache Management - Flush cache for individual page column
* Branded modal popup replaces browser alert()
*/
if (window.attachEvent) {
window.attachEvent('onload', flush_object_cache_column_button_action);
} else {
if (window.onload) {
var curronload_1 = window.onload;
var newonload_1 = function(evt) { curronload_1(evt); flush_object_cache_column_button_action(evt); };
window.onload = newonload_1;
} else {
window.onload = flush_object_cache_column_button_action;
}
}
/* ── Branded modal (injected once) ─────────────────────────────────────── */
function pcmEnsureModal() {
if (document.getElementById('pcm-col-modal-overlay')) return;
var overlay = document.createElement('div');
overlay.id = 'pcm-col-modal-overlay';
overlay.style.cssText =
'display:none;position:fixed;inset:0;background:rgba(4,0,36,.45);'
+ 'z-index:999999;align-items:center;justify-content:center;';
overlay.innerHTML =
'<div style="background:#fff;border-radius:12px;padding:28px 32px;max-width:420px;width:90%;'
+ 'box-shadow:0 8px 40px rgba(4,0,36,.18);font-family:sans-serif;position:relative;">'
+ '<div style="width:48px;height:4px;background:#03fcc2;border-radius:4px;margin-bottom:16px;"></div>'
+ '<p id="pcm-col-modal-msg" style="margin:0 0 22px;font-size:14px;color:#040024;line-height:1.6;"></p>'
+ '<button id="pcm-col-modal-ok" style="background:#dd3a03;color:#fff;border:none;border-radius:8px;'
+ 'padding:10px 28px;font-size:13.5px;font-weight:700;cursor:pointer;font-family:sans-serif;'
+ 'transition:background .2s;">OK</button>'
+ '</div>';
document.body.appendChild(overlay);
overlay.style.display = 'flex'; overlay.style.display = 'none'; // force style parse
document.getElementById('pcm-col-modal-ok').addEventListener('click', function() {
overlay.style.display = 'none';
});
overlay.addEventListener('click', function(e) {
if (e.target === overlay) overlay.style.display = 'none';
});
// hover on OK button
var okBtn = document.getElementById('pcm-col-modal-ok');
okBtn.addEventListener('mouseenter', function() { okBtn.style.background = '#b82f00'; });
okBtn.addEventListener('mouseleave', function() { okBtn.style.background = '#dd3a03'; });
}
function pcmShowColumnModal(msg) {
pcmEnsureModal();
document.getElementById('pcm-col-modal-msg').textContent = msg;
document.getElementById('pcm-col-modal-overlay').style.display = 'flex';
}
function flush_object_cache_column_button_action() {
jQuery(document).ready(function($) {
$("a[id^='flush-object-cache-url']").on('click', function(e) {
e.preventDefault();
var post_id = $(e.currentTarget).attr('data-id');
var nonce = $(e.currentTarget).attr('data-nonce');
$('#flush-object-cache-url-' + post_id).css('cursor', 'wait');
$.ajax({
type: 'GET',
url: ajaxurl,
data: { action: 'pcm_flush_object_cache_column', id: post_id, nonce: nonce },
dataType: 'json',
cache: false,
success: function(data) {
$('#flush-object-cache-url-' + post_id).css('cursor', 'pointer');
if (typeof data.success !== 'undefined' && data.success === true) {
pcmShowColumnModal('Batcache flushed successfully \u2705');
} else {
pcmShowColumnModal('Something went wrong while trying to flush the cache for this page.');
}
},
error: function() {
$('#flush-object-cache-url-' + post_id).css('cursor', 'pointer');
pcmShowColumnModal('Request failed. Please try again.');
}
});
return false;
});
});
}
@@ -0,0 +1,89 @@
/**
* Pressable Cache Management — Toolbar JS
*
* Handles the combined "Flush Cache for This Page" admin bar button.
*
* Bug fixes vs previous version:
* 1. data-edge on <li> is unsupported by WP add_menu() meta — now uses pcmToolbarData.flushEdge
* passed via wp_localize_script() which works on both admin and frontend.
* 2. Event delegation now targets document.body and checks closest('li').attr('id') correctly,
* rather than querying a non-existent '#wp-admin-bar-*-default' wrapper selector.
* 3. pcm_nonce was only available on frontend (wp_footer). Now comes from pcmToolbarData.nonce
* which is always present via wp_localize_script.
* 4. AJAX handlers now return wp_send_json_success() so jQuery parses valid JSON.
*/
jQuery(document).ready(function($) {
// Ensure the loader overlay exists once
if ( !$('#revert-loader-toolbar').length ) {
$('body').append('<div id="revert-loader-toolbar"></div>');
}
// Resolve AJAX URL: prefer localized value, fall back to WP global
var ajaxUrl = ( typeof pcmToolbarData !== 'undefined' && pcmToolbarData.ajaxurl )
? pcmToolbarData.ajaxurl
: ( typeof ajaxurl !== 'undefined' ? ajaxurl : '' );
// Nonce: from wp_localize_script (works on both admin + frontend)
var nonce = ( typeof pcmToolbarData !== 'undefined' ) ? pcmToolbarData.nonce : '';
// Whether edge cache flush should also fire (passed from PHP via wp_localize_script)
var flushEdge = ( typeof pcmToolbarData !== 'undefined' && pcmToolbarData.flushEdge === '1' );
// ── IDs for both branding variants ───────────────────────────────────────
var combinedIds = [
'wp-admin-bar-pcm-toolbar-parent-flush-cache-of-this-page',
'wp-admin-bar-pcm-toolbar-parent-remove-branding-flush-cache-of-this-page',
];
// ── Fire a single AJAX GET, returns a jQuery deferred ────────────────────
function sendRequest( action ) {
return $.ajax({
type : 'GET',
url : ajaxUrl,
data : { action: action, path: window.location.pathname, nonce: nonce },
dataType: 'json',
cache : false,
});
}
// ── Sequential flush: Batcache first, then Edge Cache if active ───────────
function flushCurrentPage() {
$('#revert-loader-toolbar').show();
sendRequest('pcm_delete_current_page_cache')
.always(function() {
if ( flushEdge ) {
sendRequest('pcm_purge_current_page_edge_cache')
.always(done);
} else {
done();
}
});
}
function done() {
if ( typeof pcmCacheStatics !== 'undefined' ) {
pcmCacheStatics.update();
} else {
$('#revert-loader-toolbar').hide();
}
}
// ── Event delegation on body — catches clicks anywhere inside the <li> ───
// We delegate from body because the admin bar is injected late and the
// submenu UL wrapper varies by WP version. Matching by the <li> id directly
// is the most reliable approach and avoids the broken '-default' suffix.
$('body').on('click', function(e) {
// Walk up from the clicked element to find the nearest <li>
var $li = $(e.target).closest('li');
var id = $li.attr('id') || '';
if ( combinedIds.indexOf(id) !== -1 ) {
e.preventDefault();
flushCurrentPage();
}
});
});
@@ -0,0 +1,6 @@
/**
* Pressable Cache Management — toolbar_remove_branding.js
* This file is intentionally empty.
* The branding-off toolbar handler is now consolidated in toolbar.js
* (PCM_TOOLBAR_REMOVE_BRANDING object) to avoid duplicate AJAX calls.
*/
@@ -0,0 +1,672 @@
<?php //Pressable Cache Management - Settings Callbacks
// Disable direct file access
if (!defined('ABSPATH'))
{
exit;
}
/**********************************************
* Process all call-backs from the plugin forms
**********************************************/
// callback: object cache section section
function pressable_cache_management_callback_section_cache()
{
$remove_pressable_branding_tab_options = false;
$remove_pressable_branding_tab_options = get_option('remove_pressable_branding_tab_options');
if ($remove_pressable_branding_tab_options && 'disable' == $remove_pressable_branding_tab_options['branding_on_off_radio_button'])
{
}
else
{
//Pressable branding logo
echo '<div><img width="230" height="50" class="pressablecmlogo" src="' . plugin_dir_url(__FILE__) . '/assets/img/pressable-logo-primary.svg' . '" > </div>';
}
echo '<p>' . esc_html__('These settings enable you to manage the object cache.', 'pressable_cache_management') . '</p>';
// Check if the site uses Cloudflare
$response = wp_remote_get( get_site_url(), array( 'timeout' => 120 ) );
$headers = wp_remote_retrieve_headers( $response );
if ( isset( $headers['server'] ) && stripos( $headers['server'], 'cloudflare' ) !== false ) {
//Cloudflare is present in the website header.
// Check Batcache status
$site_url = get_site_url();
$response = wp_remote_get( $site_url, array( 'timeout' => 120 ) );
if ( is_wp_error( $response ) || strpos( $response['body'], 'batcache' ) === false ) {
echo '<p style="text-align:right; font-weight:bold">Batcache Status: Broken &#128308;</p>';
echo '<p style="text-align:right; font-size: smaller;">Disable Cloudflare proxy and caching and try again &#x1F7E0</p></br>';
} else {
echo '<p style="text-align:right; font-weight:bold">Batcache Status: OK &#x1F7E2;</p>';
}
} else {
//Cloudflare is not present in the website header.
// Check for Batcache
$site_url = get_site_url();
$response = wp_remote_get( $site_url, array( 'timeout' => 120 ) );
if ( is_wp_error( $response ) || strpos( $response['body'], 'batcache' ) === false ) {
echo '<p style="text-align:right; font-weight:bold">Batcache Status: Broken &#128308;</p></br>';
} else {
echo '<p style="text-align:right; font-weight:bold">Batcache Status: OK &#x1F7E2;</p>';
}
}
}
// RESTORED: This function is required by admin/settings-validate.php but was accidentally removed during cleanup.
function pressable_cache_management_options_radio_button()
{
return array(
'enable' => esc_html__('Enable CDN (Recommended)', 'pressable_cache_management') ,
'disable' => esc_html__('Disable CDN', 'pressable_cache_management')
);
}
// Removed redundant code related to CDN and old API flags
$pcm_con_auth = 'pressable_api_admin_notice__status';
// If the option already exists, update it to "OK"
if ( get_option( $pcm_con_auth ) !== false ) {
update_option( $pcm_con_auth, 'OK' );
} else {
add_option( $pcm_con_auth, 'OK' );
}
function pressable_cache_management_callback_section_edge_cache()
{
echo '<p>' . esc_html__('These settings enable you to manage Edge Cache settings.', 'pressable_cache_management') . '</p>';
}
// callback: Hide Pressable branding tab page description
function pressable_cache_management_callback_section_branding()
{
echo '<p>' . esc_html__('This setting allows you to show or hide the plugin branding.', 'pressable_cache_management') . '</p>';
}
/**
********************************
* Object Cache *
* Management Tab *
********************************
*
*/
// Flush object cache button
function pressable_cache_management_callback_field_button($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
echo '</form>';
echo '<form method="post" id="flush_object_cache_nonce">
<span id="flush_cache_button">
<input id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" type="submit" size="40" value="' . __('Flush Cache', 'pressable_cache_management') . '" class="flushcache"/><input type="hidden" name="flush_object_cache_nonce" value="' . wp_create_nonce('flush_object_cache_nonce') . '" <br/><label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . $label . '</label>
</span>
</form>';
echo '</br>';
//Display time stamp when object cache was last flushed
echo '<small><strong>Last flushed at: </strong></small> ' . wp_kses_post( get_option('flush-obj-cache-time-stamp') );
}
// Extend batcache checkbox
function pressable_cache_management_callback_field_extend_cache_checkbox($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$checked = isset($options[$id]) ? checked($options[$id], 1, false) : '';
echo '<div class="container">';
echo '<label class="switch">';
echo '<input type="checkbox" id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" value="1"' . $checked . ' />';
echo '<span class="slider round"></span>
</label>';
// echo '</br>';
echo '<label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';
}
// Flush site cache on Theme/Plugin update checkbox
function pressable_cache_management_callback_field_plugin_theme_update_checkbox($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$checked = isset($options[$id]) ? checked($options[$id], 1, false) : '';
echo '<div class="container">';
echo '<label class="switch">';
echo '<input type="checkbox" id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" value="1"' . $checked . ' />';
echo '<span class="slider round"></span>
</label>';
echo '<label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';
echo '</br>';
echo '</br>';
//Display time stamp when object cache was last flushed when theme plugin
echo '<small><strong>Last flushed at: </strong></small>' . wp_kses_post( get_option('flush-cache-theme-plugin-time-stamp') );
}
// Flush site object cache on page & post update checkbox
function pressable_cache_management_callback_field_page_edit_checkbox($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$checked = isset($options[$id]) ? checked($options[$id], 1, false) : '';
echo '<div class="container">';
echo '<label class="switch">';
echo '<input type="checkbox" id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" value="1"' . $checked . ' />';
echo '<span class="slider round"></span>
</label>';
// echo '</br>';
echo '<label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';
echo '</br>';
echo '</br>';
//Display time stamp when object cache was last flushed when page or post was updated
echo '<small><strong>Last flushed at: </strong></small>' . wp_kses_post( get_option('flush-cache-page-edit-time-stamp') );
}
// Flush site object cache when page, post and posttypes are updated checkbox
function pressable_cache_management_callback_field_page_post_delete_checkbox($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$checked = isset($options[$id]) ? checked($options[$id], 1, false) : '';
echo '<div class="container">';
echo '<label class="switch">';
echo '<input type="checkbox" id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" value="1"' . $checked . ' />';
echo '<span class="slider round"></span>
</label>';
// echo '</br>';
echo '<label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';
echo '</br>';
echo '</br>';
//Display time stamp when object cache was last flushed when page or post was deleted
echo '<small><strong>Last flushed at: </strong></small>' . wp_kses_post( get_option('flush-cache-on-page-post-delete-time-stamp') );
}
// Flush cache when comment is deleted checkbox
function pressable_cache_management_callback_field_comment_delete_checkbox($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$checked = isset($options[$id]) ? checked($options[$id], 1, false) : '';
echo '<div class="container">';
echo '<label class="switch">';
echo '<input type="checkbox" id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" value="1"' . $checked . ' />';
echo '<span class="slider round"></span>
</label>';
// echo '</br>';
echo '<label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';
echo '</br>';
echo '</br>';
//Display time stamp when object cache was last flushed when comment was deleted
echo '<small><strong>Last flushed at: </strong></small>' . wp_kses_post( get_option('flush-cache-on-comment-delete-time-stamp') );
}
//Flush cache for a single page
function pressable_cache_management_callback_field_flush_batcache_particular_page_checbox($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$checked = isset($options[$id]) ? checked($options[$id], 1, false) : '';
echo '<div class="container">';
echo '<label class="switch">';
echo '<input type="checkbox" id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" value="1"' . $checked . ' />';
echo '<span class="slider round"></span>
</label>';
// echo '</br>';
echo '<label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';
echo '</br>';
echo '</br>';
//Display time stamp when object cache was last flushed
echo '<small><strong>Last flushed at:</strong></small> ' . wp_kses_post( get_option('flush-object-cache-for-single-page-time-stamp') );
echo '</br>';
echo '<small><strong>Page URL:</strong></small> ' . esc_html( get_option('single-page-url-flushed') );
}
//Flush cache for WooCommerce product single page
function pressable_cache_management_callback_field_flush_batcache_woo_product_page_checbox($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$checked = isset($options[$id]) ? checked($options[$id], 1, false) : '';
echo '<div class="container">';
echo '<label class="switch">';
echo '<input type="checkbox" id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" value="1"' . $checked . ' />';
echo '<span class="slider round"></span>
</label>';
// echo '</br>';
echo '<label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';
echo '</br>';
// echo '<small><strong>Last purged Edge at:</strong></small> ' . (get_option('single-page-edge-cache-purge-time-stamp')) . '<small></small>';
// echo '</br>';
}
//Callback: text field to exempt individual page from batcache
function pressable_cache_management_callback_field_exempt_batcache_text($args)
{
$options = get_option('pressable_cache_management_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$value = isset($options[$id]) ? sanitize_text_field($options[$id]) : '';
echo '<input autocomplete="off" id="pressable_cache_management_options_' . esc_attr( $id ) . '" name="pressable_cache_management_options[' . $id . ']" type="text" placeholder=" Exclude single page ex /pagename/" size="70" value="' . esc_attr( $value ) . '"><br/>';
echo '<label class="rad-text for="pressable_cache_management_options_' . esc_attr( $id ) . '">' . esc_html( $label ) . '</label>';
}
/*
/**
********************************
* Edge Cache *
* Management Tab *
********************************
**/
// Radio button options to turn on/off Edge Cache
function pressable_cache_management_options_radio_edge_cache_button()
{
return array(
'enable' => esc_html__('Enable Edge Cache', 'pressable_cache_management') ,
);
}
// AJAX handler function to check Edge Cache status on demand
function pcm_ajax_check_edge_cache_status()
{
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'Unauthorized'], 403);
return;
}
// --- Transient cache: avoid hitting the Pressable API on every page load ---
// Cache TTL: 5 minutes for enabled/disabled, 60 seconds for DDoS/unknown so
// we recover quickly without hammering the API.
$cache_key = 'pcm_ec_status_cache';
$cached = get_transient( $cache_key );
if ( $cached !== false ) {
// Serve from cache — no API call needed
wp_send_json_success([
'enabled' => $cached['is_enabled'],
'status_text' => $cached['status_text'],
'status_flag' => $cached['status_flag'],
'from_cache' => true,
'html_controls_enable_disable' => pressable_cache_management_generate_enable_disable_content( $cached['is_enabled'] ),
]);
return;
}
if ( ! class_exists('Edge_Cache_Plugin') ) {
wp_send_json_error([
'message' => 'Edge Cache dependency is not available.',
'html_controls_enable_disable' => '<p class="notice notice-error" style="padding: 10px;">' . esc_html__('Error: Edge Cache dependency is missing.', 'pressable_cache_management') . '</p>',
]);
return;
}
$edge_cache = Edge_Cache_Plugin::get_instance();
$server_status = $edge_cache->get_ec_status(); // live API call
$is_enabled = false;
$status_text = 'Unknown';
$status_flag = 'Error';
$ttl = 60; // short TTL for unknown/error states
if ( $server_status === Edge_Cache_Plugin::EC_ENABLED ) {
$is_enabled = true;
$status_text = 'Enabled';
$status_flag = 'Success';
$ttl = 300; // 5 minutes — stable state
} elseif ( $server_status === Edge_Cache_Plugin::EC_DISABLED ) {
$is_enabled = false;
$status_text = 'Disabled';
$status_flag = 'Success';
$ttl = 300; // 5 minutes — stable state
} elseif ( $server_status === Edge_Cache_Plugin::EC_DDOS ) {
$status_text = 'Defensive Mode (DDoS)';
$status_flag = 'Warning';
$ttl = 60; // re-check sooner during DDoS mode
}
// Store in transient so subsequent page loads skip the API call
set_transient( $cache_key, [
'is_enabled' => $is_enabled,
'status_text' => $status_text,
'status_flag' => $status_flag,
], $ttl );
// Keep wp_options in sync for server-side badge rendering
update_option('edge-cache-status', $status_flag);
update_option('edge-cache-enabled', $is_enabled ? 'enabled' : 'disabled');
wp_send_json_success([
'enabled' => $is_enabled,
'status_text' => $status_text,
'status_flag' => $status_flag,
'from_cache' => false,
'html_controls_enable_disable' => pressable_cache_management_generate_enable_disable_content( $is_enabled ),
]);
}
add_action('wp_ajax_pcm_check_edge_cache_status', 'pcm_ajax_check_edge_cache_status');
/**
* Clear the edge cache status transient whenever the state changes
* (enable, disable, purge) so the next request gets a fresh live value.
*/
function pcm_clear_ec_status_cache() {
delete_transient( 'pcm_ec_status_cache' );
}
add_action( 'pcm_after_edge_cache_enable', 'pcm_clear_ec_status_cache' );
add_action( 'pcm_after_edge_cache_disable', 'pcm_clear_ec_status_cache' );
add_action( 'pcm_after_edge_cache_purge', 'pcm_clear_ec_status_cache' );
add_action( 'pcm_after_defensive_mode_change','pcm_clear_ec_status_cache' );
/**
* Helper function to generate only the Enable/Disable button form HTML.
*
* @param bool $is_enabled Whether the Edge Cache is currently enabled.
* @return string The HTML containing only the Enable/Disable control.
*/
function pressable_cache_management_generate_enable_disable_content($is_enabled) {
ob_start();
//Button form/label
if ($is_enabled) {
$id = 'disable_edge_cache_nonce';
$value = __('Disable Edge Cache', 'pressable_cache_management');
$submit_class = 'purgecacahe';
echo '</form>';
echo '<form method="post" id="' . esc_attr($id) . '">';
echo '<span id="' . esc_attr($id) . '">';
echo '<input id="edge_cache_settings_tab_options_disable" name="edge_cache_settings_tab_options[edge_cache_on_off_radio_button]" type="submit" size="40" value="' . esc_attr($value) . '" class="' . esc_attr($submit_class) . '"/>';
echo '<input type="hidden" name="' . esc_attr($id) . '" value="' . wp_create_nonce($id) . '" />';
echo '</span>';
echo '</form>';
} else {
$id = 'enable_edge_cache_nonce';
$value = __('Enable Edge Cache', 'pressable_cache_management');
$submit_class = 'purgecacahe';
echo '</form>';
echo '<form method="post" id="' . esc_attr($id) . '">';
echo '<span id="' . esc_attr($id) . '">';
echo '<input id="edge_cache_settings_tab_options_enable" name="edge_cache_settings_tab_options[edge_cache_on_off_radio_button]" type="submit" size="40" value="' . esc_attr($value) . '" class="' . esc_attr($submit_class) . '"/>';
echo '<input type="hidden" name="' . esc_attr($id) . '" value="' . wp_create_nonce($id) . '" />';
echo '</span>';
echo '</form>';
}
return ob_get_clean();
}
// Renders the placeholder div and the synchronization script.
function pressable_cache_management_callback_field_extend_edge_cache_radio_button($args)
{
// Renders the single placeholder div and the synchronization script.
?>
<style>
.edge-cache-loader {
display: flex;
align-items: center;
height: 30px;
font-style: italic;
color: #777;
}
.edge-cache-loader::before {
content: '';
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 14px;
height: 14px;
animation: spin 1s linear infinite;
margin-right: 10px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Style for grayed-out button */
.disabled-button-style {
opacity: 0.6;
cursor: not-allowed;
pointer-events: none; /* Prevents clicks on disabled elements */
}
.disabled-button-style:hover {
opacity: 0.6 !important;
box-shadow: none !important;
}
</style>
<!-- RENDER: Container for ENABLE/DISABLE control -->
<div id="edge-cache-control-wrapper" style="min-height: 30px;">
<div class="edge-cache-loader"><?php esc_html_e('Checking Edge Cache status...', 'pressable_cache_management'); ?></div>
</div>
<script>
jQuery(document).ready(function($) {
var wrapper = $('#edge-cache-control-wrapper');
var purgeButton = $('#purge-edge-cache-button-input');
// This check ensures AJAX only fires if the element exists and hasn't already been checked.
if (wrapper.length && !wrapper.data('status-checked')) {
wrapper.data('status-checked', true);
// --- Set initial state for Purge button (Always disabled/grayed out before AJAX response) ---
purgeButton.prop('disabled', true).addClass('disabled-button-style');
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'pcm_check_edge_cache_status'
},
success: function(response) {
if (response.success && response.data.html_controls_enable_disable) {
// 1. Update Enable/Disable content
wrapper.html(response.data.html_controls_enable_disable);
// 2. Update Purge Button state (Gray out/Enable)
if (response.data.enabled) {
purgeButton.prop('disabled', false).removeClass('disabled-button-style');
} else {
// Keep grayed out
purgeButton.prop('disabled', true).addClass('disabled-button-style');
}
} else {
// Handle failure
var errorMessage = response.data && response.data.message ? response.data.message : 'Failed to retrieve Edge Cache status.';
wrapper.html('<p class="notice notice-error" style="padding: 10px;">' + errorMessage + '</p>');
}
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle AJAX network/server error
var errorMessage = 'AJAX Error: Could not connect to the status server.';
wrapper.html('<p class="notice notice-error" style="padding: 10px;">' + errorMessage + '</p>');
}
});
}
});
</script>
<?php
}
//Purge Edge Cache
function pressable_edge_cache_flush_management_callback_field_button($args)
{
$options = get_option('edge_cache_settings_tab_options');
$id = isset($args['id']) ? $args['id'] : '';
// Remove $label to avoid showing text
// $label = isset($args['label']) ? $args['label'] : '';
// Disabled attribute and class for initial state
$disabled_attr = ' disabled="disabled"';
$disabled_class = ' disabled-button-style';
$submit_class = 'purgecacahe' . $disabled_class;
echo '</form>';
echo '<form method="post" id="purge_edge_cache_nonce_form_static">
<span id="purge_edge_cache_button_span_static">
<input id="purge-edge-cache-button-input"
name="edge_cache_settings_tab_options[' . $id . ']"
type="submit"
size="40"
value="' . esc_attr__( 'Purge Edge Cache', 'pressable_cache_management' ) . '"
class="' . esc_attr($submit_class) . '"' . $disabled_attr . '/>';
echo '<input type="hidden" name="purge_edge_cache_nonce" value="' . wp_create_nonce('purge_edge_cache_nonce') . '" />';
echo '</span>
</form>';
echo '<br/>';
// Display timestamp when object cache was last flushed
echo '<small><strong>' . esc_html__( 'Last purged at:', 'pressable_cache_management' ) . ' </strong></small>' . esc_html( get_option('edge-cache-purge-time-stamp') );
echo '<br/>';
echo '<br/>';
echo '<small><strong>' . esc_html__( 'Single URL last purged at:', 'pressable_cache_management' ) . '</strong></small> ' . esc_html( get_option('single-page-edge-cache-purge-time-stamp') );
echo '<br/>';
echo '<small><strong>' . esc_html__( 'Single URL:', 'pressable_cache_management' ) . '</strong></small> ' . esc_html( get_option('edge-cache-single-page-url-purged') );
echo '<br/>';
echo '<br/>';
echo '<p style="font-size:12px;">'
. __('Purging cache will temporarily slow down your site for all visitors while the cache rebuilds.', 'pressable_cache_management'). '</p>';
}
/**
********************************
* Remove Pressable *
* Branding Tab *
********************************
*
*/
// Radio button options
function pressable_cache_management_options_remove_branding_radio_button()
{
return array(
'enable' => esc_html__('Show Pressable Branding', 'pressable_cache_management') ,
'disable' => esc_html__('Hide Pressable Branding', 'pressable_cache_management')
);
}
function pressable_cache_management_callback_field_extend_remove_branding_radio_button($args)
{
$options = get_option('remove_pressable_branding_tab_options');
$id = isset($args['id']) ? $args['id'] : '';
$label = isset($args['label']) ? $args['label'] : '';
$selected_option = isset($options[$id]) ? sanitize_text_field($options[$id]) : '';
$radio_options = pressable_cache_management_options_remove_branding_radio_button();
foreach ($radio_options as $value => $label)
{
$checked = checked($selected_option === $value, true, false);
echo '<label class="rad-label">';
echo '<input type="radio" class="rad-input" name="remove_pressable_branding_tab_options[' . $id . ']" type="radio" value="' . esc_attr( $value ) . '"' . $checked . ' name="rad">';
echo '<div class="rad-design"></div>';
echo '<span class="rad-text">' . esc_html( $label ) . '</span></label>';
echo '</label>';
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,194 @@
<?php
// Pressable Cache Management - Register Settings
// Disable direct file access
if (!defined('ABSPATH')) {
exit;
}
// Register plugin settings
function pressable_cache_management_register_settings()
{
// Save options for object cache tab
register_setting(
'pressable_cache_management_options',
'pressable_cache_management_options',
'pressable_cache_management_callback_validate_options'
);
// Save options for edge cache tab
register_setting(
'edge_cache_tab_options',
'edge_cache_settings_tab_options',
'edge_cache_settings_tab_callback_validate_options'
);
// Save options for branding tab
register_setting(
'remove_pressable_branding_tab_options',
'remove_pressable_branding_tab_options',
'remove_pressable_branding_tab_callback_validate_options'
);
$remove_pressable_branding_tab_options = get_option('remove_pressable_branding_tab_options');
if ($remove_pressable_branding_tab_options && 'disable' == $remove_pressable_branding_tab_options['branding_on_off_radio_button']) {
add_settings_section(
'pressable_cache_management_section_cache',
esc_html__('Cache Control Management', 'pressable_cache_management'),
'pressable_cache_management_callback_section_cache',
'pressable_cache_management'
);
} else {
add_settings_section(
'pressable_cache_management_section_cache',
esc_html__('Cache Management By', 'pressable_cache_management'),
'pressable_cache_management_callback_section_cache',
'pressable_cache_management'
);
}
// Edge Cache settings tab page
add_settings_section(
'pressable_cache_management_section_edge_cache',
esc_html__('Manage Edge Cache Settings', 'pressable_cache_management'),
'pressable_cache_management_callback_section_edge_cache',
'edge_cache_settings_tab'
);
// Remove Pressable branding tab page
add_settings_section(
'pressable_cache_management_section_branding',
esc_html__('Show or Hide Plugin Branding', 'pressable_cache_management'),
'pressable_cache_management_callback_section_branding',
'remove_pressable_branding_tab'
);
// Verify if the options exist
if (false == get_option('pressable_cache_management_options')) {
add_option('pressable_cache_management_options');
}
/*
* Object Cache Management Tab
*/
add_settings_field(
'flush_cache_button',
esc_html__('Flush Object Cache', 'pressable_cache_management'),
'pressable_cache_management_callback_field_button',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'flush_cache_button', 'label' => esc_html__('Flush object cache (Database)', 'pressable_cache_management')]
);
add_settings_field(
'extend_batcache_checkbox',
esc_html__('Extend Batcache', 'pressable_cache_management'),
'pressable_cache_management_callback_field_extend_cache_checkbox',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'extend_batcache_checkbox', 'label' => esc_html__('Extend Batcache storage time by 24 hours', 'pressable_cache_management')]
);
add_settings_field(
'flush_cache_theme_plugin_checkbox',
esc_html__('Flush Cache on Update', 'pressable_cache_management'),
'pressable_cache_management_callback_field_plugin_theme_update_checkbox',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'flush_cache_theme_plugin_checkbox', 'label' => esc_html__('Flush cache automatically on plugin & theme update', 'pressable_cache_management')]
);
add_settings_field(
'flush_cache_page_edit_checkbox',
esc_html__('Flush Cache on Edit', 'pressable_cache_management'),
'pressable_cache_management_callback_field_page_edit_checkbox',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'flush_cache_page_edit_checkbox', 'label' => esc_html__('Flush cache automatically when page/post/post_types are updated', 'pressable_cache_management')]
);
add_settings_field(
'flush_cache_on_page_post_delete_checkbox',
esc_html__('Flush Cache on Page Delete', 'pressable_cache_management'),
'pressable_cache_management_callback_field_page_post_delete_checkbox',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'flush_cache_on_page_post_delete_checkbox', 'label' => esc_html__('Flush cache automatically when published pages/posts are deleted', 'pressable_cache_management')]
);
add_settings_field(
'flush_cache_on_comment_delete_checkbox',
esc_html__('Flush Cache on Comment Delete', 'pressable_cache_management'),
'pressable_cache_management_callback_field_comment_delete_checkbox',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'flush_cache_on_comment_delete_checkbox', 'label' => esc_html__('Flush cache automatically when comments are deleted', 'pressable_cache_management')]
);
add_settings_field(
'flush_object_cache_for_single_page',
esc_html__('Flush Batcache for Individual Pages', 'pressable_cache_management'),
'pressable_cache_management_callback_field_flush_batcache_particular_page_checbox',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'flush_object_cache_for_single_page', 'label' => esc_html__('Flush Batcache for individual pages', 'pressable_cache_management')]
);
add_settings_field(
'flush_batcache_for_woo_product_individual_page_checkbox',
esc_html__('Flush Batcache for Woo Product Pages', 'pressable_cache_management'),
'pressable_cache_management_callback_field_flush_batcache_woo_product_page_checbox',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'flush_batcache_for_woo_product_individual_page_checkbox', 'label' => esc_html__('Flush Batcache for WooCommerce product pages', 'pressable_cache_management')]
);
add_settings_field(
'exempt_from_batcache',
esc_html__('Exclude Page from Batcache & Edge Cache', 'pressable_cache_management'),
'pressable_cache_management_callback_field_exempt_batcache_text',
'pressable_cache_management',
'pressable_cache_management_section_cache',
['id' => 'exempt_from_batcache', 'label' => esc_html__('To exclude multiple pages separate with comma ex /your-site.com/, /about-us/, /info/', 'pressable_cache_management')]
);
/*
* Edge Cache Management Tab
*/
add_settings_field(
'edge_cache_on_off_radio_button',
esc_html__('Turn On/Off Edge Cache', 'pressable_cache_management'),
'pressable_cache_management_callback_field_extend_edge_cache_radio_button',
'edge_cache_settings_tab',
'pressable_cache_management_section_edge_cache',
['id' => 'edge_cache_on_off_radio_button', 'label' => esc_html__('Turn on/off Edge Cache', 'pressable_cache_management')]
);
/*
* Display Purge Edge Cache button
*/
add_settings_field(
'purge_edge_cache_button',
esc_html__('Purge Edge Cache', 'pressable_cache_management'),
'pressable_edge_cache_flush_management_callback_field_button',
'edge_cache_settings_tab',
'pressable_cache_management_section_edge_cache',
['id' => 'purge_edge_cache_button', 'label' => esc_html__('Purge Edge Cache', 'pressable_cache_management')]
);
/*
* Remove Pressable Branding Tab
*/
add_settings_field(
'branding_on_off_radio_button',
esc_html__('Hide or Show Plugin Branding', 'pressable_cache_management'),
'pressable_cache_management_callback_field_extend_remove_branding_radio_button',
'remove_pressable_branding_tab',
'pressable_cache_management_section_branding',
['id' => 'branding_on_off_radio_button', 'label' => esc_html__('Hide or show plugin branding', 'pressable_cache_management')]
);
}
add_action('admin_init', 'pressable_cache_management_register_settings');
@@ -0,0 +1,107 @@
<?php // Pressable Cache Management - Validate Settings
// Disable direct file access
if (!defined("ABSPATH")) {
exit();
}
// Callback: validate main options
function pressable_cache_management_callback_validate_options($input) {
if (empty($input)) {
$input = [];
}
// Extend batcache checkbox
if (!isset($input["extend_batcache_checkbox"])) {
$input["extend_batcache_checkbox"] = "";
}
$input["extend_batcache_checkbox"] = filter_var($input["extend_batcache_checkbox"] == 1 ? 1 : 0, FILTER_SANITIZE_NUMBER_INT);
// Flush object cache on theme and plugin update checkbox
if (!isset($input["flush_cache_theme_plugin_checkbox"])) {
$input["flush_cache_theme_plugin_checkbox"] = "";
}
$input["flush_cache_theme_plugin_checkbox"] = filter_var($input["flush_cache_theme_plugin_checkbox"] == 1 ? 1 : 0, FILTER_SANITIZE_NUMBER_INT);
// Flush object cache on page and post update
if (!isset($input["flush_cache_page_edit_checkbox"])) {
$input["flush_cache_page_edit_checkbox"] = "";
}
$input["flush_cache_page_edit_checkbox"] = filter_var($input["flush_cache_page_edit_checkbox"] == 1 ? 1 : 0, FILTER_SANITIZE_NUMBER_INT);
// Flush object cache on page and post delete
if (!isset($input["flush_cache_on_page_post_delete_checkbox"])) {
$input["flush_cache_on_page_post_delete_checkbox"] = "";
}
$input["flush_cache_on_page_post_delete_checkbox"] = filter_var($input["flush_cache_on_page_post_delete_checkbox"] == 1 ? 1 : 0, FILTER_SANITIZE_NUMBER_INT);
// Flush object cache on comment delete
if (!isset($input["flush_cache_on_comment_delete_checkbox"])) {
$input["flush_cache_on_comment_delete_checkbox"] = "";
}
$input["flush_cache_on_comment_delete_checkbox"] = filter_var($input["flush_cache_on_comment_delete_checkbox"] == 1 ? 1 : 0, FILTER_SANITIZE_NUMBER_INT);
// Flush Batcache for individual page
if (!isset($input["flush_object_cache_for_single_page"])) {
$input["flush_object_cache_for_single_page"] = "";
}
$input["flush_object_cache_for_single_page"] = filter_var($input["flush_object_cache_for_single_page"] == 1 ? 1 : 0, FILTER_SANITIZE_NUMBER_INT);
// Flush Batcache for WooCommerce individual page
$input["flush_batcache_for_woo_product_individual_page_checkbox"] = isset($input["flush_batcache_for_woo_product_individual_page_checkbox"]) ? filter_var($input["flush_batcache_for_woo_product_individual_page_checkbox"] == 1 ? 1 : 0, FILTER_SANITIZE_NUMBER_INT) : 0;
// Exclude pages from Batcache — sanitize comma-separated URL paths
if ( isset( $input['exempt_from_batcache'] ) ) {
$raw_paths = explode( ',', $input['exempt_from_batcache'] );
$clean_paths = array_filter( array_map( function( $path ) {
$path = sanitize_text_field( wp_unslash( trim( $path ) ) );
// Strip full URLs — extract just the path portion
$parsed = wp_parse_url( $path );
if ( isset( $parsed['path'] ) && '' !== $parsed['path'] ) {
$path = $parsed['path'];
}
// Allow only safe path characters: alphanumeric, hyphen, underscore, dot, slash
$path = preg_replace( '/[^a-zA-Z0-9\-_\/\.]/', '', $path );
// Collapse multiple slashes
$path = preg_replace( '/\/+/', '/', $path );
// Ensure leading slash
if ( substr( $path, 0, 1 ) !== '/' ) $path = '/' . $path;
// Ensure trailing slash
if ( substr( $path, -1 ) !== '/' ) $path = $path . '/';
// Must be more than just a single slash
return strlen( $path ) > 1 ? $path : '';
}, $raw_paths ) );
$input['exempt_from_batcache'] = implode( ', ', $clean_paths );
}
return $input;
}
// Callback: validate Edge Cache options
function egde_cache_settings_tab_callback_validate_options($input) {
if ( ! is_array( $input ) ) {
return array();
}
// Sanitize each value — edge cache options are radio/checkbox strings
$allowed = array( 'enabled', 'disabled', 'enable', 'disable', '1', '0', '' );
foreach ( $input as $key => $value ) {
$key = sanitize_key( $key );
$input[ $key ] = in_array( $value, $allowed, true ) ? $value : sanitize_text_field( $value );
}
return $input;
}
// Callback: validate branding options
function remove_pressable_branding_tab_callback_validate_options($input) {
// Turn On/Off Pressable branding option
$radio_options = pressable_cache_management_options_radio_button();
if (!isset($input["branding_on_off_radio_button"])) {
$input["branding_on_off_radio_button"] = null;
}
if (!array_key_exists($input["branding_on_off_radio_button"], $radio_options)) {
$input["branding_on_off_radio_button"] = null;
}
return $input;
}
@@ -0,0 +1,262 @@
=== Pressable Cache Management Change log ===
= Version 6.1.0 (Mar 16, 2026) =
* Added new features to enhance Edge Cache
= Version 6.0.0 (Mar 12, 2026) =
* Added defensive mode feature for Edge Cache
= Version 5.9.9 (Mar 08, 2026) =
* Updated language string to support admin menu
* Add features to track max age
* Updated transcient for status checker
* Updated settings
* Updated validation method for exclude cache
= Version 5.8.7 (Mar 07, 2026) =
* Fix botton bug
* Update checkbox button color to red when disabled
* Bug fix
* Bypass Edge Cache header when Batcache checker checks for cache status
* Fix grid and margins
= Version 5.5.5 (Mar 06, 2026) =
* Update Edge Cache page UI
* Update button color
* Updated tool tip for Batcache status checker
= Version 5.3.2 (Mar 05, 2026) =
* Update the grid to also fill the full width of the centred container
= Version 5.3.1 (Mar 05, 2026) =
* Updated plugin updater
= Version 5.3.0 (Mar 05, 2026) =
**UI & Design**
* Redesigned settings page with card-based layout, toggle switches, and Inter font typography
* Added "Cache Management by" header above Pressable logo in branded header
* Made footer ♥ icon clickable in both branding states, linking to branding settings page
* Timestamps (Last flushed at:) are now always visible showing — when never flushed
* Timestamps display on a single straight line using flexbox layout (no line breaks)
* Bold text inside timestamps (e.g. — cache flushed due to Page edit: My Post) now renders correctly as bold rather than showing raw <b> tags
* Darkened timestamp and label text for improved readability
* Added interactive chip UI for cache exclusion URL input
* Added branded admin bar modals replacing browser alert() popups for Edge Cache enable/disable and flush actions
**Batcache Status Badge**
* Fixed Batcache status check to read the correct x-nananana header instead of scanning the response body for the word "batcache"
* Fixed probe request to send no session cookies and mimic a real browser request, preventing Batcache from skipping the response
* Removed Cache-Control: no-cache from the probe request which was causing the Pressable edge CDN to bypass cache entirely
* Added 90-second transient cache on the status result to avoid a live HTTP request on every admin page load
* Added ↺ refresh button on the badge that re-checks live status via AJAX without requiring a full page reload
* Added tooltip ? icon next to the badge explaining: when a page gets two visits within 2 minutes it is cached for 5 minutes, and that cookies may interfere with cache status updates
* Status transient is cleared immediately after any manual cache flush so the badge reflects the new state on next load
**Cache Flush Improvements**
* Flush Cache on Plugin/Theme Update now captures and displays the plugin or theme name in the timestamp (e.g. — Yoast SEO plugin was updated)
* Flush Cache on Post/Page Edit now captures and displays the post title and post type in the timestamp
* Page URL: field now correctly shows the human-readable URL when flushing from the page/post column link (previously showed the md5 hash Batcache uses internally)
* Page URL: field now correctly saves when flushing from the page preview toolbar
* Renamed Object Cache page button Flush Cache → Flush All Cache
**GitHub Auto-Updates**
* Integrated YahnisElsts/plugin-update-checker v5.6 library (bundled directly, no Composer required)
* Plugin now checks github.com/pressable/pressable-cache-management for new releases automatically
* WordPress sites show the standard update notice when a new GitHub Release is published
* Added readme.txt used to populate the "View Details" popup in WordPress admin when an update is available
* Added SETUP.md with full instructions for releasing future updates via GitHub tags
* Removed unused library files: DebugBar/ and OAuthSignature.php to reduce plugin size
**Translations**
* Added French (fr_FR) translation — 65 strings
* Added Dutch (nl_NL) translation — 65 strings
* Added Simplified Chinese (zh_CN) translation — 65 strings
* Added Hindi (hi_IN) translation — 65 strings
* Updated Spanish (es_ES) translation to 65 strings
* Fixed load_plugin_textdomain() to use the correct relative path so all locales load when site language is changed
* Wrapped all previously untranslated UI strings including card titles, toggle labels, descriptions, exclude pages hint text, and branding page strings
* All tooltip and badge strings included in all 5 languages
**Uninstall Cleanup**
* Rewrote uninstall.php to delete all option keys the plugin has ever written, organised by category: main settings, all timestamps, Edge Cache state, Batcache flags, exclusion settings, WooCommerce notices, legacy CDN options from older versions
* Added $wpdb->query() to sweep out PUC transients (_transient_puc_*pressable-cache-management*) on uninstall
= Version 5.2.2 (Oct 15, 2025) =
* Fix bug for admin bar option not updating quicky after Edge cache is enabled/disabled
= Version 5.2.1 (Oct 7, 2025) =
* Added option to purge Edge Cache for single URL
* Removed API connection features for edge cache
* Added option to control Edge Cache without using an API connection
* Added dropdown button to flush both Object and Edge Cache
* Added option to automatically purge Edge Cache when WooCommerce product are edited via the WooCommerce API
* Removed all support for the CDN
= Version 5.1.0 (Jul 30, 2025) =
* Updated permission Only users with the following: administrator, editor and manage_woocommerce Can: See the "Flush Cache" option.
= Version 5.0.0 (May 30, 2025) =
* Removed CDN tab as CDN feature has been phased out from Pressable
= Version 4.9.9 (Mar 22, 2025) =
* Added functionality to exclude specific pages from Batcache caching, ensuring they are not cached by the Edge Cache
* Updated description for the option exclude page from Batcache to include Edge Cache
= Version 4.8.9 (Feb 22, 2025) =
* Fix bug to resolve issue with cache terminating when a single page is excluded from cache
= Version 4.7.9 (Jan 28, 2025) =
* Fix bug that breaks site when excluding single file from CDN
= Version 4.6.9 (Nov 15, 2024) =
* Added features to exclude home page from caching
= Version 4.5.9 (Oct 31, 2024) =
* Added a check if the "Name" key exists in $plugin_info before trying to access it to prevent "Undefined array key 'Name'"
= Version 4.4.9 (Oct 3, 2024) =
* Fix: ensure HTML/CSS is not output on every page load including AJAX requests
= Version 4.3.9 (July 24, 2024) =
* Updated Pressable branding
= Version 4.2.9 (July 22, 2024) =
* Fixed bugs
= Version 4.2.8 (July 22, 2024) =
* Sync the plugin CDN and Edge Cache state with MyPressable Control Panel when the plugin is authenticated
* Disable CDN state by defualt on plugin install
* Hide CDN tab if /cdn api endpoint is not found
= Version 4.2.7 (June 27, 2024) =
* Fixed bug with <p> tag added to robots.txt code snippet when extend cache option is enabled for some sites
* Updated from v4.2.6 - v4.2.7
= Version 4.2.5 (March 18, 2024) =
* Fixed the warning error bug with DOMDocument PHP Warning: DOMDocument::loadHTML():
= Version 4.2.2 (December 1, 2023) =
* Fixed footer conflict with Yoursite plugin which causes critical error
= Version 4.2.1 (September 14, 2023) =
* Add notice to disable CDN if Edge Cache is enabled
* Fixed bug with edge Cache turn on/off not syncing properly with MyPressable Control Panel
= Version 4.2.0 (June 22, 2023) =
* Changed the location for mu-plugins used to flush cache when Woo product is updated via API
= Version 4.1.0 (June 22, 2023) =
* Fixed issue double function deceleration
= Version 4.0.0 (June 21, 2023) =
* Removed edge cache purge time stamp from database
= Version 3.10.10 (June 20, 2023) =
* Features to flush WooCommerce product page automatically when product are updated via Woo API
* Ability for Shop managers to flush cache via Admin top bar
* Ability to extend cache for URL's inside data-srcset attributes
* Features to manage Edge Cache option
* Resolve conflict that causes Imagify plugin generated .webp images from displaying
* Ability to auto turn on Edge Cache if it is disabled from MPCP when Edge cache is purged
= Version 3.9.10 (June 8, 2023) =
* Fixed bug of purge CDN button which is displaying when CDN is disabled
* Hide visible hyperlink on footer page to hide branding
* Fixed issue with tag not appending to RSS feed page
* Fixed bug for broken images inside
= Version 3.8.10 (May 12, 2023) =
* Added features and notification to check if Cloudflare is interfering with Batcache
= Version 3.7.10 (May 2, 2023) =
* Code cleanup and changelog update
= Version 3.6.10 (Apr 20, 2023) =
* Excluded gclid option from the UI
* Excluded wpp_ cookies option from the UI
= Version 3.5.10 (Mar 23, 2023) =
* Updated new option
= Version 3.4.10 (Mar 23, 2023) =
* Hide option from UI which does not function correctly yet
= Version 3.3.10 (Mar 20, 2023) =
* Updated batcache code
= Version 3.3.9 (Feb 26, 2023) =
* Updated language functionality
= Version 3.3.8 (Feb 23, 2023) =
* Added support to move mu-plugin from PCM to a private folder
= Version 3.3.7 (Feb 20, 2023) =
* Bug fixes and new features added
= Version 3.3.6 (Feb 07, 2023) =
* Updated footer icon
= Version 3.3.5 (Jan 07, 2023) =
* Updated extending cache option to execute via mu-plugin
* Added option to flush cache when comment is deleted
* Added notification to know if plugin or theme was updated
* Disable plugin automatically when used on another platform
* Add option to flush website cache automatically when page or post is deleted after publishing this works for post-types as well
* Added option to exclude pages from Batcache
= Version 3.3.4 (Aug 12, 2022) =
* Fixed function conflict on Flush cache on theme plugin update
= Version 3.3.4 (Aug 12, 2022) =
* Fixed Zend OPcache API is restricted by "restrict_api" configuration directive warning on extended batcache
* Fixed admin notice not displaying when extend batcache is enabled and disabled
= Version 3.3.4 (Aug 4, 2022) =
* Fixed bug for site id not entering on multi-network site
= Version 3.3.4 (Jul 10, 2022) =
* Fixed TTFB performance issue that slows down WordPress admin
* Renamed authentication button to save option
* Rename authentication button tab button to save option
* Hide save button if connection is successful for added security
* Cached the API key using transient for fast performance
* Added new admin notice warning to alert user if CDN is flushed twice within a minute
* Added admin notice to alert user to connect to the api if API credentials is not saved
* Updated toggle option to enable/disable CDN to button
* Added settings option from the plugin area
* Added button option to connect and disconnect API
* Added option to clear API credentials when API is disconnected
* Added nonce to button for added security
* Fixed bug that shows CDN option when plugin is not yet connected to the API
* Added error message to alert user if the plugin is installed on site hosted on another platform
= Version 3.2.3 (Jul 03, 2022) =
* Fixed CSS conflict issue with some third-party plugin
= Version 3.1.4 (May 21, 2022) =
* Added warning notice to CDN cache extender when enabled to notify user to disable the option if it causes any issue(The CDN extender features is buggy and know
= Version 3.0.3 (May 21, 2022) =
* Fixed issue with api_connection which adds extra time to site TTFB
= Version 3.0.2 (April 28, 2022) =
* Fixed ?extend_cdn appended to the word style.css which is added to blog post/page
= Version 3.0.2 (April 22, 2022) =
* Applied patch to prevent HTML injection from all CDN exemption features
cdn_exclude_css, cdn_exclude_js_json, cdn_exclude_jpg_png_webp, cdn_exclude_specificfile.
= Version 3.0.1 (April 17, 2022) =
* Exclude Google Tag Manager gtm.js from Pressable CDN to fix Google tracking issue bug
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,10 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5;
if ( !class_exists(PucFactory::class, false) ):
class PucFactory extends \YahnisElsts\PluginUpdateChecker\v5p6\PucFactory {
}
endif;
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,86 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists(Autoloader::class, false) ):
class Autoloader {
const DEFAULT_NS_PREFIX = 'YahnisElsts\\PluginUpdateChecker\\';
private $prefix;
private $rootDir;
private $libraryDir;
private $staticMap;
public function __construct() {
$this->rootDir = dirname(__FILE__) . '/';
$namespaceWithSlash = __NAMESPACE__ . '\\';
$this->prefix = $namespaceWithSlash;
$this->libraryDir = $this->rootDir . '../..';
if ( !self::isPhar() ) {
$this->libraryDir = realpath($this->libraryDir);
}
$this->libraryDir = $this->libraryDir . '/';
//Usually, dependencies like Parsedown are in the global namespace,
//but if someone adds a custom namespace to the entire library, they
//will be in the same namespace as this class.
$isCustomNamespace = (
substr($namespaceWithSlash, 0, strlen(self::DEFAULT_NS_PREFIX)) !== self::DEFAULT_NS_PREFIX
);
$libraryPrefix = $isCustomNamespace ? $namespaceWithSlash : '';
$this->staticMap = array(
$libraryPrefix . 'PucReadmeParser' => 'vendor/PucReadmeParser.php',
$libraryPrefix . 'Parsedown' => 'vendor/Parsedown.php',
);
//Add the generic, major-version-only factory class to the static map.
$versionSeparatorPos = strrpos(__NAMESPACE__, '\\v');
if ( $versionSeparatorPos !== false ) {
$versionSegment = substr(__NAMESPACE__, $versionSeparatorPos + 1);
$pointPos = strpos($versionSegment, 'p');
if ( ($pointPos !== false) && ($pointPos > 1) ) {
$majorVersionSegment = substr($versionSegment, 0, $pointPos);
$majorVersionNs = __NAMESPACE__ . '\\' . $majorVersionSegment;
$this->staticMap[$majorVersionNs . '\\PucFactory'] =
'Puc/' . $majorVersionSegment . '/Factory.php';
}
}
spl_autoload_register(array($this, 'autoload'));
}
/**
* Determine if this file is running as part of a Phar archive.
*
* @return bool
*/
private static function isPhar() {
//Check if the current file path starts with "phar://".
static $pharProtocol = 'phar://';
return (substr(__FILE__, 0, strlen($pharProtocol)) === $pharProtocol);
}
public function autoload($className) {
if ( isset($this->staticMap[$className]) && file_exists($this->libraryDir . $this->staticMap[$className]) ) {
include($this->libraryDir . $this->staticMap[$className]);
return;
}
if ( strpos($className, $this->prefix) === 0 ) {
$path = substr($className, strlen($this->prefix));
$path = str_replace(array('_', '\\'), '/', $path);
$path = $this->rootDir . $path . '.php';
if ( file_exists($path) ) {
include $path;
}
}
}
}
endif;
@@ -0,0 +1,105 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists(InstalledPackage::class, false) ):
/**
* This class represents a currently installed plugin or theme.
*
* Not to be confused with the "package" field in WP update API responses that contains
* the download URL of a the new version.
*/
abstract class InstalledPackage {
/**
* @var UpdateChecker
*/
protected $updateChecker;
public function __construct($updateChecker) {
$this->updateChecker = $updateChecker;
}
/**
* Get the currently installed version of the plugin or theme.
*
* @return string|null Version number.
*/
abstract public function getInstalledVersion();
/**
* Get the full path of the plugin or theme directory (without a trailing slash).
*
* @return string
*/
abstract public function getAbsoluteDirectoryPath();
/**
* Check whether a regular file exists in the package's directory.
*
* @param string $relativeFileName File name relative to the package directory.
* @return bool
*/
public function fileExists($relativeFileName) {
return is_file(
$this->getAbsoluteDirectoryPath()
. DIRECTORY_SEPARATOR
. ltrim($relativeFileName, '/\\')
);
}
/* -------------------------------------------------------------------
* File header parsing
* -------------------------------------------------------------------
*/
/**
* Parse plugin or theme metadata from the header comment.
*
* This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
* It's intended as a utility for subclasses that detect updates by parsing files in a VCS.
*
* @param string|null $content File contents.
* @return string[]
*/
public function getFileHeader($content) {
$content = (string)$content;
//WordPress only looks at the first 8 KiB of the file, so we do the same.
$content = substr($content, 0, 8192);
//Normalize line endings.
$content = str_replace("\r", "\n", $content);
$headers = $this->getHeaderNames();
$results = array();
foreach ($headers as $field => $name) {
$success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
if ( ($success === 1) && $matches[1] ) {
$value = $matches[1];
if ( function_exists('_cleanup_header_comment') ) {
$value = _cleanup_header_comment($value);
}
$results[$field] = $value;
} else {
$results[$field] = '';
}
}
return $results;
}
/**
* @return array Format: ['HeaderKey' => 'Header Name']
*/
abstract protected function getHeaderNames();
/**
* Get the value of a specific plugin or theme header.
*
* @param string $headerName
* @return string Either the value of the header, or an empty string if the header doesn't exist.
*/
abstract public function getHeaderValue($headerName);
}
endif;
@@ -0,0 +1,162 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
use LogicException;
use stdClass;
use WP_Error;
if ( !class_exists(Metadata::class, false) ):
/**
* A base container for holding information about updates and plugin metadata.
*
* @author Janis Elsts
* @copyright 2016
* @access public
*/
abstract class Metadata {
/**
* Additional dynamic properties, usually copied from the API response.
*
* @var array<string,mixed>
*/
protected $extraProperties = array();
/**
* Create an instance of this class from a JSON document.
*
* @abstract
* @param string $json
* @return self
*/
public static function fromJson($json) {
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
}
/**
* @param string $json
* @param self $target
* @return bool
*/
protected static function createFromJson($json, $target) {
/** @var \StdClass $apiResponse */
$apiResponse = json_decode($json);
if ( empty($apiResponse) || !is_object($apiResponse) ){
$errorMessage = "Failed to parse update metadata. Try validating your .json file with https://jsonlint.com/";
do_action('puc_api_error', new WP_Error('puc-invalid-json', $errorMessage));
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error -- For plugin developers.
trigger_error(esc_html($errorMessage), E_USER_NOTICE);
return false;
}
$valid = $target->validateMetadata($apiResponse);
if ( is_wp_error($valid) ){
do_action('puc_api_error', $valid);
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error -- For plugin developers.
trigger_error(esc_html($valid->get_error_message()), E_USER_NOTICE);
return false;
}
foreach(get_object_vars($apiResponse) as $key => $value){
$target->$key = $value;
}
return true;
}
/**
* No validation by default! Subclasses should check that the required fields are present.
*
* @param \StdClass $apiResponse
* @return bool|\WP_Error
*/
protected function validateMetadata($apiResponse) {
return true;
}
/**
* Create a new instance by copying the necessary fields from another object.
*
* @abstract
* @param \StdClass|self $object The source object.
* @return self The new copy.
*/
public static function fromObject($object) {
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
}
/**
* Create an instance of StdClass that can later be converted back to an
* update or info container. Useful for serialization and caching, as it
* avoids the "incomplete object" problem if the cached value is loaded
* before this class.
*
* @return \StdClass
*/
public function toStdClass() {
$object = new stdClass();
$this->copyFields($this, $object);
return $object;
}
/**
* Transform the metadata into the format used by WordPress core.
*
* @return object
*/
abstract public function toWpFormat();
/**
* Copy known fields from one object to another.
*
* @param \StdClass|self $from
* @param \StdClass|self $to
*/
protected function copyFields($from, $to) {
$fields = $this->getFieldNames();
if ( property_exists($from, 'slug') && !empty($from->slug) ) {
//Let plugins add extra fields without having to create subclasses.
$fields = apply_filters($this->getPrefixedFilter('retain_fields') . '-' . $from->slug, $fields);
}
foreach ($fields as $field) {
if ( property_exists($from, $field) ) {
$to->$field = $from->$field;
}
}
}
/**
* @return string[]
*/
protected function getFieldNames() {
return array();
}
/**
* @param string $tag
* @return string
*/
protected function getPrefixedFilter($tag) {
return 'puc_' . $tag;
}
public function __set($name, $value) {
$this->extraProperties[$name] = $value;
}
public function __get($name) {
return isset($this->extraProperties[$name]) ? $this->extraProperties[$name] : null;
}
public function __isset($name) {
return isset($this->extraProperties[$name]);
}
public function __unset($name) {
unset($this->extraProperties[$name]);
}
}
endif;
@@ -0,0 +1,188 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p6\PucFactory;
if ( !class_exists(Package::class, false) ):
class Package extends InstalledPackage {
/**
* @var UpdateChecker
*/
protected $updateChecker;
/**
* @var string Full path of the main plugin file.
*/
protected $pluginAbsolutePath = '';
/**
* @var string Plugin basename.
*/
private $pluginFile;
/**
* @var string|null
*/
private $cachedInstalledVersion = null;
public function __construct($pluginAbsolutePath, $updateChecker) {
$this->pluginAbsolutePath = $pluginAbsolutePath;
$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
parent::__construct($updateChecker);
//Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
}
public function getInstalledVersion() {
if ( isset($this->cachedInstalledVersion) ) {
return $this->cachedInstalledVersion;
}
$pluginHeader = $this->getPluginHeader();
if ( isset($pluginHeader['Version']) ) {
$this->cachedInstalledVersion = $pluginHeader['Version'];
return $pluginHeader['Version'];
} else {
//This can happen if the filename points to something that is not a plugin.
$this->updateChecker->triggerError(
sprintf(
"Cannot read the Version header for '%s'. The filename is incorrect or is not a plugin.",
$this->updateChecker->pluginFile
),
E_USER_WARNING
);
return null;
}
}
/**
* Clear the cached plugin version. This method can be set up as a filter (hook) and will
* return the filter argument unmodified.
*
* @param mixed $filterArgument
* @return mixed
*/
public function clearCachedVersion($filterArgument = null) {
$this->cachedInstalledVersion = null;
return $filterArgument;
}
public function getAbsoluteDirectoryPath() {
return dirname($this->pluginAbsolutePath);
}
/**
* Get the value of a specific plugin or theme header.
*
* @param string $headerName
* @param string $defaultValue
* @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty.
*/
public function getHeaderValue($headerName, $defaultValue = '') {
$headers = $this->getPluginHeader();
if ( isset($headers[$headerName]) && ($headers[$headerName] !== '') ) {
return $headers[$headerName];
}
return $defaultValue;
}
protected function getHeaderNames() {
return array(
'Name' => 'Plugin Name',
'PluginURI' => 'Plugin URI',
'Version' => 'Version',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
'Network' => 'Network',
//The newest WordPress version that this plugin requires or has been tested with.
//We support several different formats for compatibility with other libraries.
'Tested WP' => 'Tested WP',
'Requires WP' => 'Requires WP',
'Tested up to' => 'Tested up to',
'Requires at least' => 'Requires at least',
);
}
/**
* Get the translated plugin title.
*
* @return string
*/
public function getPluginTitle() {
$title = '';
$header = $this->getPluginHeader();
if ( $header && !empty($header['Name']) && isset($header['TextDomain']) ) {
$title = translate($header['Name'], $header['TextDomain']);
}
return $title;
}
/**
* Get plugin's metadata from its file header.
*
* @return array
*/
public function getPluginHeader() {
if ( !is_file($this->pluginAbsolutePath) ) {
//This can happen if the plugin filename is wrong.
$this->updateChecker->triggerError(
sprintf(
"Can't to read the plugin header for '%s'. The file does not exist.",
$this->updateChecker->pluginFile
),
E_USER_WARNING
);
return array();
}
if ( !function_exists('get_plugin_data') ) {
require_once(ABSPATH . '/wp-admin/includes/plugin.php');
}
return get_plugin_data($this->pluginAbsolutePath, false, false);
}
public function removeHooks() {
remove_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
remove_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
}
/**
* Check if the plugin file is inside the mu-plugins directory.
*
* @return bool
*/
public function isMuPlugin() {
static $cachedResult = null;
if ( $cachedResult === null ) {
if ( !defined('WPMU_PLUGIN_DIR') || !is_string(WPMU_PLUGIN_DIR) ) {
$cachedResult = false;
return $cachedResult;
}
//Convert both paths to the canonical form before comparison.
$muPluginDir = realpath(WPMU_PLUGIN_DIR);
$pluginPath = realpath($this->pluginAbsolutePath);
//If realpath() fails, just normalize the syntax instead.
if (($muPluginDir === false) || ($pluginPath === false)) {
$muPluginDir = PucFactory::normalizePath(WPMU_PLUGIN_DIR);
$pluginPath = PucFactory::normalizePath($this->pluginAbsolutePath);
}
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
}
return $cachedResult;
}
}
endif;
@@ -0,0 +1,137 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\Metadata;
if ( !class_exists(PluginInfo::class, false) ):
/**
* A container class for holding and transforming various plugin metadata.
*
* @author Janis Elsts
* @copyright 2016
* @access public
*/
class PluginInfo extends Metadata {
//Most fields map directly to the contents of the plugin's info.json file.
//See the relevant docs for a description of their meaning.
public $name;
public $slug;
public $version;
public $homepage;
public $sections = array();
public $download_url;
public $banners;
public $icons = array();
public $translations = array();
public $author;
public $author_homepage;
public $requires;
public $tested;
public $requires_php;
public $upgrade_notice;
public $rating;
public $num_ratings;
public $downloaded;
public $active_installs;
public $last_updated;
public $autoupdate = false;
public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
public $filename; //Plugin filename relative to the plugins directory.
/**
* Create a new instance of Plugin Info from JSON-encoded plugin info
* returned by an external update API.
*
* @param string $json Valid JSON string representing plugin info.
* @return self|null New instance of Plugin Info, or NULL on error.
*/
public static function fromJson($json){
$instance = new self();
if ( !parent::createFromJson($json, $instance) ) {
return null;
}
//json_decode decodes assoc. arrays as objects. We want them as arrays.
$instance->sections = (array)$instance->sections;
$instance->icons = (array)$instance->icons;
return $instance;
}
/**
* Very, very basic validation.
*
* @param \StdClass $apiResponse
* @return bool|\WP_Error
*/
protected function validateMetadata($apiResponse) {
if (
!isset($apiResponse->name, $apiResponse->version)
|| empty($apiResponse->name)
|| empty($apiResponse->version)
) {
return new \WP_Error(
'puc-invalid-metadata',
"The plugin metadata file does not contain the required 'name' and/or 'version' keys."
);
}
return true;
}
/**
* Transform plugin info into the format used by the native WordPress.org API
*
* @return object
*/
public function toWpFormat(){
$info = new \stdClass;
//The custom update API is built so that many fields have the same name and format
//as those returned by the native WordPress.org API. These can be assigned directly.
$sameFormat = array(
'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
'requires_php',
);
foreach($sameFormat as $field){
if ( isset($this->$field) ) {
$info->$field = $this->$field;
} else {
$info->$field = null;
}
}
//Other fields need to be renamed and/or transformed.
$info->download_link = $this->download_url;
$info->author = $this->getFormattedAuthor();
$info->sections = array_merge(array('description' => ''), $this->sections);
if ( !empty($this->banners) ) {
//WP expects an array with two keys: "high" and "low". Both are optional.
//Docs: https://wordpress.org/plugins/about/faq/#banners
$info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
$info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
}
return $info;
}
protected function getFormattedAuthor() {
if ( !empty($this->author_homepage) ){
/** @noinspection HtmlUnknownTarget */
return sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
}
return $this->author;
}
}
endif;
@@ -0,0 +1,294 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
if ( !class_exists(Ui::class, false) ):
/**
* Additional UI elements for plugins.
*/
class Ui {
private $updateChecker;
private $manualCheckErrorTransient = '';
/**
* @param UpdateChecker $updateChecker
*/
public function __construct($updateChecker) {
$this->updateChecker = $updateChecker;
$this->manualCheckErrorTransient = $this->updateChecker->getUniqueName('manual_check_errors');
add_action('admin_init', array($this, 'onAdminInit'));
}
public function onAdminInit() {
if ( $this->updateChecker->userCanInstallUpdates() ) {
$this->handleManualCheck();
add_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10, 3);
add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
}
}
/**
* Add a "View Details" link to the plugin row in the "Plugins" page. By default,
* the new link will appear before the "Visit plugin site" link (if present).
*
* You can change the link text by using the "puc_view_details_link-$slug" filter.
* Returning an empty string from the filter will disable the link.
*
* You can change the position of the link using the
* "puc_view_details_link_position-$slug" filter.
* Returning 'before' or 'after' will place the link immediately before/after
* the "Visit plugin site" link.
* Returning 'append' places the link after any existing links at the time of the hook.
* Returning 'replace' replaces the "Visit plugin site" link.
* Returning anything else disables the link when there is a "Visit plugin site" link.
*
* If there is no "Visit plugin site" link 'append' is always used!
*
* @param array $pluginMeta Array of meta links.
* @param string $pluginFile
* @param array $pluginData Array of plugin header data.
* @return array
*/
public function addViewDetailsLink($pluginMeta, $pluginFile, $pluginData = array()) {
if ( $this->isMyPluginFile($pluginFile) && !isset($pluginData['slug']) ) {
$linkText = apply_filters($this->updateChecker->getUniqueName('view_details_link'), __('View details'));
if ( !empty($linkText) ) {
$viewDetailsLinkPosition = 'append';
//Find the "Visit plugin site" link (if present).
$visitPluginSiteLinkIndex = count($pluginMeta) - 1;
if ( $pluginData['PluginURI'] ) {
$escapedPluginUri = esc_url($pluginData['PluginURI']);
foreach ($pluginMeta as $linkIndex => $existingLink) {
if ( strpos($existingLink, $escapedPluginUri) !== false ) {
$visitPluginSiteLinkIndex = $linkIndex;
$viewDetailsLinkPosition = apply_filters(
$this->updateChecker->getUniqueName('view_details_link_position'),
'before'
);
break;
}
}
}
$viewDetailsLink = sprintf('<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
esc_url(network_admin_url('plugin-install.php?tab=plugin-information&plugin=' . urlencode($this->updateChecker->slug) .
'&TB_iframe=true&width=600&height=550')),
esc_attr(sprintf(__('More information about %s'), $pluginData['Name'])),
esc_attr($pluginData['Name']),
$linkText
);
switch ($viewDetailsLinkPosition) {
case 'before':
array_splice($pluginMeta, $visitPluginSiteLinkIndex, 0, $viewDetailsLink);
break;
case 'after':
array_splice($pluginMeta, $visitPluginSiteLinkIndex + 1, 0, $viewDetailsLink);
break;
case 'replace':
$pluginMeta[$visitPluginSiteLinkIndex] = $viewDetailsLink;
break;
case 'append':
default:
$pluginMeta[] = $viewDetailsLink;
break;
}
}
}
return $pluginMeta;
}
/**
* Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
* the new link will appear after the "Visit plugin site" link if present, otherwise
* after the "View plugin details" link.
*
* You can change the link text by using the "puc_manual_check_link-$slug" filter.
* Returning an empty string from the filter will disable the link.
*
* @param array $pluginMeta Array of meta links.
* @param string $pluginFile
* @return array
*/
public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
if ( $this->isMyPluginFile($pluginFile) ) {
$linkUrl = wp_nonce_url(
add_query_arg(
array(
'puc_check_for_updates' => 1,
'puc_slug' => $this->updateChecker->slug,
),
self_admin_url('plugins.php')
),
'puc_check_for_updates'
);
$linkText = apply_filters(
$this->updateChecker->getUniqueName('manual_check_link'),
__('Check for updates', 'plugin-update-checker')
);
if ( !empty($linkText) ) {
/** @noinspection HtmlUnknownTarget */
$pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
}
}
return $pluginMeta;
}
protected function isMyPluginFile($pluginFile) {
return ($pluginFile == $this->updateChecker->pluginFile)
|| (!empty($this->updateChecker->muPluginFile) && ($pluginFile == $this->updateChecker->muPluginFile));
}
/**
* Check for updates when the user clicks the "Check for updates" link.
*
* @see self::addCheckForUpdatesLink()
*
* @return void
*/
public function handleManualCheck() {
$shouldCheck =
isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
&& $_GET['puc_slug'] == $this->updateChecker->slug
&& check_admin_referer('puc_check_for_updates');
if ( $shouldCheck ) {
$update = $this->updateChecker->checkForUpdates();
$status = ($update === null) ? 'no_update' : 'update_available';
$lastRequestApiErrors = $this->updateChecker->getLastRequestApiErrors();
if ( ($update === null) && !empty($lastRequestApiErrors) ) {
//Some errors are not critical. For example, if PUC tries to retrieve the readme.txt
//file from GitHub and gets a 404, that's an API error, but it doesn't prevent updates
//from working. Maybe the plugin simply doesn't have a readme.
//Let's only show important errors.
$foundCriticalErrors = false;
$questionableErrorCodes = array(
'puc-github-http-error',
'puc-gitlab-http-error',
'puc-bitbucket-http-error',
);
foreach ($lastRequestApiErrors as $item) {
$wpError = $item['error'];
/** @var \WP_Error $wpError */
if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) {
$foundCriticalErrors = true;
break;
}
}
if ( $foundCriticalErrors ) {
$status = 'error';
set_site_transient($this->manualCheckErrorTransient, $lastRequestApiErrors, 60);
}
}
wp_safe_redirect(add_query_arg(
array(
'puc_update_check_result' => $status,
'puc_slug' => $this->updateChecker->slug,
),
self_admin_url('plugins.php')
));
exit;
}
}
/**
* Display the results of a manual update check.
*
* @see self::handleManualCheck()
*
* You can change the result message by using the "puc_manual_check_message-$slug" filter.
*/
public function displayManualCheckResult() {
//phpcs:disable WordPress.Security.NonceVerification.Recommended -- Just displaying a message.
if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->updateChecker->slug) ) {
$status = sanitize_key($_GET['puc_update_check_result']);
$title = $this->updateChecker->getInstalledPackage()->getPluginTitle();
$noticeClass = 'updated notice-success';
$details = '';
if ( $status == 'no_update' ) {
$message = sprintf(_x('The %s plugin is up to date.', 'the plugin title', 'plugin-update-checker'), $title);
} else if ( $status == 'update_available' ) {
$message = sprintf(_x('A new version of the %s plugin is available.', 'the plugin title', 'plugin-update-checker'), $title);
} else if ( $status === 'error' ) {
$message = sprintf(_x('Could not determine if updates are available for %s.', 'the plugin title', 'plugin-update-checker'), $title);
$noticeClass = 'error notice-error';
$details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient));
delete_site_transient($this->manualCheckErrorTransient);
} else {
$message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), $status);
$noticeClass = 'error notice-error';
}
$message = esc_html($message);
//Plugins can replace the message with their own, including adding HTML.
$message = apply_filters(
$this->updateChecker->getUniqueName('manual_check_message'),
$message,
$status
);
printf(
'<div class="notice %s is-dismissible"><p>%s</p>%s</div>',
esc_attr($noticeClass),
//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Was escaped above, and plugins can add HTML.
$message,
//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Contains HTML. Content should already be escaped.
$details
);
}
//phpcs:enable
}
/**
* Format the list of errors that were thrown during an update check.
*
* @param array $errors
* @return string
*/
protected function formatManualCheckErrors($errors) {
if ( empty($errors) ) {
return '';
}
$output = '';
$showAsList = count($errors) > 1;
if ( $showAsList ) {
$output .= '<ol>';
$formatString = '<li>%1$s <code>%2$s</code></li>';
} else {
$formatString = '<p>%1$s <code>%2$s</code></p>';
}
foreach ($errors as $item) {
$wpError = $item['error'];
/** @var \WP_Error $wpError */
$output .= sprintf(
$formatString,
esc_html($wpError->get_error_message()),
esc_html($wpError->get_error_code())
);
}
if ( $showAsList ) {
$output .= '</ol>';
}
return $output;
}
public function removeHooks() {
remove_action('admin_init', array($this, 'onAdminInit'));
remove_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10);
remove_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10);
remove_action('all_admin_notices', array($this, 'displayManualCheckResult'));
}
}
endif;
@@ -0,0 +1,118 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\Update as BaseUpdate;
if ( !class_exists(Update::class, false) ):
/**
* A simple container class for holding information about an available update.
*
* @author Janis Elsts
* @copyright 2016
* @access public
*/
class Update extends BaseUpdate {
public $id = 0;
public $homepage;
public $upgrade_notice;
public $tested;
public $requires_php = false;
public $icons = array();
public $filename; //Plugin filename relative to the plugins directory.
public $autoupdate = false;
protected static $extraFields = array(
'id', 'homepage', 'tested', 'requires_php', 'upgrade_notice', 'icons', 'filename', 'autoupdate',
);
/**
* Create a new instance of PluginUpdate from its JSON-encoded representation.
*
* @param string $json
* @return self|null
*/
public static function fromJson($json){
//Since update-related information is simply a subset of the full plugin info,
//we can parse the update JSON as if it was a plugin info string, then copy over
//the parts that we care about.
$pluginInfo = PluginInfo::fromJson($json);
if ( $pluginInfo !== null ) {
return self::fromPluginInfo($pluginInfo);
} else {
return null;
}
}
/**
* Create a new instance of PluginUpdate based on an instance of PluginInfo.
* Basically, this just copies a subset of fields from one object to another.
*
* @param PluginInfo $info
* @return static
*/
public static function fromPluginInfo($info){
return static::fromObject($info);
}
/**
* Create a new instance by copying the necessary fields from another object.
*
* @param \StdClass|PluginInfo|self $object The source object.
* @return self The new copy.
*/
public static function fromObject($object) {
$update = new self();
$update->copyFields($object, $update);
return $update;
}
/**
* @return string[]
*/
protected function getFieldNames() {
return array_merge(parent::getFieldNames(), self::$extraFields);
}
/**
* Transform the update into the format used by WordPress native plugin API.
*
* @return object
*/
public function toWpFormat() {
$update = parent::toWpFormat();
$update->id = $this->id;
$update->url = $this->homepage;
$update->tested = $this->tested;
$update->requires_php = $this->requires_php;
$update->plugin = $this->filename;
$update->autoupdate = $this->autoupdate;
if ( !empty($this->upgrade_notice) ) {
$update->upgrade_notice = $this->upgrade_notice;
}
if ( !empty($this->icons) && is_array($this->icons) ) {
//This should be an array with up to 4 keys: 'svg', '1x', '2x' and 'default'.
//Docs: https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons
$icons = array_intersect_key(
$this->icons,
array('svg' => true, '1x' => true, '2x' => true, 'default' => true)
);
if ( !empty($icons) ) {
$update->icons = $icons;
//It appears that the 'default' icon isn't used anywhere in WordPress 4.9,
//but lets set it just in case a future release needs it.
if ( !isset($update->icons['default']) ) {
$update->icons['default'] = current($update->icons);
}
}
}
return $update;
}
}
endif;
@@ -0,0 +1,425 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p6\UpdateChecker as BaseUpdateChecker;
use YahnisElsts\PluginUpdateChecker\v5p6\Scheduler;
use YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
if ( !class_exists(UpdateChecker::class, false) ):
/**
* A custom plugin update checker.
*
* @author Janis Elsts
* @copyright 2018
* @access public
*/
class UpdateChecker extends BaseUpdateChecker {
protected $updateTransient = 'update_plugins';
protected $componentType = 'plugin';
public $pluginAbsolutePath = ''; //Full path of the main plugin file.
public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
/**
* @var Package
*/
protected $package;
private $extraUi = null;
/**
* Class constructor.
*
* @param string $metadataUrl The URL of the plugin's metadata file.
* @param string $pluginFile Fully qualified path to the main plugin file.
* @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
* @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
* @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
* @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
*/
public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
$this->pluginAbsolutePath = $pluginFile;
$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
$this->muPluginFile = $muPluginFile;
//If no slug is specified, use the name of the main plugin file as the slug.
//For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
if ( empty($slug) ){
$slug = basename($this->pluginFile, '.php');
}
//Plugin slugs must be unique.
$slugCheckFilter = 'puc_is_slug_in_use-' . $slug;
$slugUsedBy = apply_filters($slugCheckFilter, false);
if ( $slugUsedBy ) {
$this->triggerError(sprintf(
'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
$slug,
$slugUsedBy
), E_USER_ERROR);
}
add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));
parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName);
//Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
//it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
$this->muPluginFile = $this->pluginFile;
}
//To prevent a crash during plugin uninstallation, remove updater hooks when the user removes the plugin.
//Details: https://github.com/YahnisElsts/plugin-update-checker/issues/138#issuecomment-335590964
add_action('uninstall_' . $this->pluginFile, array($this, 'removeHooks'));
$this->extraUi = new Ui($this);
}
/**
* Create an instance of the scheduler.
*
* @param int $checkPeriod
* @return Scheduler
*/
protected function createScheduler($checkPeriod) {
$scheduler = new Scheduler($this, $checkPeriod, array('load-plugins.php'));
register_deactivation_hook($this->pluginFile, array($scheduler, 'removeUpdaterCron'));
return $scheduler;
}
/**
* Install the hooks required to run periodic update checks and inject update info
* into WP data structures.
*
* @return void
*/
protected function installHooks(){
//Override requests for plugin information
add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
parent::installHooks();
}
/**
* Remove update checker hooks.
*
* The intent is to prevent a fatal error that can happen if the plugin has an uninstall
* hook. During uninstallation, WP includes the main plugin file (which creates a PUC instance),
* the uninstall hook runs, WP deletes the plugin files and then updates some transients.
* If PUC hooks are still around at this time, they could throw an error while trying to
* autoload classes from files that no longer exist.
*
* The "site_transient_{$transient}" filter is the main problem here, but let's also remove
* most other PUC hooks to be safe.
*
* @internal
*/
public function removeHooks() {
parent::removeHooks();
$this->extraUi->removeHooks();
$this->package->removeHooks();
remove_filter('plugins_api', array($this, 'injectInfo'), 20);
}
/**
* Retrieve plugin info from the configured API endpoint.
*
* @uses wp_remote_get()
*
* @param array $queryArgs Additional query arguments to append to the request. Optional.
* @return PluginInfo
*/
public function requestInfo($queryArgs = array()) {
list($pluginInfo, $result) = $this->requestMetadata(
PluginInfo::class,
'request_info',
$queryArgs
);
if ( $pluginInfo !== null ) {
/** @var PluginInfo $pluginInfo */
$pluginInfo->filename = $this->pluginFile;
$pluginInfo->slug = $this->slug;
}
$pluginInfo = apply_filters($this->getUniqueName('request_info_result'), $pluginInfo, $result);
return $pluginInfo;
}
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @uses UpdateChecker::requestInfo()
*
* @return Update|null An instance of Plugin Update, or NULL when no updates are available.
*/
public function requestUpdate() {
//For the sake of simplicity, this function just calls requestInfo()
//and transforms the result accordingly.
$pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
if ( $pluginInfo === null ){
return null;
}
$update = Update::fromPluginInfo($pluginInfo);
$update = $this->filterUpdateResult($update);
return $update;
}
/**
* Intercept plugins_api() calls that request information about our plugin and
* use the configured API endpoint to satisfy them.
*
* @see plugins_api()
*
* @param mixed $result
* @param string $action
* @param array|object $args
* @return mixed
*/
public function injectInfo($result, $action = null, $args = null){
$relevant = ($action == 'plugin_information') && isset($args->slug) && (
($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
);
if ( !$relevant ) {
return $result;
}
$pluginInfo = $this->requestInfo();
$this->fixSupportedWordpressVersion($pluginInfo);
$pluginInfo = apply_filters($this->getUniqueName('pre_inject_info'), $pluginInfo);
if ( $pluginInfo ) {
return $pluginInfo->toWpFormat();
}
return $result;
}
protected function shouldShowUpdates() {
//No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
//is usually different from the main plugin file so the update wouldn't show up properly anyway.
return !$this->isUnknownMuPlugin();
}
/**
* @param \stdClass|null $updates
* @param \stdClass $updateToAdd
* @return \stdClass
*/
protected function addUpdateToList($updates, $updateToAdd) {
if ( $this->package->isMuPlugin() ) {
//WP does not support automatic update installation for mu-plugins, but we can
//still display a notice.
$updateToAdd->package = null;
}
return parent::addUpdateToList($updates, $updateToAdd);
}
/**
* @param \stdClass|null $updates
* @return \stdClass|null
*/
protected function removeUpdateFromList($updates) {
$updates = parent::removeUpdateFromList($updates);
if ( !empty($this->muPluginFile) && isset($updates, $updates->response) ) {
unset($updates->response[$this->muPluginFile]);
}
return $updates;
}
/**
* For plugins, the update array is indexed by the plugin filename relative to the "plugins"
* directory. Example: "plugin-name/plugin.php".
*
* @return string
*/
protected function getUpdateListKey() {
if ( $this->package->isMuPlugin() ) {
return $this->muPluginFile;
}
return $this->pluginFile;
}
protected function getNoUpdateItemFields() {
return array_merge(
parent::getNoUpdateItemFields(),
array(
'id' => $this->pluginFile,
'slug' => $this->slug,
'plugin' => $this->pluginFile,
'icons' => array(),
'banners' => array(),
'banners_rtl' => array(),
'tested' => '',
'compatibility' => new \stdClass(),
)
);
}
/**
* Alias for isBeingUpgraded().
*
* @deprecated
* @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool
*/
public function isPluginBeingUpgraded($upgrader = null) {
return $this->isBeingUpgraded($upgrader);
}
/**
* Is there an update being installed for this plugin, right now?
*
* @param \WP_Upgrader|null $upgrader
* @return bool
*/
public function isBeingUpgraded($upgrader = null) {
return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader);
}
/**
* Get the details of the currently available update, if any.
*
* If no updates are available, or if the last known update version is below or equal
* to the currently installed version, this method will return NULL.
*
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return Update|null
*/
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) ) {
/** @var Update $update */
$update->filename = $this->pluginFile;
}
return $update;
}
/**
* Get the translated plugin title.
*
* @deprecated
* @return string
*/
public function getPluginTitle() {
return $this->package->getPluginTitle();
}
/**
* Check if the current user has the required permissions to install updates.
*
* @return bool
*/
public function userCanInstallUpdates() {
return current_user_can('update_plugins');
}
/**
* Check if the plugin file is inside the mu-plugins directory.
*
* @deprecated
* @return bool
*/
protected function isMuPlugin() {
return $this->package->isMuPlugin();
}
/**
* MU plugins are partially supported, but only when we know which file in mu-plugins
* corresponds to this plugin.
*
* @return bool
*/
protected function isUnknownMuPlugin() {
return empty($this->muPluginFile) && $this->package->isMuPlugin();
}
/**
* Get absolute path to the main plugin file.
*
* @return string
*/
public function getAbsolutePath() {
return $this->pluginAbsolutePath;
}
/**
* Register a callback for filtering query arguments.
*
* The callback function should take one argument - an associative array of query arguments.
* It should return a modified array of query arguments.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addQueryArgFilter($callback){
$this->addFilter('request_info_query_args', $callback);
}
/**
* Register a callback for filtering arguments passed to wp_remote_get().
*
* The callback function should take one argument - an associative array of arguments -
* and return a modified array or arguments. See the WP documentation on wp_remote_get()
* for details on what arguments are available and how they work.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addHttpRequestArgFilter($callback) {
$this->addFilter('request_info_options', $callback);
}
/**
* Register a callback for filtering the plugin info retrieved from the external API.
*
* The callback function should take two arguments. If the plugin info was retrieved
* successfully, the first argument passed will be an instance of PluginInfo. Otherwise,
* it will be NULL. The second argument will be the corresponding return value of
* wp_remote_get (see WP docs for details).
*
* The callback function should return a new or modified instance of PluginInfo or NULL.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addResultFilter($callback) {
$this->addFilter('request_info_result', $callback, 10, 2);
}
protected function createDebugBarExtension() {
return new DebugBar\PluginExtension($this);
}
/**
* Create a package instance that represents this plugin or theme.
*
* @return InstalledPackage
*/
protected function createInstalledPackage() {
return new Package($this->pluginAbsolutePath, $this);
}
/**
* @return Package
*/
public function getInstalledPackage() {
return $this->package;
}
}
endif;
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,362 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
use YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
use YahnisElsts\PluginUpdateChecker\v5p6\Theme;
use YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !class_exists(PucFactory::class, false) ):
/**
* A factory that builds update checker instances.
*
* When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 4.0
* and 4.1), this factory will always use the latest available minor version. Register class
* versions by calling {@link PucFactory::addVersion()}.
*
* At the moment it can only build instances of the UpdateChecker class. Other classes are
* intended mainly for internal use and refer directly to specific implementations.
*/
class PucFactory {
protected static $classVersions = array();
protected static $sorted = false;
protected static $myMajorVersion = '';
protected static $latestCompatibleVersion = '';
/**
* A wrapper method for buildUpdateChecker() that reads the metadata URL from the plugin or theme header.
*
* @param string $fullPath Full path to the main plugin file or the theme's style.css.
* @param array $args Optional arguments. Keys should match the argument names of the buildUpdateChecker() method.
* @return Plugin\UpdateChecker|Theme\UpdateChecker|Vcs\BaseChecker
*/
public static function buildFromHeader($fullPath, $args = array()) {
$fullPath = self::normalizePath($fullPath);
//Set up defaults.
$defaults = array(
'metadataUrl' => '',
'slug' => '',
'checkPeriod' => 12,
'optionName' => '',
'muPluginFile' => '',
);
$args = array_merge($defaults, array_intersect_key($args, $defaults));
extract($args, EXTR_SKIP);
//Check for the service URI
if ( empty($metadataUrl) ) {
$metadataUrl = self::getServiceURI($fullPath);
}
return self::buildUpdateChecker($metadataUrl, $fullPath, $slug, $checkPeriod, $optionName, $muPluginFile);
}
/**
* Create a new instance of the update checker.
*
* This method automatically detects if you're using it for a plugin or a theme and chooses
* the appropriate implementation for your update source (JSON file, GitHub, BitBucket, etc).
*
* @see UpdateChecker::__construct
*
* @param string $metadataUrl The URL of the metadata file, a GitHub repository, or another supported update source.
* @param string $fullPath Full path to the main plugin file or to the theme directory.
* @param string $slug Custom slug. Defaults to the name of the main plugin file or the theme directory.
* @param int $checkPeriod How often to check for updates (in hours).
* @param string $optionName Where to store bookkeeping info about update checks.
* @param string $muPluginFile The plugin filename relative to the mu-plugins directory.
* @return Plugin\UpdateChecker|Theme\UpdateChecker|Vcs\BaseChecker
*/
public static function buildUpdateChecker($metadataUrl, $fullPath, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$fullPath = self::normalizePath($fullPath);
$id = null;
//Plugin or theme?
$themeDirectory = self::getThemeDirectoryName($fullPath);
if ( self::isPluginFile($fullPath) ) {
$type = 'Plugin';
$id = $fullPath;
} else if ( $themeDirectory !== null ) {
$type = 'Theme';
$id = $themeDirectory;
} else {
throw new \RuntimeException(sprintf(
'The update checker cannot determine if "%s" is a plugin or a theme. ' .
'This is a bug. Please contact the PUC developer.',
esc_html($fullPath)
));
}
//Which hosting service does the URL point to?
$service = self::getVcsService($metadataUrl);
$apiClass = null;
if ( empty($service) ) {
//The default is to get update information from a remote JSON file.
$checkerClass = $type . '\\UpdateChecker';
} else {
//You can also use a VCS repository like GitHub.
$checkerClass = 'Vcs\\' . $type . 'UpdateChecker';
$apiClass = $service . 'Api';
}
$checkerClass = self::getCompatibleClassVersion($checkerClass);
if ( $checkerClass === null ) {
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
trigger_error(
esc_html(sprintf(
'PUC %s does not support updates for %ss %s',
self::$latestCompatibleVersion,
strtolower($type),
$service ? ('hosted on ' . $service) : 'using JSON metadata'
)),
E_USER_ERROR
);
}
if ( !isset($apiClass) ) {
//Plain old update checker.
return new $checkerClass($metadataUrl, $id, $slug, $checkPeriod, $optionName, $muPluginFile);
} else {
//VCS checker + an API client.
$apiClass = self::getCompatibleClassVersion($apiClass);
if ( $apiClass === null ) {
//phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
trigger_error(esc_html(sprintf(
'PUC %s does not support %s',
self::$latestCompatibleVersion,
$service
)), E_USER_ERROR);
}
return new $checkerClass(
new $apiClass($metadataUrl),
$id,
$slug,
$checkPeriod,
$optionName,
$muPluginFile
);
}
}
/**
*
* Normalize a filesystem path. Introduced in WP 3.9.
* Copying here allows use of the class on earlier versions.
* This version adapted from WP 4.8.2 (unchanged since 4.5.6)
*
* @param string $path Path to normalize.
* @return string Normalized path.
*/
public static function normalizePath($path) {
if ( function_exists('wp_normalize_path') ) {
return wp_normalize_path($path);
}
$path = str_replace('\\', '/', $path);
$path = preg_replace('|(?<=.)/+|', '/', $path);
if ( substr($path, 1, 1) === ':' ) {
$path = ucfirst($path);
}
return $path;
}
/**
* Check if the path points to a plugin file.
*
* @param string $absolutePath Normalized path.
* @return bool
*/
protected static function isPluginFile($absolutePath) {
//Is the file inside the "plugins" or "mu-plugins" directory?
$pluginDir = self::normalizePath(WP_PLUGIN_DIR);
$muPluginDir = self::normalizePath(WPMU_PLUGIN_DIR);
if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
return true;
}
//Is it a file at all? Caution: is_file() can fail if the parent dir. doesn't have the +x permission set.
if ( !is_file($absolutePath) ) {
return false;
}
//Does it have a valid plugin header?
//This is a last-ditch check for plugins symlinked from outside the WP root.
if ( function_exists('get_file_data') ) {
$headers = get_file_data($absolutePath, array('Name' => 'Plugin Name'), 'plugin');
return !empty($headers['Name']);
}
return false;
}
/**
* Get the name of the theme's directory from a full path to a file inside that directory.
* E.g. "/abc/public_html/wp-content/themes/foo/whatever.php" => "foo".
*
* Note that subdirectories are currently not supported. For example,
* "/xyz/wp-content/themes/my-theme/includes/whatever.php" => NULL.
*
* @param string $absolutePath Normalized path.
* @return string|null Directory name, or NULL if the path doesn't point to a theme.
*/
protected static function getThemeDirectoryName($absolutePath) {
if ( is_file($absolutePath) ) {
$absolutePath = dirname($absolutePath);
}
if ( file_exists($absolutePath . '/style.css') ) {
return basename($absolutePath);
}
return null;
}
/**
* Get the service URI from the file header.
*
* @param string $fullPath
* @return string
*/
private static function getServiceURI($fullPath) {
//Look for the URI
if ( is_readable($fullPath) ) {
$seek = array(
'github' => 'GitHub URI',
'gitlab' => 'GitLab URI',
'bucket' => 'BitBucket URI',
);
$seek = apply_filters('puc_get_source_uri', $seek);
$data = get_file_data($fullPath, $seek);
foreach ($data as $key => $uri) {
if ( $uri ) {
return $uri;
}
}
}
//URI was not found so throw an error.
throw new \RuntimeException(
sprintf('Unable to locate URI in header of "%s"', esc_html($fullPath))
);
}
/**
* Get the name of the hosting service that the URL points to.
*
* @param string $metadataUrl
* @return string|null
*/
private static function getVcsService($metadataUrl) {
$service = null;
//Which hosting service does the URL point to?
$host = (string)(wp_parse_url($metadataUrl, PHP_URL_HOST));
$path = (string)(wp_parse_url($metadataUrl, PHP_URL_PATH));
//Check if the path looks like "/user-name/repository".
//For GitLab.com it can also be "/user/group1/group2/.../repository".
$repoRegex = '@^/?([^/]+?)/([^/#?&]+?)/?$@';
if ( $host === 'gitlab.com' ) {
$repoRegex = '@^/?(?:[^/#?&]++/){1,20}(?:[^/#?&]++)/?$@';
}
if ( preg_match($repoRegex, $path) ) {
$knownServices = array(
'github.com' => 'GitHub',
'bitbucket.org' => 'BitBucket',
'gitlab.com' => 'GitLab',
);
if ( isset($knownServices[$host]) ) {
$service = $knownServices[$host];
}
}
return apply_filters('puc_get_vcs_service', $service, $host, $path, $metadataUrl);
}
/**
* Get the latest version of the specified class that has the same major version number
* as this factory class.
*
* @param string $class Partial class name.
* @return string|null Full class name.
*/
protected static function getCompatibleClassVersion($class) {
if ( isset(self::$classVersions[$class][self::$latestCompatibleVersion]) ) {
return self::$classVersions[$class][self::$latestCompatibleVersion];
}
return null;
}
/**
* Get the specific class name for the latest available version of a class.
*
* @param string $class
* @return null|string
*/
public static function getLatestClassVersion($class) {
if ( !self::$sorted ) {
self::sortVersions();
}
if ( isset(self::$classVersions[$class]) ) {
return reset(self::$classVersions[$class]);
} else {
return null;
}
}
/**
* Sort available class versions in descending order (i.e. newest first).
*/
protected static function sortVersions() {
foreach ( self::$classVersions as $class => $versions ) {
uksort($versions, array(__CLASS__, 'compareVersions'));
self::$classVersions[$class] = $versions;
}
self::$sorted = true;
}
protected static function compareVersions($a, $b) {
return -version_compare($a, $b);
}
/**
* Register a version of a class.
*
* @access private This method is only for internal use by the library.
*
* @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
* @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
* @param string $version Version number, e.g. '1.2'.
*/
public static function addVersion($generalClass, $versionedClass, $version) {
if ( empty(self::$myMajorVersion) ) {
$lastNamespaceSegment = substr(__NAMESPACE__, strrpos(__NAMESPACE__, '\\') + 1);
self::$myMajorVersion = substr(ltrim($lastNamespaceSegment, 'v'), 0, 1);
}
//Store the greatest version number that matches our major version.
$components = explode('.', $version);
if ( $components[0] === self::$myMajorVersion ) {
if (
empty(self::$latestCompatibleVersion)
|| version_compare($version, self::$latestCompatibleVersion, '>')
) {
self::$latestCompatibleVersion = $version;
}
}
if ( !isset(self::$classVersions[$generalClass]) ) {
self::$classVersions[$generalClass] = array();
}
self::$classVersions[$generalClass][$version] = $versionedClass;
self::$sorted = false;
}
}
endif;
@@ -0,0 +1,300 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists(Scheduler::class, false) ):
/**
* The scheduler decides when and how often to check for updates.
* It calls @see UpdateChecker::checkForUpdates() to perform the actual checks.
*/
class Scheduler {
public $checkPeriod = 12; //How often to check for updates (in hours).
public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
public $throttledCheckPeriod = 72;
protected $hourlyCheckHooks = array('load-update.php');
/**
* @var UpdateChecker
*/
protected $updateChecker;
private $cronHook = null;
/**
* Scheduler constructor.
*
* @param UpdateChecker $updateChecker
* @param int $checkPeriod How often to check for updates (in hours).
* @param array $hourlyHooks
*/
public function __construct($updateChecker, $checkPeriod, $hourlyHooks = array('load-plugins.php')) {
$this->updateChecker = $updateChecker;
$this->checkPeriod = $checkPeriod;
//Set up the periodic update checks
$this->cronHook = $this->updateChecker->getUniqueName('cron_check_updates');
if ( $this->checkPeriod > 0 ){
//Trigger the check via Cron.
//Try to use one of the default schedules if possible as it's less likely to conflict
//with other plugins and their custom schedules.
$defaultSchedules = array(
1 => 'hourly',
12 => 'twicedaily',
24 => 'daily',
);
if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
$scheduleName = $defaultSchedules[$this->checkPeriod];
} else {
//Use a custom cron schedule.
$scheduleName = 'every' . $this->checkPeriod . 'hours';
//phpcs:ignore WordPress.WP.CronInterval.ChangeDetected -- WPCS fails to parse the callback.
add_filter('cron_schedules', array($this, '_addCustomSchedule'));
}
if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
//Randomly offset the schedule to help prevent update server traffic spikes. Without this
//most checks may happen during times of day when people are most likely to install new plugins.
$upperLimit = max($this->checkPeriod * 3600 - 15 * 60, 1);
if ( function_exists('wp_rand') ) {
$randomOffset = wp_rand(0, $upperLimit);
} else {
//This constructor may be called before wp_rand() is available.
//phpcs:ignore WordPress.WP.AlternativeFunctions.rand_rand
$randomOffset = rand(0, $upperLimit);
}
$firstCheckTime = time() - $randomOffset;
$firstCheckTime = apply_filters(
$this->updateChecker->getUniqueName('first_check_time'),
$firstCheckTime
);
wp_schedule_event($firstCheckTime, $scheduleName, $this->cronHook);
}
add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
//In case Cron is disabled or unreliable, we also manually trigger
//the periodic checks while the user is browsing the Dashboard.
add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );
//Like WordPress itself, we check more often on certain pages.
/** @see wp_update_plugins */
add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
//phpcs:ignore Squiz.PHP.CommentedOutCode.Found -- Not actually code, just file names.
//"load-update.php" and "load-plugins.php" or "load-themes.php".
$this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks);
foreach($this->hourlyCheckHooks as $hook) {
add_action($hook, array($this, 'maybeCheckForUpdates'));
}
//This hook fires after a bulk update is complete.
add_action('upgrader_process_complete', array($this, 'removeHooksIfLibraryGone'), 1, 0);
add_action('upgrader_process_complete', array($this, 'upgraderProcessComplete'), 11, 2);
} else {
//Periodic checks are disabled.
wp_clear_scheduled_hook($this->cronHook);
}
}
/**
* Remove all hooks if this version of PUC has been deleted or overwritten.
*
* Callback for the "upgrader_process_complete" action.
*/
public function removeHooksIfLibraryGone() {
//Cancel all further actions if the current version of PUC has been deleted or overwritten
//by a different version during the upgrade. If we try to do anything more in that situation,
//we could trigger a fatal error by trying to autoload a deleted class.
clearstatcache();
if ( !file_exists(__FILE__) ) {
$this->removeHooks();
$this->updateChecker->removeHooks();
}
}
/**
* Runs upon the WP action upgrader_process_complete.
*
* We look at the parameters to decide whether to call maybeCheckForUpdates() or not.
* We also check if the update checker has been removed by the update.
*
* @param \WP_Upgrader $upgrader WP_Upgrader instance
* @param array $upgradeInfo extra information about the upgrade
*/
public function upgraderProcessComplete(
/** @noinspection PhpUnusedParameterInspection */
$upgrader, $upgradeInfo
) {
//Sanity check and limitation to relevant types.
if (
!is_array($upgradeInfo) || !isset($upgradeInfo['type'], $upgradeInfo['action'])
|| 'update' !== $upgradeInfo['action'] || !in_array($upgradeInfo['type'], array('plugin', 'theme'))
) {
return;
}
//Filter out notifications of upgrades that should have no bearing upon whether or not our
//current info is up-to-date.
if ( is_a($this->updateChecker, Theme\UpdateChecker::class) ) {
if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) {
return;
}
//Letting too many things going through for checks is not a real problem, so we compare widely.
if ( !in_array(
strtolower($this->updateChecker->directoryName),
array_map('strtolower', $upgradeInfo['themes'])
) ) {
return;
}
}
if ( is_a($this->updateChecker, Plugin\UpdateChecker::class) ) {
if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) {
return;
}
//Themes pass in directory names in the information array, but plugins use the relative plugin path.
if ( !in_array(
strtolower($this->updateChecker->directoryName),
array_map('dirname', array_map('strtolower', $upgradeInfo['plugins']))
) ) {
return;
}
}
$this->maybeCheckForUpdates();
}
/**
* Check for updates if the configured check interval has already elapsed.
* Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
*
* You can override the default behaviour by using the "puc_check_now-$slug" filter.
* The filter callback will be passed three parameters:
* - Current decision. TRUE = check updates now, FALSE = don't check now.
* - Last check time as a Unix timestamp.
* - Configured check period in hours.
* Return TRUE to check for updates immediately, or FALSE to cancel.
*
* This method is declared public because it's a hook callback. Calling it directly is not recommended.
*/
public function maybeCheckForUpdates() {
if ( empty($this->checkPeriod) ){
return;
}
$state = $this->updateChecker->getUpdateState();
$shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod());
if ( $shouldCheck ) {
//Sanity check: Do not proceed if one of the critical classes is missing.
//That can happen - theoretically and extremely rarely - if maybeCheckForUpdates()
//is called before the old version of our plugin has been fully deleted, or
//called from an independent AJAX request during deletion.
if ( !(
class_exists(Utils::class)
&& class_exists(Metadata::class)
&& class_exists(Plugin\Update::class)
&& class_exists(Theme\Update::class)
) ) {
return;
}
}
//Let plugin authors substitute their own algorithm.
$shouldCheck = apply_filters(
$this->updateChecker->getUniqueName('check_now'),
$shouldCheck,
$state->getLastCheck(),
$this->checkPeriod
);
if ( $shouldCheck ) {
$this->updateChecker->checkForUpdates();
}
}
/**
* Calculate the actual check period based on the current status and environment.
*
* @return int Check period in seconds.
*/
protected function getEffectiveCheckPeriod() {
$currentFilter = current_filter();
if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
//Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
$period = 60;
} else if ( in_array($currentFilter, $this->hourlyCheckHooks) ) {
//Also check more often on /wp-admin/update.php and the "Plugins" or "Themes" page.
$period = 3600;
} else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
//Check less frequently if it's already known that an update is available.
$period = $this->throttledCheckPeriod * 3600;
} else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
//WordPress cron schedules are not exact, so let's do an update check even
//if slightly less than $checkPeriod hours have elapsed since the last check.
$cronFuzziness = 20 * 60;
$period = $this->checkPeriod * 3600 - $cronFuzziness;
} else {
$period = $this->checkPeriod * 3600;
}
return $period;
}
/**
* Add our custom schedule to the array of Cron schedules used by WP.
*
* @param array $schedules
* @return array
*/
public function _addCustomSchedule($schedules) {
if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
$scheduleName = 'every' . $this->checkPeriod . 'hours';
$schedules[$scheduleName] = array(
'interval' => $this->checkPeriod * 3600,
'display' => sprintf('Every %d hours', $this->checkPeriod),
);
}
return $schedules;
}
/**
* Remove the scheduled cron event that the library uses to check for updates.
*
* @return void
*/
public function removeUpdaterCron() {
wp_clear_scheduled_hook($this->cronHook);
}
/**
* Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
*
* @return string
*/
public function getCronHookName() {
return $this->cronHook;
}
/**
* Remove most hooks added by the scheduler.
*/
public function removeHooks() {
remove_filter('cron_schedules', array($this, '_addCustomSchedule'));
remove_action('admin_init', array($this, 'maybeCheckForUpdates'));
remove_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
if ( $this->cronHook !== null ) {
remove_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
}
if ( !empty($this->hourlyCheckHooks) ) {
foreach ($this->hourlyCheckHooks as $hook) {
remove_action($hook, array($this, 'maybeCheckForUpdates'));
}
}
}
}
endif;
@@ -0,0 +1,214 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists(StateStore::class, false) ):
class StateStore {
/**
* @var int Last update check timestamp.
*/
protected $lastCheck = 0;
/**
* @var string Version number.
*/
protected $checkedVersion = '';
/**
* @var Update|null Cached update.
*/
protected $update = null;
/**
* @var string Site option name.
*/
private $optionName = '';
/**
* @var bool Whether we've already tried to load the state from the database.
*/
private $isLoaded = false;
public function __construct($optionName) {
$this->optionName = $optionName;
}
/**
* Get time elapsed since the last update check.
*
* If there are no recorded update checks, this method returns a large arbitrary number
* (i.e. time since the Unix epoch).
*
* @return int Elapsed time in seconds.
*/
public function timeSinceLastCheck() {
$this->lazyLoad();
return time() - $this->lastCheck;
}
/**
* @return int
*/
public function getLastCheck() {
$this->lazyLoad();
return $this->lastCheck;
}
/**
* Set the time of the last update check to the current timestamp.
*
* @return $this
*/
public function setLastCheckToNow() {
$this->lazyLoad();
$this->lastCheck = time();
return $this;
}
/**
* @return null|Update
*/
public function getUpdate() {
$this->lazyLoad();
return $this->update;
}
/**
* @param Update|null $update
* @return $this
*/
public function setUpdate($update = null) {
$this->lazyLoad();
$this->update = $update;
return $this;
}
/**
* @return string
*/
public function getCheckedVersion() {
$this->lazyLoad();
return $this->checkedVersion;
}
/**
* @param string $version
* @return $this
*/
public function setCheckedVersion($version) {
$this->lazyLoad();
$this->checkedVersion = strval($version);
return $this;
}
/**
* Get translation updates.
*
* @return array
*/
public function getTranslations() {
$this->lazyLoad();
if ( isset($this->update, $this->update->translations) ) {
return $this->update->translations;
}
return array();
}
/**
* Set translation updates.
*
* @param array $translationUpdates
*/
public function setTranslations($translationUpdates) {
$this->lazyLoad();
if ( isset($this->update) ) {
$this->update->translations = $translationUpdates;
$this->save();
}
}
public function save() {
$state = new \stdClass();
$state->lastCheck = $this->lastCheck;
$state->checkedVersion = $this->checkedVersion;
if ( isset($this->update)) {
$state->update = $this->update->toStdClass();
$updateClass = get_class($this->update);
$state->updateClass = $updateClass;
$prefix = $this->getLibPrefix();
if ( Utils::startsWith($updateClass, $prefix) ) {
$state->updateBaseClass = substr($updateClass, strlen($prefix));
}
}
update_site_option($this->optionName, $state);
$this->isLoaded = true;
}
/**
* @return $this
*/
public function lazyLoad() {
if ( !$this->isLoaded ) {
$this->load();
}
return $this;
}
protected function load() {
$this->isLoaded = true;
$state = get_site_option($this->optionName, null);
if (
!is_object($state)
//Sanity check: If the Utils class is missing, the plugin is probably in the process
//of being deleted (e.g. the old version gets deleted during an update).
|| !class_exists(Utils::class)
) {
$this->lastCheck = 0;
$this->checkedVersion = '';
$this->update = null;
return;
}
$this->lastCheck = intval(Utils::get($state, 'lastCheck', 0));
$this->checkedVersion = Utils::get($state, 'checkedVersion', '');
$this->update = null;
if ( isset($state->update) ) {
//This mess is due to the fact that the want the update class from this version
//of the library, not the version that saved the update.
$updateClass = null;
if ( isset($state->updateBaseClass) ) {
$updateClass = $this->getLibPrefix() . $state->updateBaseClass;
} else if ( isset($state->updateClass) ) {
$updateClass = $state->updateClass;
}
$factory = array($updateClass, 'fromObject');
if ( ($updateClass !== null) && is_callable($factory) ) {
$this->update = call_user_func($factory, $state->update);
}
}
}
public function delete() {
delete_site_option($this->optionName);
$this->lastCheck = 0;
$this->checkedVersion = '';
$this->update = null;
}
private function getLibPrefix() {
//This assumes that the current class is at the top of the versioned namespace.
return __NAMESPACE__ . '\\';
}
}
endif;
@@ -0,0 +1,69 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Theme;
use YahnisElsts\PluginUpdateChecker\v5p6\InstalledPackage;
if ( !class_exists(Package::class, false) ):
class Package extends InstalledPackage {
/**
* @var string Theme directory name.
*/
protected $stylesheet;
/**
* @var \WP_Theme Theme object.
*/
protected $theme;
public function __construct($stylesheet, $updateChecker) {
$this->stylesheet = $stylesheet;
$this->theme = wp_get_theme($this->stylesheet);
parent::__construct($updateChecker);
}
public function getInstalledVersion() {
return $this->theme->get('Version');
}
public function getAbsoluteDirectoryPath() {
if ( method_exists($this->theme, 'get_stylesheet_directory') ) {
return $this->theme->get_stylesheet_directory(); //Available since WP 3.4.
}
return get_theme_root($this->stylesheet) . '/' . $this->stylesheet;
}
/**
* Get the value of a specific plugin or theme header.
*
* @param string $headerName
* @param string $defaultValue
* @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty.
*/
public function getHeaderValue($headerName, $defaultValue = '') {
$value = $this->theme->get($headerName);
if ( ($headerName === false) || ($headerName === '') ) {
return $defaultValue;
}
return $value;
}
protected function getHeaderNames() {
return array(
'Name' => 'Theme Name',
'ThemeURI' => 'Theme URI',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'Version' => 'Version',
'Template' => 'Template',
'Status' => 'Status',
'Tags' => 'Tags',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
);
}
}
endif;
@@ -0,0 +1,88 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Theme;
use YahnisElsts\PluginUpdateChecker\v5p6\Update as BaseUpdate;
if ( !class_exists(Update::class, false) ):
class Update extends BaseUpdate {
public $details_url = '';
protected static $extraFields = array('details_url');
/**
* Transform the metadata into the format used by WordPress core.
* Note the inconsistency: WP stores plugin updates as objects and theme updates as arrays.
*
* @return array
*/
public function toWpFormat() {
$update = array(
'theme' => $this->slug,
'new_version' => $this->version,
'url' => $this->details_url,
);
if ( !empty($this->download_url) ) {
$update['package'] = $this->download_url;
}
return $update;
}
/**
* Create a new instance of Theme_Update from its JSON-encoded representation.
*
* @param string $json Valid JSON string representing a theme information object.
* @return self New instance of ThemeUpdate, or NULL on error.
*/
public static function fromJson($json) {
$instance = new self();
if ( !parent::createFromJson($json, $instance) ) {
return null;
}
return $instance;
}
/**
* Create a new instance by copying the necessary fields from another object.
*
* @param \StdClass|self $object The source object.
* @return self The new copy.
*/
public static function fromObject($object) {
$update = new self();
$update->copyFields($object, $update);
return $update;
}
/**
* Basic validation.
*
* @param \StdClass $apiResponse
* @return bool|\WP_Error
*/
protected function validateMetadata($apiResponse) {
$required = array('version', 'details_url');
foreach($required as $key) {
if ( !isset($apiResponse->$key) || empty($apiResponse->$key) ) {
return new \WP_Error(
'tuc-invalid-metadata',
sprintf('The theme metadata is missing the required "%s" key.', $key)
);
}
}
return true;
}
protected function getFieldNames() {
return array_merge(parent::getFieldNames(), self::$extraFields);
}
protected function getPrefixedFilter($tag) {
return parent::getPrefixedFilter($tag) . '_theme';
}
}
endif;
@@ -0,0 +1,159 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Theme;
use YahnisElsts\PluginUpdateChecker\v5p6\UpdateChecker as BaseUpdateChecker;
use YahnisElsts\PluginUpdateChecker\v5p6\InstalledPackage;
use YahnisElsts\PluginUpdateChecker\v5p6\Scheduler;
use YahnisElsts\PluginUpdateChecker\v5p6\DebugBar;
if ( !class_exists(UpdateChecker::class, false) ):
class UpdateChecker extends BaseUpdateChecker {
protected $filterSuffix = 'theme';
protected $updateTransient = 'update_themes';
protected $componentType = 'theme';
/**
* @var string Theme directory name.
*/
protected $stylesheet;
public function __construct($metadataUrl, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
if ( $stylesheet === null ) {
$stylesheet = get_stylesheet();
}
$this->stylesheet = $stylesheet;
parent::__construct(
$metadataUrl,
$stylesheet,
$customSlug ? $customSlug : $stylesheet,
$checkPeriod,
$optionName
);
}
/**
* For themes, the update array is indexed by theme directory name.
*
* @return string
*/
protected function getUpdateListKey() {
return $this->directoryName;
}
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @return Update|null An instance of Update, or NULL when no updates are available.
*/
public function requestUpdate() {
list($themeUpdate, $result) = $this->requestMetadata(Update::class, 'request_update');
if ( $themeUpdate !== null ) {
/** @var Update $themeUpdate */
$themeUpdate->slug = $this->slug;
}
$themeUpdate = $this->filterUpdateResult($themeUpdate, $result);
return $themeUpdate;
}
protected function getNoUpdateItemFields() {
return array_merge(
parent::getNoUpdateItemFields(),
array(
'theme' => $this->directoryName,
'requires' => '',
)
);
}
public function userCanInstallUpdates() {
return current_user_can('update_themes');
}
/**
* Create an instance of the scheduler.
*
* @param int $checkPeriod
* @return Scheduler
*/
protected function createScheduler($checkPeriod) {
return new Scheduler($this, $checkPeriod, array('load-themes.php'));
}
/**
* Is there an update being installed right now for this theme?
*
* @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool
*/
public function isBeingUpgraded($upgrader = null) {
return $this->upgraderStatus->isThemeBeingUpgraded($this->stylesheet, $upgrader);
}
protected function createDebugBarExtension() {
return new DebugBar\Extension($this, DebugBar\ThemePanel::class);
}
/**
* Register a callback for filtering query arguments.
*
* The callback function should take one argument - an associative array of query arguments.
* It should return a modified array of query arguments.
*
* @param callable $callback
* @return void
*/
public function addQueryArgFilter($callback){
$this->addFilter('request_update_query_args', $callback);
}
/**
* Register a callback for filtering arguments passed to wp_remote_get().
*
* The callback function should take one argument - an associative array of arguments -
* and return a modified array or arguments. See the WP documentation on wp_remote_get()
* for details on what arguments are available and how they work.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addHttpRequestArgFilter($callback) {
$this->addFilter('request_update_options', $callback);
}
/**
* Register a callback for filtering theme updates retrieved from the external API.
*
* The callback function should take two arguments. If the theme update was retrieved
* successfully, the first argument passed will be an instance of Theme_Update. Otherwise,
* it will be NULL. The second argument will be the corresponding return value of
* wp_remote_get (see WP docs for details).
*
* The callback function should return a new or modified instance of Theme_Update or NULL.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addResultFilter($callback) {
$this->addFilter('request_update_result', $callback, 10, 2);
}
/**
* Create a package instance that represents this plugin or theme.
*
* @return InstalledPackage
*/
protected function createInstalledPackage() {
return new Package($this->stylesheet, $this);
}
}
endif;
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,38 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
use stdClass;
if ( !class_exists(Update::class, false) ):
/**
* A simple container class for holding information about an available update.
*
* @author Janis Elsts
* @access public
*/
abstract class Update extends Metadata {
public $slug;
public $version;
public $download_url;
public $translations = array();
/**
* @return string[]
*/
protected function getFieldNames() {
return array('slug', 'version', 'download_url', 'translations');
}
public function toWpFormat() {
$update = new stdClass();
$update->slug = $this->slug;
$update->new_version = $this->version;
$update->package = $this->download_url;
return $update;
}
}
endif;
@@ -0,0 +1,200 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists(UpgraderStatus::class, false) ):
/**
* A utility class that helps figure out which plugin or theme WordPress is upgrading.
*
* It may seem strange to have a separate class just for that, but the task is surprisingly complicated.
* Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
* This class uses a few workarounds and heuristics to get the file name.
*/
class UpgraderStatus {
private $currentType = null; //This must be either "plugin" or "theme".
private $currentId = null; //Plugin basename or theme directory name.
public function __construct() {
//Keep track of which plugin/theme WordPress is currently upgrading.
add_filter('upgrader_pre_install', array($this, 'setUpgradedThing'), 10, 2);
add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
add_filter('upgrader_post_install', array($this, 'clearUpgradedThing'), 10, 1);
add_action('upgrader_process_complete', array($this, 'clearUpgradedThing'), 10, 1);
}
/**
* Is there and update being installed RIGHT NOW, for a specific plugin?
*
* Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
* and upgrader implementations are liable to change without notice.
*
* @param string $pluginFile The plugin to check.
* @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool True if the plugin identified by $pluginFile is being upgraded.
*/
public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
return $this->isBeingUpgraded('plugin', $pluginFile, $upgrader);
}
/**
* Is there an update being installed for a specific theme?
*
* @param string $stylesheet Theme directory name.
* @param \WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool
*/
public function isThemeBeingUpgraded($stylesheet, $upgrader = null) {
return $this->isBeingUpgraded('theme', $stylesheet, $upgrader);
}
/**
* Check if a specific theme or plugin is being upgraded.
*
* @param string $type
* @param string $id
* @param \Plugin_Upgrader|\WP_Upgrader|null $upgrader
* @return bool
*/
protected function isBeingUpgraded($type, $id, $upgrader = null) {
if ( isset($upgrader) ) {
list($currentType, $currentId) = $this->getThingBeingUpgradedBy($upgrader);
if ( $currentType !== null ) {
$this->currentType = $currentType;
$this->currentId = $currentId;
}
}
return ($this->currentType === $type) && ($this->currentId === $id);
}
/**
* Figure out which theme or plugin is being upgraded by a WP_Upgrader instance.
*
* Returns an array with two items. The first item is the type of the thing that's being
* upgraded: "plugin" or "theme". The second item is either the plugin basename or
* the theme directory name. If we can't determine what the upgrader is doing, both items
* will be NULL.
*
* Examples:
* ['plugin', 'plugin-dir-name/plugin.php']
* ['theme', 'theme-dir-name']
*
* @param \Plugin_Upgrader|\WP_Upgrader $upgrader
* @return array
*/
private function getThingBeingUpgradedBy($upgrader) {
if ( !isset($upgrader, $upgrader->skin) ) {
return array(null, null);
}
//Figure out which plugin or theme is being upgraded.
$pluginFile = null;
$themeDirectoryName = null;
$skin = $upgrader->skin;
if ( isset($skin->theme_info) && ($skin->theme_info instanceof \WP_Theme) ) {
$themeDirectoryName = $skin->theme_info->get_stylesheet();
} elseif ( $skin instanceof \Plugin_Upgrader_Skin ) {
if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
$pluginFile = $skin->plugin;
}
} elseif ( $skin instanceof \Theme_Upgrader_Skin ) {
if ( isset($skin->theme) && is_string($skin->theme) && ($skin->theme !== '') ) {
$themeDirectoryName = $skin->theme;
}
} elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
//This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
//filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
//do is compare those headers to the headers of installed plugins.
$pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
}
if ( $pluginFile !== null ) {
return array('plugin', $pluginFile);
} elseif ( $themeDirectoryName !== null ) {
return array('theme', $themeDirectoryName);
}
return array(null, null);
}
/**
* Identify an installed plugin based on its headers.
*
* @param array $searchHeaders The plugin file header to look for.
* @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
*/
private function identifyPluginByHeaders($searchHeaders) {
if ( !function_exists('get_plugins') ){
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
$installedPlugins = get_plugins();
$matches = array();
foreach($installedPlugins as $pluginBasename => $headers) {
$diff1 = array_diff_assoc($headers, $searchHeaders);
$diff2 = array_diff_assoc($searchHeaders, $headers);
if ( empty($diff1) && empty($diff2) ) {
$matches[] = $pluginBasename;
}
}
//It's possible (though very unlikely) that there could be two plugins with identical
//headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
if ( count($matches) !== 1 ) {
return null;
}
return reset($matches);
}
/**
* @access private
*
* @param mixed $input
* @param array $hookExtra
* @return mixed Returns $input unaltered.
*/
public function setUpgradedThing($input, $hookExtra) {
if ( !empty($hookExtra['plugin']) && is_string($hookExtra['plugin']) ) {
$this->currentId = $hookExtra['plugin'];
$this->currentType = 'plugin';
} elseif ( !empty($hookExtra['theme']) && is_string($hookExtra['theme']) ) {
$this->currentId = $hookExtra['theme'];
$this->currentType = 'theme';
} else {
$this->currentType = null;
$this->currentId = null;
}
return $input;
}
/**
* @access private
*
* @param array $options
* @return array
*/
public function setUpgradedPluginFromOptions($options) {
if ( isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin']) ) {
$this->currentType = 'plugin';
$this->currentId = $options['hook_extra']['plugin'];
} else {
$this->currentType = null;
$this->currentId = null;
}
return $options;
}
/**
* @access private
*
* @param mixed $input
* @return mixed Returns $input unaltered.
*/
public function clearUpgradedThing($input = null) {
$this->currentId = null;
$this->currentType = null;
return $input;
}
}
endif;
@@ -0,0 +1,70 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
if ( !class_exists(Utils::class, false) ):
class Utils {
/**
* Get a value from a nested array or object based on a path.
*
* @param array|object|null $collection Get an entry from this array.
* @param array|string $path A list of array keys in hierarchy order, or a string path like "foo.bar.baz".
* @param mixed $default The value to return if the specified path is not found.
* @param string $separator Path element separator. Only applies to string paths.
* @return mixed
*/
public static function get($collection, $path, $default = null, $separator = '.') {
if ( is_string($path) ) {
$path = explode($separator, $path);
}
//Follow the $path into $input as far as possible.
$currentValue = $collection;
foreach ($path as $node) {
if ( is_array($currentValue) && isset($currentValue[$node]) ) {
$currentValue = $currentValue[$node];
} else if ( is_object($currentValue) && isset($currentValue->$node) ) {
$currentValue = $currentValue->$node;
} else {
return $default;
}
}
return $currentValue;
}
/**
* Get the first array element that is not empty.
*
* @param array $values
* @param mixed|null $default Returns this value if there are no non-empty elements.
* @return mixed|null
*/
public static function findNotEmpty($values, $default = null) {
if ( empty($values) ) {
return $default;
}
foreach ($values as $value) {
if ( !empty($value) ) {
return $value;
}
}
return $default;
}
/**
* Check if the input string starts with the specified prefix.
*
* @param string $input
* @param string $prefix
* @return bool
*/
public static function startsWith($input, $prefix) {
$length = strlen($prefix);
return (substr($input, 0, $length) === $prefix);
}
}
endif;
@@ -0,0 +1,379 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use Parsedown;
use PucReadmeParser;
if ( !class_exists(Api::class, false) ):
abstract class Api {
const STRATEGY_LATEST_RELEASE = 'latest_release';
const STRATEGY_LATEST_TAG = 'latest_tag';
const STRATEGY_STABLE_TAG = 'stable_tag';
const STRATEGY_BRANCH = 'branch';
/**
* Consider all releases regardless of their version number or prerelease/upcoming
* release status.
*/
const RELEASE_FILTER_ALL = 3;
/**
* Exclude releases that have the "prerelease" or "upcoming release" flag.
*
* This does *not* look for prerelease keywords like "beta" in the version number.
* It only uses the data provided by the API. For example, on GitHub, you can
* manually mark a release as a prerelease.
*/
const RELEASE_FILTER_SKIP_PRERELEASE = 1;
/**
* If there are no release assets or none of them match the configured filter,
* fall back to the automatically generated source code archive.
*/
const PREFER_RELEASE_ASSETS = 1;
/**
* Skip releases that don't have any matching release assets.
*/
const REQUIRE_RELEASE_ASSETS = 2;
protected $tagNameProperty = 'name';
protected $slug = '';
/**
* @var string
*/
protected $repositoryUrl = '';
/**
* @var mixed Authentication details for private repositories. Format depends on service.
*/
protected $credentials = null;
/**
* @var string The filter tag that's used to filter options passed to wp_remote_get.
* For example, "puc_request_info_options-slug" or "puc_request_update_options_theme-slug".
*/
protected $httpFilterName = '';
/**
* @var string The filter applied to the list of update detection strategies that
* are used to find the latest version.
*/
protected $strategyFilterName = '';
/**
* @var string|null
*/
protected $localDirectory = null;
/**
* Api constructor.
*
* @param string $repositoryUrl
* @param array|string|null $credentials
*/
public function __construct($repositoryUrl, $credentials = null) {
$this->repositoryUrl = $repositoryUrl;
$this->setAuthentication($credentials);
}
/**
* @return string
*/
public function getRepositoryUrl() {
return $this->repositoryUrl;
}
/**
* Figure out which reference (i.e. tag or branch) contains the latest version.
*
* @param string $configBranch Start looking in this branch.
* @return null|Reference
*/
public function chooseReference($configBranch) {
$strategies = $this->getUpdateDetectionStrategies($configBranch);
if ( !empty($this->strategyFilterName) ) {
$strategies = apply_filters(
$this->strategyFilterName,
$strategies,
$this->slug
);
}
foreach ($strategies as $strategy) {
$reference = call_user_func($strategy);
if ( !empty($reference) ) {
return $reference;
}
}
return null;
}
/**
* Get an ordered list of strategies that can be used to find the latest version.
*
* The update checker will try each strategy in order until one of them
* returns a valid reference.
*
* @param string $configBranch
* @return array<callable> Array of callables that return Vcs_Reference objects.
*/
abstract protected function getUpdateDetectionStrategies($configBranch);
/**
* Get the readme.txt file from the remote repository and parse it
* according to the plugin readme standard.
*
* @param string $ref Tag or branch name.
* @return array Parsed readme.
*/
public function getRemoteReadme($ref = 'master') {
$fileContents = $this->getRemoteFile($this->getLocalReadmeName(), $ref);
if ( empty($fileContents) ) {
return array();
}
$parser = new PucReadmeParser();
return $parser->parse_readme_contents($fileContents);
}
/**
* Get the case-sensitive name of the local readme.txt file.
*
* In most cases it should just be called "readme.txt", but some plugins call it "README.txt",
* "README.TXT", or even "Readme.txt". Most VCS are case-sensitive so we need to know the correct
* capitalization.
*
* Defaults to "readme.txt" (all lowercase).
*
* @return string
*/
public function getLocalReadmeName() {
static $fileName = null;
if ( $fileName !== null ) {
return $fileName;
}
$fileName = 'readme.txt';
if ( isset($this->localDirectory) ) {
$files = scandir($this->localDirectory);
if ( !empty($files) ) {
foreach ($files as $possibleFileName) {
if ( strcasecmp($possibleFileName, 'readme.txt') === 0 ) {
$fileName = $possibleFileName;
break;
}
}
}
}
return $fileName;
}
/**
* Get a branch.
*
* @param string $branchName
* @return Reference|null
*/
abstract public function getBranch($branchName);
/**
* Get a specific tag.
*
* @param string $tagName
* @return Reference|null
*/
abstract public function getTag($tagName);
/**
* Get the tag that looks like the highest version number.
* (Implementations should skip pre-release versions if possible.)
*
* @return Reference|null
*/
abstract public function getLatestTag();
/**
* Check if a tag name string looks like a version number.
*
* @param string $name
* @return bool
*/
protected function looksLikeVersion($name) {
//Tag names may be prefixed with "v", e.g. "v1.2.3".
$name = ltrim($name, 'v');
//The version string must start with a number.
if ( !is_numeric(substr($name, 0, 1)) ) {
return false;
}
//The goal is to accept any SemVer-compatible or "PHP-standardized" version number.
return (preg_match('@^(\d{1,5}?)(\.\d{1,10}?){0,4}?($|[abrdp+_\-]|\s)@i', $name) === 1);
}
/**
* Check if a tag appears to be named like a version number.
*
* @param \stdClass $tag
* @return bool
*/
protected function isVersionTag($tag) {
$property = $this->tagNameProperty;
return isset($tag->$property) && $this->looksLikeVersion($tag->$property);
}
/**
* Sort a list of tags as if they were version numbers.
* Tags that don't look like version number will be removed.
*
* @param \stdClass[] $tags Array of tag objects.
* @return \stdClass[] Filtered array of tags sorted in descending order.
*/
protected function sortTagsByVersion($tags) {
//Keep only those tags that look like version numbers.
$versionTags = array_filter($tags, array($this, 'isVersionTag'));
//Sort them in descending order.
usort($versionTags, array($this, 'compareTagNames'));
return $versionTags;
}
/**
* Compare two tags as if they were version number.
*
* @param \stdClass $tag1 Tag object.
* @param \stdClass $tag2 Another tag object.
* @return int
*/
protected function compareTagNames($tag1, $tag2) {
$property = $this->tagNameProperty;
if ( !isset($tag1->$property) ) {
return 1;
}
if ( !isset($tag2->$property) ) {
return -1;
}
return -version_compare(ltrim($tag1->$property, 'v'), ltrim($tag2->$property, 'v'));
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
abstract public function getRemoteFile($path, $ref = 'master');
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
abstract public function getLatestCommitTime($ref);
/**
* Get the contents of the changelog file from the repository.
*
* @param string $ref
* @param string $localDirectory Full path to the local plugin or theme directory.
* @return null|string The HTML contents of the changelog.
*/
public function getRemoteChangelog($ref, $localDirectory) {
$filename = $this->findChangelogName($localDirectory);
if ( empty($filename) ) {
return null;
}
$changelog = $this->getRemoteFile($filename, $ref);
if ( $changelog === null ) {
return null;
}
return Parsedown::instance()->text($changelog);
}
/**
* Guess the name of the changelog file.
*
* @param string $directory
* @return string|null
*/
protected function findChangelogName($directory = null) {
if ( !isset($directory) ) {
$directory = $this->localDirectory;
}
if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
return null;
}
$possibleNames = array('CHANGES.md', 'CHANGELOG.md', 'changes.md', 'changelog.md');
$files = scandir($directory);
$foundNames = array_intersect($possibleNames, $files);
if ( !empty($foundNames) ) {
return reset($foundNames);
}
return null;
}
/**
* Set authentication credentials.
*
* @param $credentials
*/
public function setAuthentication($credentials) {
$this->credentials = $credentials;
}
public function isAuthenticationEnabled() {
return !empty($this->credentials);
}
/**
* @param string $url
* @return string
*/
public function signDownloadUrl($url) {
return $url;
}
/**
* @param string $filterName
*/
public function setHttpFilterName($filterName) {
$this->httpFilterName = $filterName;
}
/**
* @param string $filterName
*/
public function setStrategyFilterName($filterName) {
$this->strategyFilterName = $filterName;
}
/**
* @param string $directory
*/
public function setLocalDirectory($directory) {
if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
$this->localDirectory = null;
} else {
$this->localDirectory = $directory;
}
}
/**
* @param string $slug
*/
public function setSlug($slug) {
$this->slug = $slug;
}
}
endif;
@@ -0,0 +1,29 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !interface_exists(BaseChecker::class, false) ):
interface BaseChecker {
/**
* Set the repository branch to use for updates. Defaults to 'master'.
*
* @param string $branch
* @return $this
*/
public function setBranch($branch);
/**
* Set authentication credentials.
*
* @param array|string $credentials
* @return $this
*/
public function setAuthentication($credentials);
/**
* @return Api
*/
public function getVcsApi();
}
endif;
@@ -0,0 +1,272 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use YahnisElsts\PluginUpdateChecker\v5p6\OAuthSignature;
use YahnisElsts\PluginUpdateChecker\v5p6\Utils;
if ( !class_exists(BitBucketApi::class, false) ):
class BitBucketApi extends Api {
/**
* @var OAuthSignature
*/
private $oauth = null;
/**
* @var string
*/
private $username;
/**
* @var string
*/
private $repository;
public function __construct($repositoryUrl, $credentials = array()) {
$path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->username = $matches['username'];
$this->repository = $matches['repository'];
} else {
throw new \InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"');
}
parent::__construct($repositoryUrl, $credentials);
}
protected function getUpdateDetectionStrategies($configBranch) {
$strategies = array(
self::STRATEGY_STABLE_TAG => function () use ($configBranch) {
return $this->getStableTag($configBranch);
},
);
if ( ($configBranch === 'master' || $configBranch === 'main') ) {
$strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
$strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
return $this->getBranch($configBranch);
};
return $strategies;
}
public function getBranch($branchName) {
$branch = $this->api('/refs/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
//The "/src/{stuff}/{path}" endpoint doesn't seem to handle branch names that contain slashes.
//If we don't encode the slash, we get a 404. If we encode it as "%2F", we get a 401.
//To avoid issues, if the branch name is not URL-safe, let's use the commit hash instead.
$ref = $branch->name;
if ((urlencode($ref) !== $ref) && isset($branch->target->hash)) {
$ref = $branch->target->hash;
}
return new Reference(array(
'name' => $ref,
'updated' => $branch->target->date,
'downloadUrl' => $this->getDownloadUrl($branch->name),
));
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return Reference|null
*/
public function getTag($tagName) {
$tag = $this->api('/refs/tags/' . $tagName);
if ( is_wp_error($tag) || empty($tag) ) {
return null;
}
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date,
'downloadUrl' => $this->getDownloadUrl($tag->name),
));
}
/**
* Get the tag that looks like the highest version number.
*
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/refs/tags?sort=-target.date');
if ( !isset($tags, $tags->values) || !is_array($tags->values) ) {
return null;
}
//Filter and sort the list of tags.
$versionTags = $this->sortTagsByVersion($tags->values);
//Return the first result.
if ( !empty($versionTags) ) {
$tag = $versionTags[0];
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date,
'downloadUrl' => $this->getDownloadUrl($tag->name),
));
}
return null;
}
/**
* Get the tag/ref specified by the "Stable tag" header in the readme.txt of a given branch.
*
* @param string $branch
* @return null|Reference
*/
protected function getStableTag($branch) {
$remoteReadme = $this->getRemoteReadme($branch);
if ( !empty($remoteReadme['stable_tag']) ) {
$tag = $remoteReadme['stable_tag'];
//You can explicitly opt out of using tags by setting "Stable tag" to
//"trunk" or the name of the current branch.
if ( ($tag === $branch) || ($tag === 'trunk') ) {
return $this->getBranch($branch);
}
return $this->getTag($tag);
}
return null;
}
/**
* @param string $ref
* @return string
*/
protected function getDownloadUrl($ref) {
return sprintf(
'https://bitbucket.org/%s/%s/get/%s.zip',
$this->username,
$this->repository,
$ref
);
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$response = $this->api('src/' . $ref . '/' . ltrim($path));
if ( is_wp_error($response) || !is_string($response) ) {
return null;
}
return $response;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$response = $this->api('commits/' . $ref);
if ( isset($response->values, $response->values[0], $response->values[0]->date) ) {
return $response->values[0]->date;
}
return null;
}
/**
* Perform a BitBucket API 2.0 request.
*
* @param string $url
* @param string $version
* @return mixed|\WP_Error
*/
public function api($url, $version = '2.0') {
$url = ltrim($url, '/');
$isSrcResource = Utils::startsWith($url, 'src/');
$url = implode('/', array(
'https://api.bitbucket.org',
$version,
'repositories',
$this->username,
$this->repository,
$url
));
$baseUrl = $url;
if ( $this->oauth ) {
$url = $this->oauth->sign($url,'GET');
}
$options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
if ( $isSrcResource ) {
//Most responses are JSON-encoded, but src resources just
//return raw file contents.
$document = $body;
} else {
$document = json_decode($body);
}
return $document;
}
$error = new \WP_Error(
'puc-bitbucket-http-error',
sprintf('BitBucket API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
* @param array $credentials
*/
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
$this->oauth = new OAuthSignature(
$credentials['consumer_key'],
$credentials['consumer_secret']
);
} else {
$this->oauth = null;
}
}
public function signDownloadUrl($url) {
//Add authentication data to download URLs. Since OAuth signatures incorporate
//timestamps, we have to do this immediately before inserting the update. Otherwise,
//authentication could fail due to a stale timestamp.
if ( $this->oauth ) {
$url = $this->oauth->sign($url);
}
return $url;
}
}
endif;
@@ -0,0 +1,467 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use Parsedown;
if ( !class_exists(GitHubApi::class, false) ):
class GitHubApi extends Api {
use ReleaseAssetSupport;
use ReleaseFilteringFeature;
/**
* @var string GitHub username.
*/
protected $userName;
/**
* @var string GitHub repository name.
*/
protected $repositoryName;
/**
* @var string Either a fully qualified repository URL, or just "user/repo-name".
*/
protected $repositoryUrl;
/**
* @var string GitHub authentication token. Optional.
*/
protected $accessToken;
/**
* @var bool
*/
private $downloadFilterAdded = false;
public function __construct($repositoryUrl, $accessToken = null) {
$path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username'];
$this->repositoryName = $matches['repository'];
} else {
throw new \InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
}
parent::__construct($repositoryUrl, $accessToken);
}
/**
* Get the latest release from GitHub.
*
* @return Reference|null
*/
public function getLatestRelease() {
//The "latest release" endpoint returns one release and always skips pre-releases,
//so we can only use it if that's compatible with the current filter settings.
if (
$this->shouldSkipPreReleases()
&& (
($this->releaseFilterMaxReleases === 1) || !$this->hasCustomReleaseFilter()
)
) {
//Just get the latest release.
$release = $this->api('/repos/:user/:repo/releases/latest');
if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) {
return null;
}
$foundReleases = array($release);
} else {
//Get a list of the most recent releases.
$foundReleases = $this->api(
'/repos/:user/:repo/releases',
array('per_page' => $this->releaseFilterMaxReleases)
);
if ( is_wp_error($foundReleases) || !is_array($foundReleases) ) {
return null;
}
}
foreach ($foundReleases as $release) {
//Always skip drafts.
if ( isset($release->draft) && !empty($release->draft) ) {
continue;
}
//Skip pre-releases unless specifically included.
if (
$this->shouldSkipPreReleases()
&& isset($release->prerelease)
&& !empty($release->prerelease)
) {
continue;
}
$versionNumber = ltrim($release->tag_name, 'v'); //Remove the "v" prefix from "v1.2.3".
//Custom release filtering.
if ( !$this->matchesCustomReleaseFilter($versionNumber, $release) ) {
continue;
}
$reference = new Reference(array(
'name' => $release->tag_name,
'version' => $versionNumber,
'downloadUrl' => $release->zipball_url,
'updated' => $release->created_at,
'apiResponse' => $release,
));
if ( isset($release->assets[0]) ) {
$reference->downloadCount = $release->assets[0]->download_count;
}
if ( $this->releaseAssetsEnabled ) {
//Use the first release asset that matches the specified regular expression.
if ( isset($release->assets, $release->assets[0]) ) {
$matchingAssets = array_values(array_filter($release->assets, array($this, 'matchesAssetFilter')));
} else {
$matchingAssets = array();
}
if ( !empty($matchingAssets) ) {
if ( $this->isAuthenticationEnabled() ) {
/**
* Keep in mind that we'll need to add an "Accept" header to download this asset.
*
* @see setUpdateDownloadHeaders()
*/
$reference->downloadUrl = $matchingAssets[0]->url;
} else {
//It seems that browser_download_url only works for public repositories.
//Using an access_token doesn't help. Maybe OAuth would work?
$reference->downloadUrl = $matchingAssets[0]->browser_download_url;
}
$reference->downloadCount = $matchingAssets[0]->download_count;
} else if ( $this->releaseAssetPreference === Api::REQUIRE_RELEASE_ASSETS ) {
//None of the assets match the filter, and we're not allowed
//to fall back to the auto-generated source ZIP.
return null;
}
}
if ( !empty($release->body) ) {
$reference->changelog = Parsedown::instance()->text($release->body);
}
return $reference;
}
return null;
}
/**
* Get the tag that looks like the highest version number.
*
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/repos/:user/:repo/tags');
if ( is_wp_error($tags) || !is_array($tags) ) {
return null;
}
$versionTags = $this->sortTagsByVersion($tags);
if ( empty($versionTags) ) {
return null;
}
$tag = $versionTags[0];
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $tag->zipball_url,
'apiResponse' => $tag,
));
}
/**
* Get a branch by name.
*
* @param string $branchName
* @return null|Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/repos/:user/:repo/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
$reference = new Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
));
if ( isset($branch->commit, $branch->commit->commit, $branch->commit->commit->author->date) ) {
$reference->updated = $branch->commit->commit->author->date;
}
return $reference;
}
/**
* Get the latest commit that changed the specified file.
*
* @param string $filename
* @param string $ref Reference name (e.g. branch or tag).
* @return \StdClass|null
*/
public function getLatestCommit($filename, $ref = 'master') {
$commits = $this->api(
'/repos/:user/:repo/commits',
array(
'path' => $filename,
'sha' => $ref,
)
);
if ( !is_wp_error($commits) && isset($commits[0]) ) {
return $commits[0];
}
return null;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$commits = $this->api('/repos/:user/:repo/commits', array('sha' => $ref));
if ( !is_wp_error($commits) && isset($commits[0]) ) {
return $commits[0]->commit->author->date;
}
return null;
}
/**
* Perform a GitHub API request.
*
* @param string $url
* @param array $queryParams
* @return mixed|\WP_Error
*/
protected function api($url, $queryParams = array()) {
$baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams);
$options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( $this->isAuthenticationEnabled() ) {
$options['headers'] = array('Authorization' => $this->getAuthorizationHeader());
}
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
$document = json_decode($body);
return $document;
}
$error = new \WP_Error(
'puc-github-http-error',
sprintf('GitHub API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
* Build a fully qualified URL for an API request.
*
* @param string $url
* @param array $queryParams
* @return string
*/
protected function buildApiUrl($url, $queryParams) {
$variables = array(
'user' => $this->userName,
'repo' => $this->repositoryName,
);
foreach ($variables as $name => $value) {
$url = str_replace('/:' . $name, '/' . urlencode($value), $url);
}
$url = 'https://api.github.com' . $url;
if ( !empty($queryParams) ) {
$url = add_query_arg($queryParams, $url);
}
return $url;
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$apiUrl = '/repos/:user/:repo/contents/' . $path;
$response = $this->api($apiUrl, array('ref' => $ref));
if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) {
return null;
}
return base64_decode($response->content);
}
/**
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
*
* @param string $ref
* @return string
*/
public function buildArchiveDownloadUrl($ref = 'master') {
$url = sprintf(
'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s',
urlencode($this->userName),
urlencode($this->repositoryName),
urlencode($ref)
);
return $url;
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return void
*/
public function getTag($tagName) {
//The current GitHub update checker doesn't use getTag, so I didn't bother to implement it.
throw new \LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
}
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
$this->accessToken = is_string($credentials) ? $credentials : null;
//Optimization: Instead of filtering all HTTP requests, let's do it only when
//WordPress is about to download an update.
add_filter('upgrader_pre_download', array($this, 'addHttpRequestFilter'), 10, 1); //WP 3.7+
}
protected function getUpdateDetectionStrategies($configBranch) {
$strategies = array();
if ( $configBranch === 'master' || $configBranch === 'main') {
//Use the latest release.
$strategies[self::STRATEGY_LATEST_RELEASE] = array($this, 'getLatestRelease');
//Failing that, use the tag with the highest version number.
$strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
//Alternatively, just use the branch itself.
$strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
return $this->getBranch($configBranch);
};
return $strategies;
}
/**
* Get the unchanging part of a release asset URL. Used to identify download attempts.
*
* @return string
*/
protected function getAssetApiBaseUrl() {
return sprintf(
'//api.github.com/repos/%1$s/%2$s/releases/assets/',
$this->userName,
$this->repositoryName
);
}
protected function getFilterableAssetName($releaseAsset) {
if ( isset($releaseAsset->name) ) {
return $releaseAsset->name;
}
return null;
}
/**
* @param bool $result
* @return bool
* @internal
*/
public function addHttpRequestFilter($result) {
if ( !$this->downloadFilterAdded && $this->isAuthenticationEnabled() ) {
//phpcs:ignore WordPressVIPMinimum.Hooks.RestrictedHooks.http_request_args -- The callback doesn't change the timeout.
add_filter('http_request_args', array($this, 'setUpdateDownloadHeaders'), 10, 2);
add_action('requests-requests.before_redirect', array($this, 'removeAuthHeaderFromRedirects'), 10, 4);
$this->downloadFilterAdded = true;
}
return $result;
}
/**
* Set the HTTP headers that are necessary to download updates from private repositories.
*
* See GitHub docs:
*
* @link https://developer.github.com/v3/repos/releases/#get-a-single-release-asset
* @link https://developer.github.com/v3/auth/#basic-authentication
*
* @internal
* @param array $requestArgs
* @param string $url
* @return array
*/
public function setUpdateDownloadHeaders($requestArgs, $url = '') {
//Is WordPress trying to download one of our release assets?
if ( $this->releaseAssetsEnabled && (strpos($url, $this->getAssetApiBaseUrl()) !== false) ) {
$requestArgs['headers']['Accept'] = 'application/octet-stream';
}
//Use Basic authentication, but only if the download is from our repository.
$repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array());
if ( $this->isAuthenticationEnabled() && (strpos($url, $repoApiBaseUrl)) === 0 ) {
$requestArgs['headers']['Authorization'] = $this->getAuthorizationHeader();
}
return $requestArgs;
}
/**
* When following a redirect, the Requests library will automatically forward
* the authorization header to other hosts. We don't want that because it breaks
* AWS downloads and can leak authorization information.
*
* @param string $location
* @param array $headers
* @internal
*/
public function removeAuthHeaderFromRedirects(&$location, &$headers) {
$repoApiBaseUrl = $this->buildApiUrl('/repos/:user/:repo/', array());
if ( strpos($location, $repoApiBaseUrl) === 0 ) {
return; //This request is going to GitHub, so it's fine.
}
//Remove the header.
if ( isset($headers['Authorization']) ) {
unset($headers['Authorization']);
}
}
/**
* Generate the value of the "Authorization" header.
*
* @return string
*/
protected function getAuthorizationHeader() {
return 'Basic ' . base64_encode($this->userName . ':' . $this->accessToken);
}
}
endif;
@@ -0,0 +1,414 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !class_exists(GitLabApi::class, false) ):
class GitLabApi extends Api {
use ReleaseAssetSupport;
use ReleaseFilteringFeature;
/**
* @var string GitLab username.
*/
protected $userName;
/**
* @var string GitLab server host.
*/
protected $repositoryHost;
/**
* @var string Protocol used by this GitLab server: "http" or "https".
*/
protected $repositoryProtocol = 'https';
/**
* @var string GitLab repository name.
*/
protected $repositoryName;
/**
* @var string GitLab authentication token. Optional.
*/
protected $accessToken;
/**
* @deprecated
* @var bool No longer used.
*/
protected $releasePackageEnabled = false;
public function __construct($repositoryUrl, $accessToken = null, $subgroup = null) {
//Parse the repository host to support custom hosts.
$port = wp_parse_url($repositoryUrl, PHP_URL_PORT);
if ( !empty($port) ) {
$port = ':' . $port;
}
$this->repositoryHost = wp_parse_url($repositoryUrl, PHP_URL_HOST) . $port;
if ( $this->repositoryHost !== 'gitlab.com' ) {
$this->repositoryProtocol = wp_parse_url($repositoryUrl, PHP_URL_SCHEME);
}
//Find the repository information
$path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username'];
$this->repositoryName = $matches['repository'];
} elseif ( ($this->repositoryHost === 'gitlab.com') ) {
//This is probably a repository in a subgroup, e.g. "/organization/category/repo".
$parts = explode('/', trim($path, '/'));
if ( count($parts) < 3 ) {
throw new \InvalidArgumentException('Invalid GitLab.com repository URL: "' . $repositoryUrl . '"');
}
$lastPart = array_pop($parts);
$this->userName = implode('/', $parts);
$this->repositoryName = $lastPart;
} else {
//There could be subgroups in the URL: gitlab.domain.com/group/subgroup/subgroup2/repository
if ( $subgroup !== null ) {
$path = str_replace(trailingslashit($subgroup), '', $path);
}
//This is not a traditional url, it could be gitlab is in a deeper subdirectory.
//Get the path segments.
$segments = explode('/', untrailingslashit(ltrim($path, '/')));
//We need at least /user-name/repository-name/
if ( count($segments) < 2 ) {
throw new \InvalidArgumentException('Invalid GitLab repository URL: "' . $repositoryUrl . '"');
}
//Get the username and repository name.
$usernameRepo = array_splice($segments, -2, 2);
$this->userName = $usernameRepo[0];
$this->repositoryName = $usernameRepo[1];
//Append the remaining segments to the host if there are segments left.
if ( count($segments) > 0 ) {
$this->repositoryHost = trailingslashit($this->repositoryHost) . implode('/', $segments);
}
//Add subgroups to username.
if ( $subgroup !== null ) {
$this->userName = $usernameRepo[0] . '/' . untrailingslashit($subgroup);
}
}
parent::__construct($repositoryUrl, $accessToken);
}
/**
* Get the latest release from GitLab.
*
* @return Reference|null
*/
public function getLatestRelease() {
$releases = $this->api('/:id/releases', array('per_page' => $this->releaseFilterMaxReleases));
if ( is_wp_error($releases) || empty($releases) || !is_array($releases) ) {
return null;
}
foreach ($releases as $release) {
if (
//Skip invalid/unsupported releases.
!is_object($release)
|| !isset($release->tag_name)
//Skip upcoming releases.
|| (
!empty($release->upcoming_release)
&& $this->shouldSkipPreReleases()
)
) {
continue;
}
$versionNumber = ltrim($release->tag_name, 'v'); //Remove the "v" prefix from "v1.2.3".
//Apply custom filters.
if ( !$this->matchesCustomReleaseFilter($versionNumber, $release) ) {
continue;
}
$downloadUrl = $this->findReleaseDownloadUrl($release);
if ( empty($downloadUrl) ) {
//The latest release doesn't have valid download URL.
return null;
}
if ( !empty($this->accessToken) ) {
$downloadUrl = add_query_arg('private_token', $this->accessToken, $downloadUrl);
}
return new Reference(array(
'name' => $release->tag_name,
'version' => $versionNumber,
'downloadUrl' => $downloadUrl,
'updated' => $release->released_at,
'apiResponse' => $release,
));
}
return null;
}
/**
* @param object $release
* @return string|null
*/
protected function findReleaseDownloadUrl($release) {
if ( $this->releaseAssetsEnabled ) {
if ( isset($release->assets, $release->assets->links) ) {
//Use the first asset link where the URL matches the filter.
foreach ($release->assets->links as $link) {
if ( $this->matchesAssetFilter($link) ) {
return $link->url;
}
}
}
if ( $this->releaseAssetPreference === Api::REQUIRE_RELEASE_ASSETS ) {
//Falling back to source archives is not allowed, so give up.
return null;
}
}
//Use the first source code archive that's in ZIP format.
foreach ($release->assets->sources as $source) {
if ( isset($source->format) && ($source->format === 'zip') ) {
return $source->url;
}
}
return null;
}
/**
* Get the tag that looks like the highest version number.
*
* @return Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/:id/repository/tags');
if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
return null;
}
$versionTags = $this->sortTagsByVersion($tags);
if ( empty($versionTags) ) {
return null;
}
$tag = $versionTags[0];
return new Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name),
'apiResponse' => $tag,
));
}
/**
* Get a branch by name.
*
* @param string $branchName
* @return null|Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/:id/repository/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
$reference = new Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
));
if ( isset($branch->commit, $branch->commit->committed_date) ) {
$reference->updated = $branch->commit->committed_date;
}
return $reference;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$commits = $this->api('/:id/repository/commits/', array('ref_name' => $ref));
if ( is_wp_error($commits) || !is_array($commits) || !isset($commits[0]) ) {
return null;
}
return $commits[0]->committed_date;
}
/**
* Perform a GitLab API request.
*
* @param string $url
* @param array $queryParams
* @return mixed|\WP_Error
*/
protected function api($url, $queryParams = array()) {
$baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams);
$options = array('timeout' => wp_doing_cron() ? 10 : 3);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
return json_decode($body);
}
$error = new \WP_Error(
'puc-gitlab-http-error',
sprintf('GitLab API error. URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
* Build a fully qualified URL for an API request.
*
* @param string $url
* @param array $queryParams
* @return string
*/
protected function buildApiUrl($url, $queryParams) {
$variables = array(
'user' => $this->userName,
'repo' => $this->repositoryName,
'id' => $this->userName . '/' . $this->repositoryName,
);
foreach ($variables as $name => $value) {
$url = str_replace("/:{$name}", '/' . urlencode($value), $url);
}
$url = substr($url, 1);
$url = sprintf('%1$s://%2$s/api/v4/projects/%3$s', $this->repositoryProtocol, $this->repositoryHost, $url);
if ( !empty($this->accessToken) ) {
$queryParams['private_token'] = $this->accessToken;
}
if ( !empty($queryParams) ) {
$url = add_query_arg($queryParams, $url);
}
return $url;
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$response = $this->api('/:id/repository/files/' . $path, array('ref' => $ref));
if ( is_wp_error($response) || !isset($response->content) || $response->encoding !== 'base64' ) {
return null;
}
return base64_decode($response->content);
}
/**
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
*
* @param string $ref
* @return string
*/
public function buildArchiveDownloadUrl($ref = 'master') {
$url = sprintf(
'%1$s://%2$s/api/v4/projects/%3$s/repository/archive.zip',
$this->repositoryProtocol,
$this->repositoryHost,
urlencode($this->userName . '/' . $this->repositoryName)
);
$url = add_query_arg('sha', urlencode($ref), $url);
if ( !empty($this->accessToken) ) {
$url = add_query_arg('private_token', $this->accessToken, $url);
}
return $url;
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return void
*/
public function getTag($tagName) {
throw new \LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
}
protected function getUpdateDetectionStrategies($configBranch) {
$strategies = array();
if ( ($configBranch === 'main') || ($configBranch === 'master') ) {
$strategies[self::STRATEGY_LATEST_RELEASE] = array($this, 'getLatestRelease');
$strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
}
$strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
return $this->getBranch($configBranch);
};
return $strategies;
}
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
$this->accessToken = is_string($credentials) ? $credentials : null;
}
/**
* Use release assets that link to GitLab generic packages (e.g. .zip files)
* instead of automatically generated source archives.
*
* This is included for backwards compatibility with older versions of PUC.
*
* @return void
* @deprecated Use enableReleaseAssets() instead.
* @noinspection PhpUnused -- Public API
*/
public function enableReleasePackages() {
$this->enableReleaseAssets(
/** @lang RegExp */ '/\.zip($|[?&#])/i',
Api::REQUIRE_RELEASE_ASSETS
);
}
protected function getFilterableAssetName($releaseAsset) {
if ( isset($releaseAsset->url) ) {
return $releaseAsset->url;
}
return null;
}
}
endif;
@@ -0,0 +1,275 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use YahnisElsts\PluginUpdateChecker\v5p6\Plugin;
if ( !class_exists(PluginUpdateChecker::class, false) ):
class PluginUpdateChecker extends Plugin\UpdateChecker implements BaseChecker {
use VcsCheckerMethods;
/**
* PluginUpdateChecker constructor.
*
* @param Api $api
* @param string $pluginFile
* @param string $slug
* @param int $checkPeriod
* @param string $optionName
* @param string $muPluginFile
*/
public function __construct($api, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$this->api = $api;
parent::__construct($api->getRepositoryUrl(), $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
$this->api->setHttpFilterName($this->getUniqueName('request_info_options'));
$this->api->setStrategyFilterName($this->getUniqueName('vcs_update_detection_strategies'));
$this->api->setSlug($this->slug);
}
public function requestInfo($unusedParameter = null) {
//We have to make several remote API requests to gather all the necessary info
//which can take a while on slow networks.
if ( function_exists('set_time_limit') ) {
@set_time_limit(60);
}
$api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
$info = new Plugin\PluginInfo();
$info->filename = $this->pluginFile;
$info->slug = $this->slug;
$this->setInfoFromHeader($this->package->getPluginHeader(), $info);
$this->setIconsFromLocalAssets($info);
$this->setBannersFromLocalAssets($info);
//Pick a branch or tag.
$updateSource = $api->chooseReference($this->branch);
if ( $updateSource ) {
$ref = $updateSource->name;
$info->version = $updateSource->version;
$info->last_updated = $updateSource->updated;
$info->download_url = $updateSource->downloadUrl;
if ( !empty($updateSource->changelog) ) {
$info->sections['changelog'] = $updateSource->changelog;
}
if ( isset($updateSource->downloadCount) ) {
$info->downloaded = $updateSource->downloadCount;
}
} else {
//There's probably a network problem or an authentication error.
do_action(
'puc_api_error',
new \WP_Error(
'puc-no-update-source',
'Could not retrieve version information from the repository. '
. 'This usually means that the update checker either can\'t connect '
. 'to the repository or it\'s configured incorrectly.'
),
null, null, $this->slug
);
return null;
}
//Get headers from the main plugin file in this branch/tag. Its "Version" header and other metadata
//are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
$mainPluginFile = basename($this->pluginFile);
$remotePlugin = $api->getRemoteFile($mainPluginFile, $ref);
if ( !empty($remotePlugin) ) {
$remoteHeader = $this->package->getFileHeader($remotePlugin);
$this->setInfoFromHeader($remoteHeader, $info);
}
//Sanity check: Reject updates that don't have a version number.
//This can happen when we're using a branch, and we either fail to retrieve the main plugin
//file or the file doesn't have a "Version" header.
if ( empty($info->version) ) {
do_action(
'puc_api_error',
new \WP_Error(
'puc-no-plugin-version',
'Could not find the version number in the repository.'
),
null, null, $this->slug
);
return null;
}
//Try parsing readme.txt. If it's formatted according to WordPress.org standards, it will contain
//a lot of useful information like the required/tested WP version, changelog, and so on.
if ( $this->readmeTxtExistsLocally() ) {
$this->setInfoFromRemoteReadme($ref, $info);
}
//The changelog might be in a separate file.
if ( empty($info->sections['changelog']) ) {
$info->sections['changelog'] = $api->getRemoteChangelog($ref, $this->package->getAbsoluteDirectoryPath());
if ( empty($info->sections['changelog']) ) {
$info->sections['changelog'] = __('There is no changelog available.', 'plugin-update-checker');
}
}
if ( empty($info->last_updated) ) {
//Fetch the latest commit that changed the tag or branch and use it as the "last_updated" date.
$latestCommitTime = $api->getLatestCommitTime($ref);
if ( $latestCommitTime !== null ) {
$info->last_updated = $latestCommitTime;
}
}
$info = apply_filters($this->getUniqueName('request_info_result'), $info, null);
return $info;
}
/**
* Check if the currently installed version has a readme.txt file.
*
* @return bool
*/
protected function readmeTxtExistsLocally() {
return $this->package->fileExists($this->api->getLocalReadmeName());
}
/**
* Copy plugin metadata from a file header to a Plugin Info object.
*
* @param array $fileHeader
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setInfoFromHeader($fileHeader, $pluginInfo) {
$headerToPropertyMap = array(
'Version' => 'version',
'Name' => 'name',
'PluginURI' => 'homepage',
'Author' => 'author',
'AuthorName' => 'author',
'AuthorURI' => 'author_homepage',
'Requires WP' => 'requires',
'Tested WP' => 'tested',
'Requires at least' => 'requires',
'Tested up to' => 'tested',
'Requires PHP' => 'requires_php',
);
foreach ($headerToPropertyMap as $headerName => $property) {
if ( isset($fileHeader[$headerName]) && !empty($fileHeader[$headerName]) ) {
$pluginInfo->$property = $fileHeader[$headerName];
}
}
if ( !empty($fileHeader['Description']) ) {
$pluginInfo->sections['description'] = $fileHeader['Description'];
}
}
/**
* Copy plugin metadata from the remote readme.txt file.
*
* @param string $ref GitHub tag or branch where to look for the readme.
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
$readme = $this->api->getRemoteReadme($ref);
if ( empty($readme) ) {
return;
}
if ( isset($readme['sections']) ) {
$pluginInfo->sections = array_merge($pluginInfo->sections, $readme['sections']);
}
if ( !empty($readme['tested_up_to']) ) {
$pluginInfo->tested = $readme['tested_up_to'];
}
if ( !empty($readme['requires_at_least']) ) {
$pluginInfo->requires = $readme['requires_at_least'];
}
if ( !empty($readme['requires_php']) ) {
$pluginInfo->requires_php = $readme['requires_php'];
}
if ( isset($readme['upgrade_notice'], $readme['upgrade_notice'][$pluginInfo->version]) ) {
$pluginInfo->upgrade_notice = $readme['upgrade_notice'][$pluginInfo->version];
}
}
/**
* Add icons from the currently installed version to a Plugin Info object.
*
* The icons should be in a subdirectory named "assets". Supported image formats
* and file names are described here:
* @link https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons
*
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setIconsFromLocalAssets($pluginInfo) {
$icons = $this->getLocalAssetUrls(array(
'icon.svg' => 'svg',
'icon-256x256.png' => '2x',
'icon-256x256.jpg' => '2x',
'icon-128x128.png' => '1x',
'icon-128x128.jpg' => '1x',
));
if ( !empty($icons) ) {
//The "default" key seems to be used only as last-resort fallback in WP core (5.8/5.9),
//but we'll set it anyway in case some code somewhere needs it.
reset($icons);
$firstKey = key($icons);
$icons['default'] = $icons[$firstKey];
$pluginInfo->icons = $icons;
}
}
/**
* Add banners from the currently installed version to a Plugin Info object.
*
* The banners should be in a subdirectory named "assets". Supported image formats
* and file names are described here:
* @link https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-headers
*
* @param Plugin\PluginInfo $pluginInfo
*/
protected function setBannersFromLocalAssets($pluginInfo) {
$banners = $this->getLocalAssetUrls(array(
'banner-772x250.png' => 'high',
'banner-772x250.jpg' => 'high',
'banner-1544x500.png' => 'low',
'banner-1544x500.jpg' => 'low',
));
if ( !empty($banners) ) {
$pluginInfo->banners = $banners;
}
}
/**
* @param array<string, string> $filesToKeys
* @return array<string, string>
*/
protected function getLocalAssetUrls($filesToKeys) {
$assetDirectory = $this->package->getAbsoluteDirectoryPath() . DIRECTORY_SEPARATOR . 'assets';
if ( !is_dir($assetDirectory) ) {
return array();
}
$assetBaseUrl = trailingslashit(plugins_url('', $assetDirectory . '/imaginary.file'));
$foundAssets = array();
foreach ($filesToKeys as $fileName => $key) {
$fullBannerPath = $assetDirectory . DIRECTORY_SEPARATOR . $fileName;
if ( !isset($icons[$key]) && is_file($fullBannerPath) ) {
$foundAssets[$key] = $assetBaseUrl . $fileName;
}
}
return $foundAssets;
}
}
endif;
@@ -0,0 +1,51 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !class_exists(Reference::class, false) ):
/**
* This class represents a VCS branch or tag. It's intended as a read only, short-lived container
* that only exists to provide a limited degree of type checking.
*
* @property string $name
* @property string|null version
* @property string $downloadUrl
* @property string $updated
*
* @property string|null $changelog
* @property int|null $downloadCount
*/
class Reference {
private $properties = array();
public function __construct($properties = array()) {
$this->properties = $properties;
}
/**
* @param string $name
* @return mixed|null
*/
public function __get($name) {
return array_key_exists($name, $this->properties) ? $this->properties[$name] : null;
}
/**
* @param string $name
* @param mixed $value
*/
public function __set($name, $value) {
$this->properties[$name] = $value;
}
/**
* @param string $name
* @return bool
*/
public function __isset($name) {
return isset($this->properties[$name]);
}
}
endif;
@@ -0,0 +1,83 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !trait_exists(ReleaseAssetSupport::class, false) ) :
trait ReleaseAssetSupport {
/**
* @var bool Whether to download release assets instead of the auto-generated
* source code archives.
*/
protected $releaseAssetsEnabled = false;
/**
* @var string|null Regular expression that's used to filter release assets
* by file name or URL. Optional.
*/
protected $assetFilterRegex = null;
/**
* How to handle releases that don't have any matching release assets.
*
* @var int
*/
protected $releaseAssetPreference = Api::PREFER_RELEASE_ASSETS;
/**
* Enable updating via release assets.
*
* If the latest release contains no usable assets, the update checker
* will fall back to using the automatically generated ZIP archive.
*
* @param string|null $nameRegex Optional. Use only those assets where
* the file name or URL matches this regex.
* @param int $preference Optional. How to handle releases that don't have
* any matching release assets.
*/
public function enableReleaseAssets($nameRegex = null, $preference = Api::PREFER_RELEASE_ASSETS) {
$this->releaseAssetsEnabled = true;
$this->assetFilterRegex = $nameRegex;
$this->releaseAssetPreference = $preference;
}
/**
* Disable release assets.
*
* @return void
* @noinspection PhpUnused -- Public API
*/
public function disableReleaseAssets() {
$this->releaseAssetsEnabled = false;
$this->assetFilterRegex = null;
}
/**
* Does the specified asset match the name regex?
*
* @param mixed $releaseAsset Data type and structure depend on the host/API.
* @return bool
*/
protected function matchesAssetFilter($releaseAsset) {
if ( $this->assetFilterRegex === null ) {
//The default is to accept all assets.
return true;
}
$name = $this->getFilterableAssetName($releaseAsset);
if ( !is_string($name) ) {
return false;
}
return (bool)preg_match($this->assetFilterRegex, $releaseAsset->name);
}
/**
* Get the part of asset data that will be checked against the filter regex.
*
* @param mixed $releaseAsset
* @return string|null
*/
abstract protected function getFilterableAssetName($releaseAsset);
}
endif;
@@ -0,0 +1,108 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !trait_exists(ReleaseFilteringFeature::class, false) ) :
trait ReleaseFilteringFeature {
/**
* @var callable|null
*/
protected $releaseFilterCallback = null;
/**
* @var int
*/
protected $releaseFilterMaxReleases = 1;
/**
* @var string One of the Api::RELEASE_FILTER_* constants.
*/
protected $releaseFilterByType = Api::RELEASE_FILTER_SKIP_PRERELEASE;
/**
* Set a custom release filter.
*
* Setting a new filter will override the old filter, if any.
*
* @param callable $callback A callback that accepts a version number and a release
* object, and returns a boolean.
* @param int $releaseTypes One of the Api::RELEASE_FILTER_* constants.
* @param int $maxReleases Optional. The maximum number of recent releases to examine
* when trying to find a release that matches the filter. 1 to 100.
* @return $this
*/
public function setReleaseFilter(
$callback,
$releaseTypes = Api::RELEASE_FILTER_SKIP_PRERELEASE,
$maxReleases = 20
) {
if ( $maxReleases > 100 ) {
throw new \InvalidArgumentException(sprintf(
'The max number of releases is too high (%d). It must be 100 or less.',
$maxReleases
));
} else if ( $maxReleases < 1 ) {
throw new \InvalidArgumentException(sprintf(
'The max number of releases is too low (%d). It must be at least 1.',
$maxReleases
));
}
$this->releaseFilterCallback = $callback;
$this->releaseFilterByType = $releaseTypes;
$this->releaseFilterMaxReleases = $maxReleases;
return $this;
}
/**
* Filter releases by their version number.
*
* @param string $regex A regular expression. The release version number must match this regex.
* @param int $releaseTypes
* @param int $maxReleasesToExamine
* @return $this
* @noinspection PhpUnused -- Public API
*/
public function setReleaseVersionFilter(
$regex,
$releaseTypes = Api::RELEASE_FILTER_SKIP_PRERELEASE,
$maxReleasesToExamine = 20
) {
return $this->setReleaseFilter(
function ($versionNumber) use ($regex) {
return (preg_match($regex, $versionNumber) === 1);
},
$releaseTypes,
$maxReleasesToExamine
);
}
/**
* @param string $versionNumber The detected release version number.
* @param object $releaseObject Varies depending on the host/API.
* @return bool
*/
protected function matchesCustomReleaseFilter($versionNumber, $releaseObject) {
if ( !is_callable($this->releaseFilterCallback) ) {
return true; //No custom filter.
}
return call_user_func($this->releaseFilterCallback, $versionNumber, $releaseObject);
}
/**
* @return bool
*/
protected function shouldSkipPreReleases() {
//Maybe this could be a bitfield in the future, if we need to support
//more release types.
return ($this->releaseFilterByType !== Api::RELEASE_FILTER_ALL);
}
/**
* @return bool
*/
protected function hasCustomReleaseFilter() {
return isset($this->releaseFilterCallback) && is_callable($this->releaseFilterCallback);
}
}
endif;
@@ -0,0 +1,83 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
use YahnisElsts\PluginUpdateChecker\v5p6\Theme;
use YahnisElsts\PluginUpdateChecker\v5p6\Utils;
if ( !class_exists(ThemeUpdateChecker::class, false) ):
class ThemeUpdateChecker extends Theme\UpdateChecker implements BaseChecker {
use VcsCheckerMethods;
/**
* ThemeUpdateChecker constructor.
*
* @param Api $api
* @param null $stylesheet
* @param null $customSlug
* @param int $checkPeriod
* @param string $optionName
*/
public function __construct($api, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
$this->api = $api;
parent::__construct($api->getRepositoryUrl(), $stylesheet, $customSlug, $checkPeriod, $optionName);
$this->api->setHttpFilterName($this->getUniqueName('request_update_options'));
$this->api->setStrategyFilterName($this->getUniqueName('vcs_update_detection_strategies'));
$this->api->setSlug($this->slug);
}
public function requestUpdate() {
$api = $this->api;
$api->setLocalDirectory($this->package->getAbsoluteDirectoryPath());
$update = new Theme\Update();
$update->slug = $this->slug;
//Figure out which reference (tag or branch) we'll use to get the latest version of the theme.
$updateSource = $api->chooseReference($this->branch);
if ( $updateSource ) {
$ref = $updateSource->name;
$update->download_url = $updateSource->downloadUrl;
} else {
do_action(
'puc_api_error',
new \WP_Error(
'puc-no-update-source',
'Could not retrieve version information from the repository. '
. 'This usually means that the update checker either can\'t connect '
. 'to the repository or it\'s configured incorrectly.'
),
null, null, $this->slug
);
$ref = $this->branch;
}
//Get headers from the main stylesheet in this branch/tag. Its "Version" header and other metadata
//are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
$remoteHeader = $this->package->getFileHeader($api->getRemoteFile('style.css', $ref));
$update->version = Utils::findNotEmpty(array(
$remoteHeader['Version'],
Utils::get($updateSource, 'version'),
));
//The details URL defaults to the Theme URI header or the repository URL.
$update->details_url = Utils::findNotEmpty(array(
$remoteHeader['ThemeURI'],
$this->package->getHeaderValue('ThemeURI'),
$this->metadataUrl,
));
if ( empty($update->version) ) {
//It looks like we didn't find a valid update after all.
$update = null;
}
$update = $this->filterUpdateResult($update);
return $update;
}
}
endif;
@@ -0,0 +1,59 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6\Vcs;
if ( !trait_exists(VcsCheckerMethods::class, false) ) :
trait VcsCheckerMethods {
/**
* @var string The branch where to look for updates. Defaults to "master".
*/
protected $branch = 'master';
/**
* @var Api Repository API client.
*/
protected $api = null;
public function setBranch($branch) {
$this->branch = $branch;
return $this;
}
/**
* Set authentication credentials.
*
* @param array|string $credentials
* @return $this
*/
public function setAuthentication($credentials) {
$this->api->setAuthentication($credentials);
return $this;
}
/**
* @return Api
*/
public function getVcsApi() {
return $this->api;
}
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) && !empty($update->download_url) ) {
$update->download_url = $this->api->signDownloadUrl($update->download_url);
}
return $update;
}
public function onDisplayConfiguration($panel) {
parent::onDisplayConfiguration($panel);
$panel->row('Branch', $this->branch);
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
$panel->row('API client', get_class($this->api));
}
}
endif;
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,84 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
use WP_CLI;
/**
* Triggers an update check when relevant WP-CLI commands are executed.
*
* When WP-CLI runs certain commands like "wp plugin status" or "wp theme list", it calls
* wp_update_plugins() and wp_update_themes() to refresh update information. This class hooks into
* the same commands and triggers an update check when they are executed.
*
* Note that wp_update_plugins() and wp_update_themes() do not perform an update check *every* time
* they are called. They use a context-dependent delay between update checks. Similarly, this class
* calls Scheduler::maybeCheckForUpdates(), which also dynamically decides whether to actually
* run a check. If you want to force an update check, call UpdateChecker::checkForUpdates() instead.
*/
class WpCliCheckTrigger {
/**
* @var Scheduler
*/
private $scheduler;
/**
* @var string 'plugin' or 'theme'
*/
private $componentType;
/**
* @var bool Whether an update check was already triggered during the current request
* or script execution.
*/
private $wasCheckTriggered = false;
public function __construct($componentType, Scheduler $scheduler) {
if ( !in_array($componentType, ['plugin', 'theme']) ) {
throw new \InvalidArgumentException('Invalid component type. Must be "plugin" or "theme".');
}
$this->componentType = $componentType;
$this->scheduler = $scheduler;
if ( !defined('WP_CLI') || !class_exists(WP_CLI::class, false) ) {
return; //Nothing to do if WP-CLI is not available.
}
/*
* We can't hook directly into wp_update_plugins(), but we can hook into the WP-CLI
* commands that call it. We'll use the "before_invoke:xyz" hook to trigger update checks.
*/
foreach ($this->getRelevantCommands() as $command) {
WP_CLI::add_hook('before_invoke:' . $command, [$this, 'triggerUpdateCheckOnce']);
}
}
private function getRelevantCommands() {
$result = [];
foreach (['status', 'list', 'update'] as $subcommand) {
$result[] = $this->componentType . ' ' . $subcommand;
}
return $result;
}
/**
* Trigger a potential update check once.
*
* @param mixed $input
* @return mixed The input value, unchanged.
* @internal This method is public so that it can be used as a WP-CLI hook callback.
* It should not be called directly.
*
*/
public function triggerUpdateCheckOnce($input = null) {
if ( $this->wasCheckTriggered ) {
return $input;
}
$this->wasCheckTriggered = true;
$this->scheduler->maybeCheckForUpdates();
return $input;
}
}
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1 @@
<?php // Silence is golden.
@@ -0,0 +1,34 @@
<?php
namespace YahnisElsts\PluginUpdateChecker\v5p6;
use YahnisElsts\PluginUpdateChecker\v5\PucFactory as MajorFactory;
use YahnisElsts\PluginUpdateChecker\v5p6\PucFactory as MinorFactory;
require __DIR__ . '/Puc/v5p6/Autoloader.php';
new Autoloader();
require __DIR__ . '/Puc/v5p6/PucFactory.php';
require __DIR__ . '/Puc/v5/PucFactory.php';
//Register classes defined in this version with the factory.
foreach (
array(
'Plugin\\UpdateChecker' => Plugin\UpdateChecker::class,
'Theme\\UpdateChecker' => Theme\UpdateChecker::class,
'Vcs\\PluginUpdateChecker' => Vcs\PluginUpdateChecker::class,
'Vcs\\ThemeUpdateChecker' => Vcs\ThemeUpdateChecker::class,
'GitHubApi' => Vcs\GitHubApi::class,
'BitBucketApi' => Vcs\BitBucketApi::class,
'GitLabApi' => Vcs\GitLabApi::class,
)
as $pucGeneralClass => $pucVersionedClass
) {
MajorFactory::addVersion($pucGeneralClass, $pucVersionedClass, '5.6');
//Also add it to the minor-version factory in case the major-version factory
//was already defined by another, older version of the update checker.
MinorFactory::addVersion($pucGeneralClass, $pucVersionedClass, '5.6');
}
@@ -0,0 +1,10 @@
<?php
/**
* Plugin Update Checker Library 5.6
* http://w-shadow.com/
*
* Copyright 2025 Janis Elsts
* Released under the MIT license. See license.txt for details.
*/
require dirname(__FILE__) . '/load-v5p6.php';
@@ -0,0 +1,874 @@
<?php
#
#
# Parsedown
# http://parsedown.org
#
# (c) Emanuil Rusev
# http://erusev.com
#
# For the full license information, view the LICENSE file that was distributed
# with this source code.
#
# Sourced from: https://github.com/erusev/parsedown (MIT License)
# Required by plugin-update-checker (Puc/v5p6) via vendor/Parsedown.php
#
class Parsedown
{
# ~
const version = '1.8.0';
# ~
function text($text)
{
$Elements = $this->textElements($text);
# convert to markup
$markup = $this->elements($Elements);
# trim line breaks
$markup = trim($markup, "\n");
return $markup;
}
protected function textElements($text)
{
# make sure no definitions are set
$this->DefinitionData = array();
# standardize line breaks
$text = str_replace(array("\r\n", "\r"), "\n", $text);
# remove surrounding line breaks
$text = trim($text, "\n");
# split text into lines
$lines = explode("\n", $text);
# iterate through lines to identify blocks
return $this->linesElements($lines);
}
#
# Setters
#
function setBreaksEnabled($breaksEnabled)
{
$this->breaksEnabled = $breaksEnabled;
return $this;
}
protected $breaksEnabled;
function setMarkupEscaped($markupEscaped)
{
$this->markupEscaped = $markupEscaped;
return $this;
}
protected $markupEscaped;
function setUrlsLinked($urlsLinked)
{
$this->urlsLinked = $urlsLinked;
return $this;
}
protected $urlsLinked = true;
function setSafeMode($safeMode)
{
$this->safeMode = (bool) $safeMode;
return $this;
}
protected $safeMode;
function setStrictMode($strictMode)
{
$this->strictMode = (bool) $strictMode;
return $this;
}
protected $strictMode;
protected $safeLinksWhitelist = array(
'http://',
'https://',
'ftp://',
'ftps://',
'mailto:',
'tel:',
'data:image/png;base64,',
'data:image/gif;base64,',
'data:image/jpeg;base64,',
'irc:',
'ircs:',
'git:',
'ssh:',
'news:',
'steam:',
);
#
# Lines
#
protected $BlockTypes = array(
'#' => array('Header'),
'*' => array('Rule', 'List'),
'+' => array('List'),
'-' => array('SetextHeader', 'Table', 'Rule', 'List'),
'0' => array('List'),
'1' => array('List'),
'2' => array('List'),
'3' => array('List'),
'4' => array('List'),
'5' => array('List'),
'6' => array('List'),
'7' => array('List'),
'8' => array('List'),
'9' => array('List'),
':' => array('Table'),
'<' => array('Comment', 'Markup'),
'=' => array('SetextHeader'),
'>' => array('Quote'),
'[' => array('Reference'),
'_' => array('Rule'),
'`' => array('FencedCode'),
'|' => array('Table'),
'~' => array('FencedCode'),
);
protected $unmarkedBlockTypes = array('Code');
protected function lines(array $lines)
{
return $this->elements($this->linesElements($lines));
}
protected function linesElements(array $lines)
{
$Elements = array();
$CurrentBlock = null;
foreach ($lines as $line)
{
if (chop($line) === '')
{
if (isset($CurrentBlock))
{
$CurrentBlock['interrupted'] = (isset($CurrentBlock['interrupted'])
? $CurrentBlock['interrupted'] + 1 : 1
);
}
continue;
}
while (($beforeTab = strstr($line, "\t", true)) !== false)
{
$shortage = 4 - mb_strlen($beforeTab, 'utf-8') % 4;
$line = $beforeTab . str_repeat(' ', $shortage) . substr($line, strlen($beforeTab) + 1);
}
$indent = strspn($line, ' ');
$text = $indent > 0 ? substr($line, $indent) : $line;
$Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
if (isset($CurrentBlock['continuable']))
{
$methodName = 'block' . $CurrentBlock['type'] . 'Continue';
$Block = $this->$methodName($Line, $CurrentBlock);
if (isset($Block))
{
$CurrentBlock = $Block;
continue;
}
else
{
if ($this->isBlockCompletable($CurrentBlock['type']))
{
$methodName = 'block' . $CurrentBlock['type'] . 'Complete';
$CurrentBlock = $this->$methodName($CurrentBlock);
}
}
}
$marker = $text[0];
$blockTypes = $this->unmarkedBlockTypes;
if (isset($this->BlockTypes[$marker]))
{
foreach ($this->BlockTypes[$marker] as $blockType)
{
$blockTypes[] = $blockType;
}
}
foreach ($blockTypes as $blockType)
{
$Block = $this->{"block$blockType"}($Line, $CurrentBlock);
if (isset($Block))
{
$Block['type'] = $blockType;
if (!isset($Block['identified']))
{
if (isset($CurrentBlock))
{
$Elements[] = $this->extractElement($CurrentBlock);
}
$Block['identified'] = true;
}
if ($this->isBlockContinuable($blockType))
{
$Block['continuable'] = true;
}
$CurrentBlock = $Block;
continue 2;
}
}
if (isset($CurrentBlock) and $CurrentBlock['type'] === 'Paragraph')
{
$Block = $this->paragraphContinue($Line, $CurrentBlock);
}
if (isset($Block))
{
$CurrentBlock = $Block;
}
else
{
if (isset($CurrentBlock))
{
$Elements[] = $this->extractElement($CurrentBlock);
}
$CurrentBlock = $this->paragraph($Line);
$CurrentBlock['identified'] = true;
}
}
if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type']))
{
$methodName = 'block' . $CurrentBlock['type'] . 'Complete';
$CurrentBlock = $this->$methodName($CurrentBlock);
}
if (isset($CurrentBlock))
{
$Elements[] = $this->extractElement($CurrentBlock);
}
return $Elements;
}
protected function extractElement(array $Component)
{
if (!isset($Component['element']))
{
if (isset($Component['markup']))
{
$Component['element'] = array('rawHtml' => $Component['markup']);
}
elseif (isset($Component['hidden']))
{
$Component['element'] = array();
}
}
return $Component['element'];
}
protected function isBlockContinuable($Type)
{
return method_exists($this, 'block' . $Type . 'Continue');
}
protected function isBlockCompletable($Type)
{
return method_exists($this, 'block' . $Type . 'Complete');
}
protected function blockCode($Line, $Block = null)
{
if (isset($Block) and $Block['type'] === 'Paragraph' and !isset($Block['interrupted'])) { return; }
if ($Line['indent'] >= 4)
{
$text = substr($Line['body'], 4);
return array('element' => array('name' => 'pre', 'element' => array('name' => 'code', 'text' => $text)));
}
}
protected function blockCodeContinue($Line, $Block)
{
if ($Line['indent'] >= 4)
{
if (isset($Block['interrupted'])) { $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']); unset($Block['interrupted']); }
$Block['element']['element']['text'] .= "\n" . substr($Line['body'], 4);
return $Block;
}
}
protected function blockCodeComplete($Block) { return $Block; }
protected function blockComment($Line)
{
if ($this->markupEscaped or $this->safeMode) { return; }
if (strpos($Line['text'], '<!--') === 0)
{
$Block = array('element' => array('rawHtml' => $Line['body'], 'autobreak' => true));
if (strpos($Line['text'], '-->') !== false) { $Block['closed'] = true; }
return $Block;
}
}
protected function blockCommentContinue($Line, array $Block)
{
if (isset($Block['closed'])) { return; }
$Block['element']['rawHtml'] .= "\n" . $Line['body'];
if (strpos($Line['text'], '-->') !== false) { $Block['closed'] = true; }
return $Block;
}
protected function blockFencedCode($Line)
{
$marker = $Line['text'][0];
$openerLength = strspn($Line['text'], $marker);
if ($openerLength < 3) { return; }
$infostring = trim(substr($Line['text'], $openerLength), "\t ");
if (strpos($infostring, '`') !== false) { return; }
$Element = array('name' => 'code', 'text' => '');
if ($infostring !== '')
{
$language = substr($infostring, 0, strcspn($infostring, " \t\n\f\r"));
$Element['attributes'] = array('class' => "language-$language");
}
return array('char' => $marker, 'openerLength' => $openerLength, 'element' => array('name' => 'pre', 'element' => $Element));
}
protected function blockFencedCodeContinue($Line, $Block)
{
if (isset($Block['complete'])) { return; }
if (isset($Block['interrupted'])) { $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']); unset($Block['interrupted']); }
if (($len = strspn($Line['text'], $Block['char'])) >= $Block['openerLength'] and chop(substr($Line['text'], $len), ' ') === '')
{
$Block['element']['element']['text'] = substr($Block['element']['element']['text'], 1);
$Block['complete'] = true;
return $Block;
}
$Block['element']['element']['text'] .= "\n" . $Line['body'];
return $Block;
}
protected function blockFencedCodeComplete($Block) { return $Block; }
protected function blockHeader($Line)
{
$level = strspn($Line['text'], '#');
if ($level > 6) { return; }
$text = trim($Line['text'], '#');
if ($this->strictMode and isset($text[0]) and $text[0] !== ' ') { return; }
$text = trim($text, ' ');
return array('element' => array('name' => 'h' . $level, 'handler' => array('function' => 'lineElements', 'argument' => $text, 'destination' => 'elements')));
}
protected function blockList($Line, ?array $CurrentBlock = null)
{
list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]{1,9}+[.\)]');
if (preg_match('/^('.$pattern.'([ ]++|$))(.*+)/', $Line['text'], $matches))
{
$contentIndent = strlen($matches[2]);
if ($contentIndent >= 5) { $contentIndent--; $matches[1] = substr($matches[1], 0, -$contentIndent); $matches[3] = str_repeat(' ', $contentIndent) . $matches[3]; }
elseif ($contentIndent === 0) { $matches[1] .= ' '; }
$markerWithoutWhitespace = strstr($matches[1], ' ', true);
$Block = array('indent' => $Line['indent'], 'pattern' => $pattern, 'data' => array('type' => $name, 'marker' => $matches[1], 'markerType' => ($name === 'ul' ? $markerWithoutWhitespace : substr($markerWithoutWhitespace, -1))), 'element' => array('name' => $name, 'elements' => array()));
$Block['data']['markerTypeRegex'] = preg_quote($Block['data']['markerType'], '/');
if ($name === 'ol')
{
$listStart = ltrim(strstr($matches[1], $Block['data']['markerType'], true), '0') ?: '0';
if ($listStart !== '1') { if (isset($CurrentBlock) and $CurrentBlock['type'] === 'Paragraph' and !isset($CurrentBlock['interrupted'])) { return; } $Block['element']['attributes'] = array('start' => $listStart); }
}
$Block['li'] = array('name' => 'li', 'handler' => array('function' => 'li', 'argument' => !empty($matches[3]) ? array($matches[3]) : array(), 'destination' => 'elements'));
$Block['element']['elements'][] = &$Block['li'];
return $Block;
}
}
protected function blockListContinue($Line, array $Block)
{
if (isset($Block['interrupted']) and empty($Block['li']['handler']['argument'])) { return null; }
$requiredIndent = ($Block['indent'] + strlen($Block['data']['marker']));
if ($Line['indent'] < $requiredIndent and (($Block['data']['type'] === 'ol' and preg_match('/^[0-9]++'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches)) or ($Block['data']['type'] === 'ul' and preg_match('/^'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches))))
{
if (isset($Block['interrupted'])) { $Block['li']['handler']['argument'][] = ''; $Block['loose'] = true; unset($Block['interrupted']); }
unset($Block['li']);
$text = isset($matches[1]) ? $matches[1] : '';
$Block['indent'] = $Line['indent'];
$Block['li'] = array('name' => 'li', 'handler' => array('function' => 'li', 'argument' => array($text), 'destination' => 'elements'));
$Block['element']['elements'][] = &$Block['li'];
return $Block;
}
elseif ($Line['indent'] < $requiredIndent and $this->blockList($Line)) { return null; }
if ($Line['text'][0] === '[' and $this->blockReference($Line)) { return $Block; }
if ($Line['indent'] >= $requiredIndent)
{
if (isset($Block['interrupted'])) { $Block['li']['handler']['argument'][] = ''; $Block['loose'] = true; unset($Block['interrupted']); }
$Block['li']['handler']['argument'][] = substr($Line['body'], $requiredIndent);
return $Block;
}
if (!isset($Block['interrupted'])) { $Block['li']['handler']['argument'][] = preg_replace('/^[ ]{0,'.$requiredIndent.'}+/', '', $Line['body']); return $Block; }
}
protected function blockListComplete(array $Block)
{
if (isset($Block['loose'])) { foreach ($Block['element']['elements'] as &$li) { if (end($li['handler']['argument']) !== '') { $li['handler']['argument'][] = ''; } } }
return $Block;
}
protected function blockQuote($Line)
{
if (preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches))
{
return array('element' => array('name' => 'blockquote', 'handler' => array('function' => 'linesElements', 'argument' => (array) $matches[1], 'destination' => 'elements')));
}
}
protected function blockQuoteContinue($Line, array $Block)
{
if (isset($Block['interrupted'])) { return; }
if ($Line['text'][0] === '>' and preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches)) { $Block['element']['handler']['argument'][] = $matches[1]; return $Block; }
if (!isset($Block['interrupted'])) { $Block['element']['handler']['argument'][] = $Line['text']; return $Block; }
}
protected function blockRule($Line)
{
$marker = $Line['text'][0];
if (substr_count($Line['text'], $marker) >= 3 and chop($Line['text'], " $marker") === '') { return array('element' => array('name' => 'hr')); }
}
protected function blockSetextHeader($Line, ?array $Block = null)
{
if (!isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted'])) { return; }
if ($Line['indent'] < 4 and chop(chop($Line['text'], ' '), $Line['text'][0]) === '') { $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2'; return $Block; }
}
protected function blockMarkup($Line)
{
if ($this->markupEscaped or $this->safeMode) { return; }
if (preg_match('/^<[\/]?+(\w*)(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+(\/)?>/', $Line['text'], $matches))
{
$element = strtolower($matches[1]);
if (in_array($element, $this->textLevelElements)) { return; }
return array('name' => $matches[1], 'element' => array('rawHtml' => $Line['text'], 'autobreak' => true));
}
}
protected function blockMarkupContinue($Line, array $Block)
{
if (isset($Block['closed']) or isset($Block['interrupted'])) { return; }
$Block['element']['rawHtml'] .= "\n" . $Line['body'];
return $Block;
}
protected function blockReference($Line)
{
if (strpos($Line['text'], ']') !== false and preg_match('/^\[(.+?)\]:[ ]*+<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*+$/', $Line['text'], $matches))
{
$id = strtolower($matches[1]);
$this->DefinitionData['Reference'][$id] = array('url' => $matches[2], 'title' => isset($matches[3]) ? $matches[3] : null);
return array('element' => array());
}
}
protected function blockTable($Line, ?array $Block = null)
{
if (!isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted'])) { return; }
if (strpos($Block['element']['handler']['argument'], '|') === false and strpos($Line['text'], '|') === false and strpos($Line['text'], ':') === false or strpos($Block['element']['handler']['argument'], "\n") !== false) { return; }
if (chop($Line['text'], ' -:|') !== '') { return; }
$alignments = array();
$divider = trim(trim($Line['text']), '|');
$dividerCells = explode('|', $divider);
foreach ($dividerCells as $dividerCell)
{
$dividerCell = trim($dividerCell);
if ($dividerCell === '') { return; }
$alignment = null;
if ($dividerCell[0] === ':') { $alignment = 'left'; }
if (substr($dividerCell, -1) === ':') { $alignment = $alignment === 'left' ? 'center' : 'right'; }
$alignments[] = $alignment;
}
$HeaderElements = array();
$header = trim(trim($Block['element']['handler']['argument']), '|');
$headerCells = explode('|', $header);
if (count($headerCells) !== count($alignments)) { return; }
foreach ($headerCells as $index => $headerCell)
{
$headerCell = trim($headerCell);
$HeaderElement = array('name' => 'th', 'handler' => array('function' => 'lineElements', 'argument' => $headerCell, 'destination' => 'elements'));
if (isset($alignments[$index])) { $HeaderElement['attributes'] = array('style' => "text-align: {$alignments[$index]};"); }
$HeaderElements[] = $HeaderElement;
}
$Block = array('alignments' => $alignments, 'identified' => true, 'element' => array('name' => 'table', 'elements' => array()));
$Block['element']['elements'][] = array('name' => 'thead');
$Block['element']['elements'][] = array('name' => 'tbody', 'elements' => array());
$Block['element']['elements'][0]['elements'][] = array('name' => 'tr', 'elements' => $HeaderElements);
return $Block;
}
protected function blockTableContinue($Line, array $Block)
{
if (isset($Block['interrupted'])) { return; }
if (count($Block['alignments']) === 1 or $Line['text'][0] === '|' or strpos($Line['text'], '|'))
{
$Elements = array();
$row = trim(trim($Line['text']), '|');
preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]++`|`)++/', $row, $matches);
$cells = array_slice($matches[0], 0, count($Block['alignments']));
foreach ($cells as $index => $cell)
{
$cell = trim($cell);
$Element = array('name' => 'td', 'handler' => array('function' => 'lineElements', 'argument' => $cell, 'destination' => 'elements'));
if (isset($Block['alignments'][$index])) { $Element['attributes'] = array('style' => 'text-align: ' . $Block['alignments'][$index] . ';'); }
$Elements[] = $Element;
}
$Block['element']['elements'][1]['elements'][] = array('name' => 'tr', 'elements' => $Elements);
return $Block;
}
}
protected function paragraph($Line)
{
return array('type' => 'Paragraph', 'element' => array('name' => 'p', 'handler' => array('function' => 'lineElements', 'argument' => $Line['text'], 'destination' => 'elements')));
}
protected function paragraphContinue($Line, array $Block)
{
if (isset($Block['interrupted'])) { return; }
$Block['element']['handler']['argument'] .= "\n" . $Line['text'];
return $Block;
}
protected $InlineTypes = array(
'!' => array('Image'), '&' => array('SpecialCharacter'), '*' => array('Emphasis'),
':' => array('Url'), '<' => array('UrlTag', 'EmailTag', 'Markup'), '[' => array('Link'),
'_' => array('Emphasis'), '`' => array('Code'), '~' => array('Strikethrough'), '\\' => array('EscapeSequence'),
);
protected $inlineMarkerList = '!*_&[:<`~\\';
public function line($text, $nonNestables = array())
{
return $this->elements($this->lineElements($text, $nonNestables));
}
protected function lineElements($text, $nonNestables = array())
{
$text = str_replace(array("\r\n", "\r"), "\n", $text);
$Elements = array();
$nonNestables = (empty($nonNestables) ? array() : array_combine($nonNestables, $nonNestables));
while ($excerpt = strpbrk($text, $this->inlineMarkerList))
{
$marker = $excerpt[0];
$markerPosition = strlen($text) - strlen($excerpt);
$Excerpt = array('text' => $excerpt, 'context' => $text);
foreach ($this->InlineTypes[$marker] as $inlineType)
{
if (isset($nonNestables[$inlineType])) { continue; }
$Inline = $this->{"inline$inlineType"}($Excerpt);
if (!isset($Inline)) { continue; }
if (isset($Inline['position']) and $Inline['position'] > $markerPosition) { continue; }
if (!isset($Inline['position'])) { $Inline['position'] = $markerPosition; }
$Inline['element']['nonNestables'] = isset($Inline['element']['nonNestables']) ? array_merge($Inline['element']['nonNestables'], $nonNestables) : $nonNestables;
$unmarkedText = substr($text, 0, $Inline['position']);
$InlineText = $this->inlineText($unmarkedText);
$Elements[] = $InlineText['element'];
$Elements[] = $this->extractElement($Inline);
$text = substr($text, $Inline['position'] + $Inline['extent']);
continue 2;
}
$unmarkedText = substr($text, 0, $markerPosition + 1);
$InlineText = $this->inlineText($unmarkedText);
$Elements[] = $InlineText['element'];
$text = substr($text, $markerPosition + 1);
}
$InlineText = $this->inlineText($text);
$Elements[] = $InlineText['element'];
foreach ($Elements as &$Element) { if (!isset($Element['autobreak'])) { $Element['autobreak'] = false; } }
return $Elements;
}
protected function inlineText($text)
{
$Inline = array('extent' => strlen($text), 'element' => array());
$Inline['element']['elements'] = self::pregReplaceElements(
$this->breaksEnabled ? '/[ ]*+\n/' : '/(?:[ ]*+\\\\|[ ]{2,}+)\n/',
array(array('name' => 'br'), array('text' => "\n")),
$text
);
return $Inline;
}
protected function inlineCode($Excerpt)
{
$marker = $Excerpt['text'][0];
if (preg_match('/^(['.$marker.']++)[ ]*+(.+?)[ ]*+(?<!['.$marker.'])\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
{
return array('extent' => strlen($matches[0]), 'element' => array('name' => 'code', 'text' => preg_replace('/[ ]*+\n/', ' ', $matches[2])));
}
}
protected function inlineEmailTag($Excerpt)
{
$hostnameLabel = '[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?';
$commonMarkEmail = '[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]++@' . $hostnameLabel . '(?:\.' . $hostnameLabel . ')*';
if (strpos($Excerpt['text'], '>') !== false and preg_match("/^<((mailto:)?$commonMarkEmail)>/i", $Excerpt['text'], $matches))
{
$url = $matches[1];
if (!isset($matches[2])) { $url = "mailto:$url"; }
return array('extent' => strlen($matches[0]), 'element' => array('name' => 'a', 'text' => $matches[1], 'attributes' => array('href' => $url)));
}
}
protected function inlineEmphasis($Excerpt)
{
if (!isset($Excerpt['text'][1])) { return; }
$marker = $Excerpt['text'][0];
if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) { $emphasis = 'strong'; }
elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) { $emphasis = 'em'; }
else { return; }
return array('extent' => strlen($matches[0]), 'element' => array('name' => $emphasis, 'handler' => array('function' => 'lineElements', 'argument' => $matches[1], 'destination' => 'elements')));
}
protected function inlineEscapeSequence($Excerpt)
{
if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
{
return array('element' => array('rawHtml' => $Excerpt['text'][1]), 'extent' => 2);
}
}
protected function inlineImage($Excerpt)
{
if (!isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[') { return; }
$Excerpt['text'] = substr($Excerpt['text'], 1);
$Link = $this->inlineLink($Excerpt);
if ($Link === null) { return; }
$Inline = array('extent' => $Link['extent'] + 1, 'element' => array('name' => 'img', 'attributes' => array('src' => $Link['element']['attributes']['href'], 'alt' => $Link['element']['handler']['argument']), 'autobreak' => true));
$Inline['element']['attributes'] += $Link['element']['attributes'];
unset($Inline['element']['attributes']['href']);
return $Inline;
}
protected function inlineLink($Excerpt)
{
$Element = array('name' => 'a', 'handler' => array('function' => 'lineElements', 'argument' => null, 'destination' => 'elements'), 'nonNestables' => array('Url', 'Link'), 'attributes' => array('href' => null, 'title' => null));
$extent = 0;
$remainder = $Excerpt['text'];
if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches)) { $Element['handler']['argument'] = $matches[1]; $extent += strlen($matches[0]); $remainder = substr($remainder, $extent); }
else { return; }
if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*+"|\'[^\']*+\'))?\s*+[)]/', $remainder, $matches))
{
$Element['attributes']['href'] = $matches[1];
if (isset($matches[2])) { $Element['attributes']['title'] = substr($matches[2], 1, -1); }
$extent += strlen($matches[0]);
}
else
{
if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches)) { $definition = strlen($matches[1]) ? $matches[1] : $Element['handler']['argument']; $definition = strtolower($definition); $extent += strlen($matches[0]); }
else { $definition = strtolower($Element['handler']['argument']); }
if (!isset($this->DefinitionData['Reference'][$definition])) { return; }
$Definition = $this->DefinitionData['Reference'][$definition];
$Element['attributes']['href'] = $Definition['url'];
$Element['attributes']['title'] = $Definition['title'];
}
return array('extent' => $extent, 'element' => $Element);
}
protected function inlineMarkup($Excerpt)
{
if ($this->markupEscaped or $this->safeMode or strpos($Excerpt['text'], '>') === false) { return; }
if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w[\w-]*+[ ]*+>/s', $Excerpt['text'], $matches)) { return array('element' => array('rawHtml' => $matches[0]), 'extent' => strlen($matches[0])); }
if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?+[^-])*-->/s', $Excerpt['text'], $matches)) { return array('element' => array('rawHtml' => $matches[0]), 'extent' => strlen($matches[0])); }
if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w[\w-]*+(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+\/?>/s', $Excerpt['text'], $matches)) { return array('element' => array('rawHtml' => $matches[0]), 'extent' => strlen($matches[0])); }
}
protected function inlineSpecialCharacter($Excerpt)
{
if (substr($Excerpt['text'], 1, 1) !== ' ' and strpos($Excerpt['text'], ';') !== false and preg_match('/^&(#?+[0-9a-zA-Z]++);/', $Excerpt['text'], $matches))
{
return array('element' => array('rawHtml' => '&' . $matches[1] . ';'), 'extent' => strlen($matches[0]));
}
}
protected function inlineStrikethrough($Excerpt)
{
if (!isset($Excerpt['text'][1])) { return; }
if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
{
return array('extent' => strlen($matches[0]), 'element' => array('name' => 'del', 'handler' => array('function' => 'lineElements', 'argument' => $matches[1], 'destination' => 'elements')));
}
}
protected function inlineUrl($Excerpt)
{
if ($this->urlsLinked !== true or !isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/') { return; }
if (strpos($Excerpt['context'], 'http') !== false and preg_match('/\bhttps?+:[\/]{2}[^\s<]+\b\/*+/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
{
$url = $matches[0][0];
return array('extent' => strlen($matches[0][0]), 'position' => $matches[0][1], 'element' => array('name' => 'a', 'text' => $url, 'attributes' => array('href' => $url)));
}
}
protected function inlineUrlTag($Excerpt)
{
if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w++:\/{2}[^ >]++)>/i', $Excerpt['text'], $matches))
{
return array('extent' => strlen($matches[0]), 'element' => array('name' => 'a', 'text' => $matches[1], 'attributes' => array('href' => $matches[1])));
}
}
protected function unmarkedText($text)
{
$Inline = $this->inlineText($text);
return $this->element($Inline['element']);
}
protected function handle(array $Element)
{
if (isset($Element['handler']))
{
if (!isset($Element['nonNestables'])) { $Element['nonNestables'] = array(); }
if (is_string($Element['handler'])) { $function = $Element['handler']; $argument = $Element['text']; unset($Element['text']); $destination = 'rawHtml'; }
else { $function = $Element['handler']['function']; $argument = $Element['handler']['argument']; $destination = $Element['handler']['destination']; }
$Element[$destination] = $this->{$function}($argument, $Element['nonNestables']);
if ($destination === 'handler') { $Element = $this->handle($Element); }
unset($Element['handler']);
}
return $Element;
}
protected function handleElementRecursive(array $Element) { return $this->elementApplyRecursive(array($this, 'handle'), $Element); }
protected function handleElementsRecursive(array $Elements) { return $this->elementsApplyRecursive(array($this, 'handle'), $Elements); }
protected function elementApplyRecursive($closure, array $Element)
{
$Element = call_user_func($closure, $Element);
if (isset($Element['elements'])) { $Element['elements'] = $this->elementsApplyRecursive($closure, $Element['elements']); }
elseif (isset($Element['element'])) { $Element['element'] = $this->elementApplyRecursive($closure, $Element['element']); }
return $Element;
}
protected function elementApplyRecursiveDepthFirst($closure, array $Element)
{
if (isset($Element['elements'])) { $Element['elements'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['elements']); }
elseif (isset($Element['element'])) { $Element['element'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['element']); }
return call_user_func($closure, $Element);
}
protected function elementsApplyRecursive($closure, array $Elements) { foreach ($Elements as &$Element) { $Element = $this->elementApplyRecursive($closure, $Element); } return $Elements; }
protected function elementsApplyRecursiveDepthFirst($closure, array $Elements) { foreach ($Elements as &$Element) { $Element = $this->elementApplyRecursiveDepthFirst($closure, $Element); } return $Elements; }
protected function element(array $Element)
{
if ($this->safeMode) { $Element = $this->sanitiseElement($Element); }
$Element = $this->handle($Element);
$hasName = isset($Element['name']);
$markup = '';
if ($hasName) { $markup .= '<' . $Element['name']; if (isset($Element['attributes'])) { foreach ($Element['attributes'] as $name => $value) { if ($value === null) { continue; } $markup .= " $name=\"" . self::escape($value) . '"'; } } }
$permitRawHtml = false;
if (isset($Element['text'])) { $text = $Element['text']; }
elseif (isset($Element['rawHtml'])) { $text = $Element['rawHtml']; $allowRawHtmlInSafeMode = isset($Element['allowRawHtmlInSafeMode']) && $Element['allowRawHtmlInSafeMode']; $permitRawHtml = !$this->safeMode || $allowRawHtmlInSafeMode; }
$hasContent = isset($text) || isset($Element['element']) || isset($Element['elements']);
if ($hasContent) { $markup .= $hasName ? '>' : ''; if (isset($Element['elements'])) { $markup .= $this->elements($Element['elements']); } elseif (isset($Element['element'])) { $markup .= $this->element($Element['element']); } else { $markup .= $permitRawHtml ? $text : self::escape($text, true); } $markup .= $hasName ? '</' . $Element['name'] . '>' : ''; }
elseif ($hasName) { $markup .= ' />'; }
return $markup;
}
protected function elements(array $Elements)
{
$markup = '';
$autoBreak = true;
foreach ($Elements as $Element)
{
if (empty($Element)) { continue; }
$autoBreakNext = (isset($Element['autobreak']) ? $Element['autobreak'] : isset($Element['name']));
$autoBreak = !$autoBreak ? $autoBreak : $autoBreakNext;
$markup .= ($autoBreak ? "\n" : '') . $this->element($Element);
$autoBreak = $autoBreakNext;
}
$markup .= $autoBreak ? "\n" : '';
return $markup;
}
protected function li($lines)
{
$Elements = $this->linesElements($lines);
if (!in_array('', $lines) and isset($Elements[0]) and isset($Elements[0]['name']) and $Elements[0]['name'] === 'p') { unset($Elements[0]['name']); }
return $Elements;
}
protected static function pregReplaceElements($regexp, $Elements, $text)
{
$newElements = array();
while (preg_match($regexp, $text, $matches, PREG_OFFSET_CAPTURE))
{
$offset = $matches[0][1];
$before = substr($text, 0, $offset);
$after = substr($text, $offset + strlen($matches[0][0]));
$newElements[] = array('text' => $before);
foreach ($Elements as $Element) { $newElements[] = $Element; }
$text = $after;
}
$newElements[] = array('text' => $text);
return $newElements;
}
function parse($text) { return $this->text($text); }
protected function sanitiseElement(array $Element)
{
static $goodAttribute = '/^[a-zA-Z0-9][a-zA-Z0-9-_]*+$/';
static $safeUrlNameToAtt = array('a' => 'href', 'img' => 'src');
if (!isset($Element['name'])) { unset($Element['attributes']); return $Element; }
if (isset($safeUrlNameToAtt[$Element['name']])) { $Element = $this->filterUnsafeUrlInAttribute($Element, $safeUrlNameToAtt[$Element['name']]); }
if (!empty($Element['attributes'])) { foreach ($Element['attributes'] as $att => $val) { if (!preg_match($goodAttribute, $att)) { unset($Element['attributes'][$att]); } elseif (self::striAtStart($att, 'on')) { unset($Element['attributes'][$att]); } } }
return $Element;
}
protected function filterUnsafeUrlInAttribute(array $Element, $attribute)
{
foreach ($this->safeLinksWhitelist as $scheme) { if (self::striAtStart($Element['attributes'][$attribute], $scheme)) { return $Element; } }
$Element['attributes'][$attribute] = str_replace(':', '%3A', $Element['attributes'][$attribute]);
return $Element;
}
protected static function escape($text, $allowQuotes = false) { return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8'); }
protected static function striAtStart($string, $needle) { $len = strlen($needle); if ($len > strlen($string)) { return false; } return strtolower(substr($string, 0, $len)) === strtolower($needle); }
static function instance($name = 'default')
{
if (isset(self::$instances[$name])) { return self::$instances[$name]; }
$instance = new static();
self::$instances[$name] = $instance;
return $instance;
}
private static $instances = array();
protected $DefinitionData;
protected $specialCharacters = array('\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|', '~');
protected $StrongRegex = array('*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*+[*])+?)[*]{2}(?![*])/s', '_' => '/^__((?:\\\\_|[^_]|_[^_]*+_)+?)__(?!_)/us');
protected $EmRegex = array('*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us');
protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*+(?:\s*+=\s*+(?:[^"\'=<>`\s]+|"[^"]*+"|\'[^\']*+\'))?+';
protected $voidElements = array('area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source');
protected $textLevelElements = array('a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont', 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing', 'i', 'rp', 'del', 'code', 'strike', 'marquee', 'q', 'rt', 'ins', 'font', 'strong', 's', 'tt', 'kbd', 'mark', 'u', 'xm', 'sub', 'nobr', 'sup', 'ruby', 'var', 'span', 'wbr', 'time');
}
@@ -0,0 +1,158 @@
<?php
/**
* WordPress readme.txt parser.
*
* Parses a readme.txt file formatted according to the WordPress.org plugin readme standard.
* This is the vendor file expected by plugin-update-checker (Puc v5) at:
* plugin-update-checker/vendor/PucReadmeParser.php
*
* Based on the WordPress.org readme parser. Restored because the vendor/ directory
* was missing from the plugin package, causing:
* Fatal error: Class "PucReadmeParser" not found in .../Puc/v5p6/Vcs/Api.php:139
*/
if ( ! class_exists( 'PucReadmeParser', false ) ) :
class PucReadmeParser {
/**
* Parse the contents of a readme.txt file.
*
* @param string $contents The raw contents of a readme.txt file.
* @return array Associative array of parsed fields.
*/
public function parse_readme_contents( $contents ) {
$contents = (string) $contents;
$contents = preg_replace( '/\r\n|\r/', "\n", $contents );
$contents = trim( $contents );
if ( empty( $contents ) ) {
return array();
}
$data = array(
'name' => '',
'tags' => array(),
'requires' => '',
'tested' => '',
'requires_php' => '',
'contributors' => array(),
'stable_tag' => '',
'donate_link' => '',
'short_description' => '',
'sections' => array(),
);
$lines = explode( "\n", $contents );
// First line: plugin name (== Plugin Name ==)
$name_line = array_shift( $lines );
if ( preg_match( '/^=+\s*(.+?)\s*=+$/', $name_line, $m ) ) {
$data['name'] = $m[1];
}
// Parse header fields up to the first blank line after the name
$in_header = true;
$remaining = array();
foreach ( $lines as $line ) {
if ( $in_header ) {
if ( trim( $line ) === '' ) {
// blank line ends the header block only if we've seen at least one header
if ( ! empty( $data['requires'] ) || ! empty( $data['stable_tag'] ) || ! empty( $data['short_description'] ) ) {
$in_header = false;
}
$remaining[] = $line;
continue;
}
if ( preg_match( '/^([^:]+):\s*(.*)$/', $line, $m ) ) {
$key = strtolower( trim( $m[1] ) );
$value = trim( $m[2] );
switch ( $key ) {
case 'tags':
$data['tags'] = array_map( 'trim', explode( ',', $value ) );
break;
case 'requires at least':
$data['requires'] = $value;
break;
case 'tested up to':
$data['tested'] = $value;
break;
case 'requires php':
$data['requires_php'] = $value;
break;
case 'stable tag':
$data['stable_tag'] = $value;
break;
case 'contributors':
$data['contributors'] = array_map( 'trim', explode( ',', $value ) );
break;
case 'donate link':
$data['donate_link'] = $value;
break;
}
} else {
// Not a header field — treat as short description or start of body
$trimmed = trim( $line );
if ( $trimmed !== '' && empty( $data['short_description'] ) ) {
$data['short_description'] = $trimmed;
}
$remaining[] = $line;
}
} else {
$remaining[] = $line;
}
}
// Short description: first non-empty, non-header line before sections
if ( empty( $data['short_description'] ) ) {
foreach ( $remaining as $line ) {
$trimmed = trim( $line );
if ( $trimmed !== '' && ! preg_match( '/^=+/', $trimmed ) ) {
$data['short_description'] = $trimmed;
break;
}
}
}
// Truncate short description at 150 chars
if ( strlen( $data['short_description'] ) > 150 ) {
$data['short_description'] = substr( $data['short_description'], 0, 150 );
}
// Parse sections (== Section Name ==)
$body = implode( "\n", $remaining );
$section_parts = preg_split( '/^==\s*(.+?)\s*==\s*$/m', $body, -1, PREG_SPLIT_DELIM_CAPTURE );
// section_parts: [ text_before, name1, body1, name2, body2, ... ]
for ( $i = 1; $i < count( $section_parts ); $i += 2 ) {
$section_name = strtolower( trim( $section_parts[ $i ] ) );
$section_name = str_replace( ' ', '_', $section_name );
$section_body = isset( $section_parts[ $i + 1 ] ) ? trim( $section_parts[ $i + 1 ] ) : '';
$data['sections'][ $section_name ] = $section_body;
}
return $data;
}
/**
* Parse a readme.txt file by path.
*
* @param string $file_path Absolute path to the readme.txt file.
* @return array|WP_Error Parsed data or WP_Error on failure.
*/
public function parse_readme( $file_path ) {
if ( ! is_readable( $file_path ) ) {
if ( function_exists( 'is_wp_error' ) ) {
return new WP_Error( 'puc_readme_not_found', 'Readme file not found: ' . $file_path );
}
return array();
}
return $this->parse_readme_contents( file_get_contents( $file_path ) );
}
}
endif;
@@ -0,0 +1 @@
<?php // Silence is golden
@@ -0,0 +1 @@
<?php // Silence is golden
@@ -0,0 +1,93 @@
msgid ""
msgstr ""
"Project-Id-Version: Pressable Cache Management\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-08-02 19:05+0000\n"
"PO-Revision-Date: 2021-08-09 12:00+0000\n"
"Last-Translator: \n"
"Language-Team: Deutsch\n"
"Language: de-DE\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Loco https://localise.biz/\n"
"X-Loco-Version: 2.5.3; wp-5.8\n"
"X-Domain: pressable_cache_management"
#: admin/settings-register.php:37
msgid "Cache Management By"
msgstr "Cache-Verwaltung von"
#: admin/settings-register.php:93
msgid "Extend Batcache"
msgstr "Batchcache erweitern"
#: admin/settings-register.php:93
msgid "Extend the length of time a Batcache render is stored"
msgstr "Verlängern Sie die Speicherdauer eines Batcache-Renderings"
#: admin/settings-register.php:89
msgid "Flush Batcache automatically when new page/post is updated"
msgstr ""
"Batcache automatisch leeren, wenn eine neue Seite/ein neuer Beitrag "
"aktualisiert wird"
#: admin/settings-callbacks.php:59
msgid "Flush Cache"
msgstr "Cache leeren"
#: admin/settings-register.php:86
msgid "Flush cache automatically on plugin & theme update"
msgstr "Cache automatisch bei Plugin- und Theme-Update leeren"
#: admin/settings-register.php:89
msgid "Flush Cache on Edit"
msgstr "Cache beim Bearbeiten leeren"
#: admin/settings-register.php:86
msgid "Flush Cache on Update"
msgstr "Cache beim Update leeren"
#: admin/settings-register.php:83
msgid "Flush Object Cache"
msgstr "Objekt-Cache leeren"
#: admin/settings-register.php:83
msgid "Flush your Pressable site object cache (Database)"
msgstr "Leeren Sie Ihren Pressable-Site-Objekt-Cache (Datenbank)"
#. URI of the plugin
msgid "https://pressable.com"
msgstr ""
#. Description of the plugin
msgid "Presable cache management made easy"
msgstr "Presable Cache Management leicht gemacht"
#: admin/admin-menu.php:53
msgid "Pressable Cache"
msgstr "Pressable Cache"
#. Name of the plugin
#: admin/admin-menu.php:30
msgid "Pressable Cache Management"
msgstr "Pressable Cache Management"
#: admin/admin-menu.php:53
msgid "Pressable Cache Management Settings"
msgstr "Pressable Cache-Verwaltungseinstellungen"
#. Author of the plugin
msgid "Pressable Customer Success Team"
msgstr "Pressable Customer Success Team"
#: admin/settings-callbacks.php:242
msgid "Purge CDN Cache"
msgstr "CDN-Cache leeren"
#: admin/settings-callbacks.php:23
msgid "These settings enable you to manage cache on your Pressable site."
msgstr ""
"Mit diesen Einstellungen können Sie den Cache auf Ihrer Pressable-Site "
"verwalten."
@@ -0,0 +1,238 @@
msgid ""
msgstr ""
"Project-Id-Version: Pressable Cache Management\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-08-02 19:05+0000\n"
"PO-Revision-Date: 2021-08-09 12:01+0000\n"
"Last-Translator: \n"
"Language-Team: Deutsch\n"
"Language: de_DE\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Loco https://localise.biz/\n"
"X-Loco-Version: 2.5.3; wp-5.8\n"
"X-Domain: pressable_cache_management"
#: admin/settings-register.php:37
msgid "Cache Management By"
msgstr "Cache-Verwaltung von"
#: admin/settings-register.php:93
msgid "Extend Batcache"
msgstr "Batchcache erweitern"
#: admin/settings-register.php:93
msgid "Extend the length of time a Batcache render is stored"
msgstr "Verlängern Sie die Speicherdauer eines Batcache-Renderings"
#: admin/settings-register.php:89
msgid "Flush Batcache automatically when new page/post is updated"
msgstr ""
"Batcache automatisch leeren, wenn eine neue Seite/ein neuer Beitrag "
"aktualisiert wird"
#: admin/settings-callbacks.php:59
msgid "Flush Cache"
msgstr "Cache leeren"
#: admin/settings-register.php:86
msgid "Flush cache automatically on plugin & theme update"
msgstr "Cache automatisch bei Plugin- und Theme-Update leeren"
#: admin/settings-register.php:89
msgid "Flush Cache on Edit"
msgstr "Cache beim Bearbeiten leeren"
#: admin/settings-register.php:86
msgid "Flush Cache on Update"
msgstr "Cache beim Update leeren"
#: admin/settings-register.php:83
msgid "Flush Object Cache"
msgstr "Objekt-Cache leeren"
#: admin/settings-register.php:83
msgid "Flush your Pressable site object cache (Database)"
msgstr "Leeren Sie Ihren Pressable-Site-Objekt-Cache (Datenbank)"
#. URI of the plugin
msgid "https://pressable.com"
msgstr ""
#. Description of the plugin
msgid "Presable cache management made easy"
msgstr "Presable Cache Management leicht gemacht"
#: admin/admin-menu.php:53
msgid "Pressable Cache"
msgstr "Pressable Cache"
#. Name of the plugin
#: admin/admin-menu.php:30
msgid "Pressable Cache Management"
msgstr "Pressable Cache Management"
#: admin/admin-menu.php:53
msgid "Pressable Cache Management Settings"
msgstr "Pressable Cache-Verwaltungseinstellungen"
#. Author of the plugin
msgid "Pressable Customer Success Team"
msgstr "Pressable Customer Success Team"
#: admin/settings-callbacks.php:242
msgid "Purge CDN Cache"
msgstr "CDN-Cache leeren"
#: admin/settings-callbacks.php:23
msgid "These settings enable you to manage cache on your Pressable site."
msgstr ""
"Mit diesen Einstellungen können Sie den Cache auf Ihrer Pressable-Site "
"verwalten."
msgid "Manage Edge Cache Settings"
msgstr "Edge-Cache-Einstellungen verwalten"
msgid "These settings enable you to manage Edge Cache settings."
msgstr "Mit diesen Einstellungen können Sie die Edge-Cache-Einstellungen verwalten."
msgid "Enable or disable the edge cache for this site."
msgstr "Edge-Cache für diese Website aktivieren oder deaktivieren."
msgid "LAST FLUSHED"
msgstr "ZULETZT GELEERT"
msgid "SINGLE PAGE LAST FLUSHED"
msgstr "EINZELSEITE ZULETZT GELEERT"
msgid "SINGLE PAGE URL"
msgstr "EINZELSEITEN-URL"
msgid "Failed to retrieve status."
msgstr "Status konnte nicht abgerufen werden."
msgid "Could not connect to server."
msgstr "Verbindung zum Server fehlgeschlagen."
msgid "Use the refresh button to manually check your cache status. If the cache status remains broken for more than 4 minutes after two visits are recorded on your site, it is likely that caching is failing due to cookie interference from your plugin, theme or custom code."
msgstr "Verwenden Sie die Schaltfläche \"Aktualisieren\", um den Cache-Status manuell zu überprüfen. Wenn der Cache-Status nach zwei Besuchen auf Ihrer Website länger als 4 Minuten als defekt angezeigt wird, liegt es wahrscheinlich an Cookie-Interferenzen durch Ihr Plugin, Theme oder benutzerdefinierten Code."
msgid "Flush Batcache for WooCommerce Product Pages — Enabled"
msgstr "Batcache für WooCommerce-Produktseiten leeren — Aktiviert"
msgid "Automatically flush individual pages, including product pages updated via the WooCommerce API."
msgstr "Einzelne Seiten automatisch leeren, einschließlich Produktseiten, die über die WooCommerce-API aktualisiert wurden."
msgid "You can Flush Cache for Individual page or post from page preview."
msgstr "Sie können den Cache für einzelne Seiten oder Beiträge über die Seitenvorschau leeren."
msgid "Flush Object & Edge Cache"
msgstr "Objekt- & Edge-Cache leeren"
msgid "Cache Settings"
msgstr "Cache-Einstellungen"
msgid "Cache Management"
msgstr "Cache-Verwaltung"
msgid "Cache Control"
msgstr "Cache-Steuerung"
msgid "CURRENT CACHE MAX-AGE"
msgstr "AKTUELLE CACHE MAX-AGE"
msgid "Checking…"
msgstr "Wird geprüft…"
msgid "Object Cache Flushed successfully."
msgstr "Objekt-Cache erfolgreich geleert."
msgid "Edge Cache purged successfully."
msgstr "Edge-Cache erfolgreich geleert."
msgid "Edge Cache Purged successfully."
msgstr "Edge-Cache erfolgreich geleert."
msgid "Error: Edge Cache Plugin is not active. Purge aborted."
msgstr "Fehler: Edge Cache Plugin ist nicht aktiv. Bereinigung abgebrochen."
msgid "Edge Cache purge failed (possibly disabled or rate-limited)."
msgstr "Edge-Cache-Bereinigung fehlgeschlagen."
msgid "Edge Cache Plugin not found; skipping Edge Cache purge."
msgstr "Edge Cache Plugin nicht gefunden."
msgid "Edge Cache Defensive Mode"
msgstr "Edge-Cache-Schutzmodus"
msgid "Adds an extra layer of protection against spam bots and DDoS attacks. When enabled, visitors' browsers must complete a small challenge before accessing the site. Legitimate users may see a brief challenge page. Edge Cache must be enabled to use this feature."
msgstr "Fügt eine zusätzliche Schutzschicht gegen Spam-Bots und DDoS-Angriffe hinzu. Wenn aktiviert, müssen die Browser der Besucher eine kleine Herausforderung abschließen, bevor sie auf die Website zugreifen. Legitime Benutzer sehen möglicherweise kurz eine Herausforderungsseite. Edge Cache muss aktiviert sein, um diese Funktion zu nutzen."
msgid "Checking status\u2026"
msgstr ""
msgid "Enable Defensive Mode"
msgstr ""
msgid "Disable Defensive Mode"
msgstr ""
msgid "Enabled"
msgstr ""
msgid "at"
msgstr ""
msgid "Enabled until"
msgstr "Aktiv bis"
msgid "Disabled"
msgstr "Deaktiviert"
msgid "Disabled \u2014 Edge Cache must be enabled first."
msgstr ""
msgid "Unable to retrieve Defensive Mode status."
msgstr ""
msgid "Could not retrieve Defensive Mode status."
msgstr ""
msgid "Defensive Mode enabled for %s."
msgstr ""
msgid "Defensive Mode disabled."
msgstr "Schutzmodus deaktiviert."
msgid "Error: Edge Cache Plugin is not active."
msgstr ""
msgid "Unknown error enabling Defensive Mode."
msgstr ""
msgid "Unknown error disabling Defensive Mode."
msgstr ""
msgid "Could not retrieve Defensive Mode status from server."
msgstr ""
msgid "Edge Cache Defensive Mode"
msgstr "Edge Cache Defensiv-Modus"
msgid "Adds an extra layer of protection against spam bots and DDoS attacks. When enabled, visitors' browsers must complete a small challenge before accessing the site. Legitimate users may see a brief challenge page. Edge Cache must be enabled to use this feature."
msgstr "Fügt eine zusätzliche Schutzebene gegen Spam-Bots und DDoS-Angriffe hinzu. Wenn aktiviert, müssen die Browser der Besucher eine kleine Herausforderung bestehen, bevor sie auf die Website zugreifen können. Legitime Benutzer sehen möglicherweise kurz eine Überprüfungsseite. Edge Cache muss aktiviert sein, um diese Funktion zu nutzen."
msgid "Disabled"
msgstr "Deaktiviert"
msgid "Enabled until:"
msgstr "Aktiviert bis:"
msgid "Defensive Mode disabled."
msgstr "Defensiv-Modus deaktiviert."
msgid "Defensive Mode enabled for %s."
msgstr "Defensiv-Modus für %s aktiviert."
@@ -0,0 +1,119 @@
# English (United States) translation for Pressable Cache Management
# Copyright (C) 2025 Pressable
msgid ""
msgstr ""
"Project-Id-Version: Pressable Cache Management 5.2.2\n"
"POT-Creation-Date: 2025-10-15 00:00+0000\n"
"PO-Revision-Date: 2025-10-15 00:00+0000\n"
"Last-Translator: Pressable CS Team\n"
"Language-Team: English\n"
"Language: en_US\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Domain: pressable_cache_management\n"
msgid "Object Cache"
msgstr "Object Cache"
msgid "Edge Cache"
msgstr "Edge Cache"
msgid "Settings to manage the object cache."
msgstr "Settings to manage the object cache."
msgid "These settings enable you to manage the object cache."
msgstr "These settings enable you to manage the object cache."
msgid "Flush Cache for all Pages"
msgstr "Flush Cache for all Pages"
msgid "Object Cache Flushed Successfully."
msgstr "Object Cache Flushed Successfully."
msgid "Automated Rules"
msgstr "Automated Rules"
msgid "Flush Cache on Plugin/Theme Update"
msgstr "Flush Cache on Plugin/Theme Update"
msgid "Flush cache automatically on plugin & theme update."
msgstr "Flush cache automatically on plugin & theme update."
msgid "Flush Cache on Post/Page Edit"
msgstr "Flush Cache on Post/Page Edit"
msgid "Flush cache automatically when published pages are edited."
msgstr "Flush cache automatically when published pages are edited."
msgid "Flush Cache on Comment Delete"
msgstr "Flush Cache on Comment Delete"
msgid "Flush cache automatically when comments are deleted."
msgstr "Flush cache automatically when comments are deleted."
msgid "Batcache & Page Rules"
msgstr "Batcache & Page Rules"
msgid "Extend Batcache (by 24 hrs)"
msgstr "Extend Batcache (by 24 hrs)"
msgid "Flush Batcache to Individual Pages"
msgstr "Flush Batcache to Individual Pages"
msgid "Flush cache automatically when published pages/posts are deleted."
msgstr "Flush cache automatically when published pages/posts are deleted."
msgid "Flush Batcache for WooCommerce product pages"
msgstr "Flush Batcache for WooCommerce product pages"
msgid "Exclude Pages"
msgstr "Exclude Pages"
msgid "Cache Exclusions"
msgstr "Cache Exclusions"
msgid "Save Settings"
msgstr "Save Settings"
msgid "Batcache Active"
msgstr "Batcache Active"
msgid "Batcache Broken"
msgstr "Batcache Broken"
msgid "Enable Edge Cache"
msgstr "Enable Edge Cache"
msgid "Disable Edge Cache"
msgstr "Disable Edge Cache"
msgid "Purge Edge Cache"
msgstr "Purge Edge Cache"
msgid "Edge Cache Enabled!"
msgstr "Edge Cache Enabled!"
msgid "Edge Cache provides performance improvements, particularly for Time to First Byte (TTFB), by serving page cache from the nearest server to your website visitors."
msgstr "Edge Cache provides performance improvements, particularly for Time to First Byte (TTFB), by serving page cache from the nearest server to your website visitors."
msgid "Learn more about Edge Cache."
msgstr "Learn more about Edge Cache."
msgid "Edge Cache Deactivated."
msgstr "Edge Cache Deactivated."
msgid "Edge Cache purged successfully."
msgstr "Edge Cache purged successfully."
msgid "Edge Cache purge failed. Please try again."
msgstr "Edge Cache purge failed. Please try again."
msgid "Show Pressable Branding"
msgstr "Show Pressable Branding"
msgid "Hide Pressable Branding"
msgstr "Hide Pressable Branding"
msgid "This plugin is not supported on this platform."
msgstr "This plugin is not supported on this platform."
@@ -0,0 +1,336 @@
# Pressable Cache Management
msgid ""
msgstr ""
"Project-Id-Version: pressable-cache-management\n"
"PO-Revision-Date: 2026-03-05 00:00+0000\n"
"Language: es_ES\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
msgid "&#10003;&nbsp; Save Settings"
msgstr "&#10003;&nbsp; Guardar configuración"
msgid "Automated Rules"
msgstr "Reglas automáticas"
msgid "Batcache & Page Rules"
msgstr "Batcache y reglas de página"
msgid "Batcache Active"
msgstr "Batcache activo"
msgid "Batcache Broken"
msgstr "Batcache roto"
msgid "Cache Control Management"
msgstr "Gestión de control de caché"
msgid "Cache Exclusions"
msgstr "Exclusiones de caché"
msgid "Cache Management by"
msgstr "Gestión de caché por"
msgid "Cache settings updated."
msgstr "Configuración de caché actualizada."
msgid "Cloudflare Detected"
msgstr "Cloudflare detectado"
msgid "Disable Edge Cache"
msgstr "Desactivar Edge Cache"
msgid "Edge Cache Deactivated."
msgstr "Edge Cache desactivado."
msgid "Edge Cache Enabled!"
msgstr "¡Edge Cache activado!"
msgid "Edge Cache is disabled on the server. Enable Edge Cache."
msgstr "Edge Cache está desactivado en el servidor. Active Edge Cache."
msgid "Edge Cache provides performance improvements, particularly for Time to First Byte (TTFB), by serving page cache from the nearest server to your website visitors."
msgstr "Edge Cache mejora el rendimiento, especialmente el Tiempo hasta el Primer Byte (TTFB), sirviendo el caché desde el servidor más cercano a sus visitantes."
msgid "Edge Cache purge failed. Please try again."
msgstr "Error al purgar Edge Cache. Por favor, inténtelo de nuevo."
msgid "Edge Cache purged successfully."
msgstr "Edge Cache purgado correctamente."
msgid "Edge Cache was disabled and could not be auto-enabled. Purge aborted."
msgstr "Edge Cache estaba desactivado y no se pudo activar automáticamente. Purga cancelada."
msgid "Edge Cache was disabled on the server. It has been automatically enabled and purged successfully."
msgstr "Edge Cache estaba desactivado. Se ha activado y purgado automáticamente."
msgid "Enable Edge Cache"
msgstr "Activar Edge Cache"
msgid "Enter single URL (e.g., /pagename/)."
msgstr "Introduzca una URL (ej. /nombre-pagina/)."
msgid "Error: Edge Cache Plugin is not active."
msgstr "Error: El plugin de Edge Cache no está activo."
msgid "Error: Edge Cache dependency is missing."
msgstr "Error: Falta la dependencia de Edge Cache."
msgid "Exclude Pages"
msgstr "Excluir páginas"
msgid "Extend Batcache (by 24 hrs)"
msgstr "Extender Batcache (24 horas)"
msgid "Extend Batcache storage time by 24 hours."
msgstr "Extender el tiempo de almacenamiento de Batcache 24 horas."
msgid "Extending Batcache for 24 hours — see "
msgstr "Extendiendo Batcache por 24 horas — ver "
msgid "Flush Cache for all Pages"
msgstr "Vaciar caché de todas las páginas"
msgid "Flush Batcache for Individual Pages"
msgstr "Limpiar Batcache para páginas individuales"
msgid "Flush Batcache for WooCommerce product pages"
msgstr "Limpiar Batcache para productos WooCommerce"
msgid "Flush Batcache for WooCommerce product pages."
msgstr "Limpiar Batcache para productos WooCommerce."
msgid "Flush Batcache for individual pages from page preview toolbar."
msgstr "Limpiar Batcache desde la barra de vista previa."
msgid "Flush Cache on Comment Delete"
msgstr "Limpiar caché al eliminar comentario"
msgid "Flush Cache on Page Delete"
msgstr "Limpiar caché al eliminar página"
msgid "Flush Cache on Plugin/Theme Update"
msgstr "Limpiar caché al actualizar plugin/tema"
msgid "Flush Cache on Post/Page Edit"
msgstr "Limpiar caché al editar entrada/página"
msgid "Flush Object Cache"
msgstr "Limpiar caché de objetos"
msgid "Flush cache automatically on plugin & theme update."
msgstr "Limpiar caché automáticamente al actualizar plugins y temas."
msgid "Flush cache automatically when comments are deleted."
msgstr "Limpiar caché automáticamente al eliminar comentarios."
msgid "Flush cache automatically when page/post/post_types are updated."
msgstr "Limpiar caché automáticamente al actualizar páginas o entradas."
msgid "Flush cache automatically when published pages/posts are deleted."
msgstr "Limpiar caché automáticamente al eliminar páginas publicadas."
msgid "Flushes Batcache for the specific page when it is deleted."
msgstr "Limpia Batcache de la página específica al eliminarla."
msgid "Global Controls"
msgstr "Controles globales"
msgid "Hide Pressable Branding"
msgstr "Ocultar marca Pressable"
msgid "Hide or Show Plugin Branding"
msgstr "Ocultar o mostrar la marca del plugin"
msgid "Hide or show plugin branding"
msgstr "Ocultar o mostrar la marca del plugin"
msgid "LAST FLUSHED"
msgstr "ÚLTIMA LIMPIEZA"
msgid "Last flushed at:"
msgstr "Última limpieza:"
msgid "Manage Edge Cache settings below."
msgstr "Gestione la configuración del Edge Cache a continuación."
msgid "Modifying Batcache Times."
msgstr "Modificar tiempos de Batcache."
msgid "Object Cache Flushed Successfully."
msgstr "Caché de objetos limpiado correctamente."
msgid "Page URL:"
msgstr "URL de la página:"
msgid "Purge Edge Cache"
msgstr "Purgar Edge Cache"
msgid "Purging cache will temporarily slow down your site for all visitors while the cache rebuilds."
msgstr "Purgar el caché ralentizará temporalmente su sitio mientras se reconstruye."
msgid "Settings to manage the object cache."
msgstr "Configuración para gestionar el caché de objetos."
msgid "Show Pressable Branding"
msgstr "Mostrar marca Pressable"
msgid "Show or Hide Plugin Branding"
msgstr "Mostrar u ocultar la marca del plugin"
msgid "Something went wrong trying to communicate with the Edge Cache system. Try again."
msgstr "Algo salió mal al comunicarse con Edge Cache. Inténtelo de nuevo."
msgid "These settings enable you to manage Edge Cache settings."
msgstr "Estos ajustes permiten gestionar la configuración del Edge Cache."
msgid "These settings enable you to manage the object cache."
msgstr "Estos ajustes permiten gestionar el caché de objetos."
msgid "This setting allows you to show or hide the plugin branding."
msgstr "Este ajuste permite mostrar u ocultar la marca del plugin."
msgid "To exclude a single page use"
msgstr "Para excluir una página use"
msgid "for multiple pages separate with comma, e.g."
msgstr "para varias páginas separe con coma, p.ej."
msgid "Manage Edge Cache Settings"
msgstr "Gestionar la configuración del Edge Cache"
msgid "Enable or disable the edge cache for this site."
msgstr "Habilitar o deshabilitar el Edge Cache para este sitio."
msgid "SINGLE PAGE LAST FLUSHED"
msgstr "ÚLTIMA LIMPIEZA DE PÁGINA"
msgid "SINGLE PAGE URL"
msgstr "URL DE PÁGINA INDIVIDUAL"
msgid "Failed to retrieve status."
msgstr "No se pudo obtener el estado."
msgid "Could not connect to server."
msgstr "No se pudo conectar al servidor."
msgid "Use the refresh button to manually check your cache status. If the cache status remains broken for more than 4 minutes after two visits are recorded on your site, it is likely that caching is failing due to cookie interference from your plugin, theme or custom code."
msgstr "Usa el botón de actualización para verificar manualmente el estado de tu caché. Si el estado del caché permanece roto durante más de 4 minutos después de que se registren dos visitas en tu sitio, es probable que el almacenamiento en caché esté fallando debido a interferencias de cookies de tu plugin, tema o código personalizado."
msgid "Flush Batcache for WooCommerce Product Pages — Enabled"
msgstr "Vaciar Batcache para páginas de productos WooCommerce — Activado"
msgid "Automatically flush individual pages, including product pages updated via the WooCommerce API."
msgstr "Vaciar automáticamente las páginas individuales, incluidas las páginas de productos actualizadas a través de la API de WooCommerce."
msgid "You can Flush Cache for Individual page or post from page preview."
msgstr "Puede vaciar la caché de una página o publicación individual desde la vista previa de la página."
msgid "Flush Object & Edge Cache"
msgstr "Vaciar caché de objetos y Edge"
msgid "Cache Settings"
msgstr "Configuración de caché"
msgid "Cache Management"
msgstr "Gestión de caché"
msgid "Cache Control"
msgstr "Control de caché"
msgid "CURRENT CACHE MAX-AGE"
msgstr "MAX-AGE DE CACHÉ ACTUAL"
msgid "Checking…"
msgstr "Comprobando…"
msgid "Object Cache Flushed successfully."
msgstr "Caché de objetos vaciada correctamente."
msgid "Edge Cache Purged successfully."
msgstr "Edge Cache purgado correctamente."
msgid "Error: Edge Cache Plugin is not active. Purge aborted."
msgstr "Error: El plugin Edge Cache no está activo. Purga cancelada."
msgid "Edge Cache purge failed (possibly disabled or rate-limited)."
msgstr "Error al purgar Edge Cache."
msgid "Edge Cache Plugin not found; skipping Edge Cache purge."
msgstr "Plugin Edge Cache no encontrado."
msgid "Edge Cache Defensive Mode"
msgstr "Modo Defensivo de Edge Cache"
msgid "Adds an extra layer of protection against spam bots and DDoS attacks. When enabled, visitors' browsers must complete a small challenge before accessing the site. Legitimate users may see a brief challenge page. Edge Cache must be enabled to use this feature."
msgstr "Añade una capa adicional de protección contra bots de spam y ataques DDoS. Cuando está activado, los navegadores de los visitantes deben completar un pequeño desafío antes de acceder al sitio. Los usuarios legítimos pueden ver una breve página de desafío. Edge Cache debe estar activado para usar esta función."
msgid "Checking status\u2026"
msgstr ""
msgid "Enable Defensive Mode"
msgstr ""
msgid "Disable Defensive Mode"
msgstr ""
msgid "Enabled"
msgstr ""
msgid "at"
msgstr ""
msgid "Enabled until"
msgstr "Activo hasta"
msgid "Disabled"
msgstr "Desactivado"
msgid "Disabled \u2014 Edge Cache must be enabled first."
msgstr ""
msgid "Unable to retrieve Defensive Mode status."
msgstr ""
msgid "Could not retrieve Defensive Mode status."
msgstr ""
msgid "Defensive Mode enabled for %s."
msgstr ""
msgid "Defensive Mode disabled."
msgstr "Modo defensivo desactivado."
msgid "Error: Edge Cache Plugin is not active."
msgstr ""
msgid "Unknown error enabling Defensive Mode."
msgstr ""
msgid "Unknown error disabling Defensive Mode."
msgstr ""
msgid "Could not retrieve Defensive Mode status from server."
msgstr ""
msgid "Edge Cache Defensive Mode"
msgstr "Modo Defensivo de Edge Cache"
msgid "Adds an extra layer of protection against spam bots and DDoS attacks. When enabled, visitors' browsers must complete a small challenge before accessing the site. Legitimate users may see a brief challenge page. Edge Cache must be enabled to use this feature."
msgstr "Añade una capa adicional de protección contra bots de spam y ataques DDoS. Cuando está activado, los navegadores de los visitantes deben completar un pequeño desafío antes de acceder al sitio. Los usuarios legítimos pueden ver una breve página de verificación. Edge Cache debe estar activado para usar esta función."
msgid "Disabled"
msgstr "Desactivado"
msgid "Enabled until:"
msgstr "Activado hasta:"
msgid "Defensive Mode disabled."
msgstr "Modo Defensivo desactivado."
msgid "Defensive Mode enabled for %s."
msgstr "Modo Defensivo activado por %s."
@@ -0,0 +1,336 @@
# Pressable Cache Management
msgid ""
msgstr ""
"Project-Id-Version: pressable-cache-management\n"
"PO-Revision-Date: 2026-03-05 00:00+0000\n"
"Language: fr_FR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
msgid "&#10003;&nbsp; Save Settings"
msgstr "&#10003;&nbsp; Enregistrer les paramètres"
msgid "Automated Rules"
msgstr "Règles automatisées"
msgid "Batcache & Page Rules"
msgstr "Batcache et règles de page"
msgid "Batcache Active"
msgstr "Batcache actif"
msgid "Batcache Broken"
msgstr "Batcache défaillant"
msgid "Cache Control Management"
msgstr "Gestion du contrôle du cache"
msgid "Cache Exclusions"
msgstr "Exclusions du cache"
msgid "Cache Management by"
msgstr "Gestion du cache par"
msgid "Cache settings updated."
msgstr "Paramètres du cache mis à jour."
msgid "Cloudflare Detected"
msgstr "Cloudflare détecté"
msgid "Disable Edge Cache"
msgstr "Désactiver le cache de périphérie"
msgid "Edge Cache Deactivated."
msgstr "Cache de périphérie désactivé."
msgid "Edge Cache Enabled!"
msgstr "Cache de périphérie activé !"
msgid "Edge Cache is disabled on the server. Enable Edge Cache."
msgstr "Le cache de périphérie est désactivé sur le serveur. Activez-le."
msgid "Edge Cache provides performance improvements, particularly for Time to First Byte (TTFB), by serving page cache from the nearest server to your website visitors."
msgstr "Le cache de périphérie améliore les performances, notamment le Temps jusqu'au Premier Octet (TTFB), en servant le cache depuis le serveur le plus proche de vos visiteurs."
msgid "Edge Cache purge failed. Please try again."
msgstr "Échec de la purge du cache de périphérie. Veuillez réessayer."
msgid "Edge Cache purged successfully."
msgstr "Cache de périphérie purgé avec succès."
msgid "Edge Cache was disabled and could not be auto-enabled. Purge aborted."
msgstr "Le cache de périphérie était désactivé et n'a pas pu être activé automatiquement. Purge annulée."
msgid "Edge Cache was disabled on the server. It has been automatically enabled and purged successfully."
msgstr "Le cache de périphérie était désactivé. Il a été activé et purgé automatiquement."
msgid "Enable Edge Cache"
msgstr "Activer le cache de périphérie"
msgid "Enter single URL (e.g., /pagename/)."
msgstr "Entrez une URL (ex. /nom-de-page/)."
msgid "Error: Edge Cache Plugin is not active."
msgstr "Erreur : le plugin de cache de périphérie n'est pas actif."
msgid "Error: Edge Cache dependency is missing."
msgstr "Erreur : la dépendance du cache de périphérie est manquante."
msgid "Exclude Pages"
msgstr "Exclure les pages"
msgid "Extend Batcache (by 24 hrs)"
msgstr "Étendre Batcache (de 24 heures)"
msgid "Extend Batcache storage time by 24 hours."
msgstr "Étendre la durée de stockage de Batcache de 24 heures."
msgid "Extending Batcache for 24 hours — see "
msgstr "Extension de Batcache pour 24 heures — voir "
msgid "Flush Cache for all Pages"
msgstr "Vider le cache pour toutes les pages"
msgid "Flush Batcache for Individual Pages"
msgstr "Vider Batcache pour les pages individuelles"
msgid "Flush Batcache for WooCommerce product pages"
msgstr "Vider Batcache pour les pages produits WooCommerce"
msgid "Flush Batcache for WooCommerce product pages."
msgstr "Vider Batcache pour les pages produits WooCommerce."
msgid "Flush Batcache for individual pages from page preview toolbar."
msgstr "Vider Batcache depuis la barre d'aperçu."
msgid "Flush Cache on Comment Delete"
msgstr "Vider le cache lors de la suppression d'un commentaire"
msgid "Flush Cache on Page Delete"
msgstr "Vider le cache lors de la suppression d'une page"
msgid "Flush Cache on Plugin/Theme Update"
msgstr "Vider le cache lors de la mise à jour d'un plugin/thème"
msgid "Flush Cache on Post/Page Edit"
msgstr "Vider le cache lors d'une modification"
msgid "Flush Object Cache"
msgstr "Vider le cache d'objets"
msgid "Flush cache automatically on plugin & theme update."
msgstr "Vider automatiquement le cache lors des mises à jour."
msgid "Flush cache automatically when comments are deleted."
msgstr "Vider automatiquement le cache lors de la suppression de commentaires."
msgid "Flush cache automatically when page/post/post_types are updated."
msgstr "Vider automatiquement le cache lors de la mise à jour des pages."
msgid "Flush cache automatically when published pages/posts are deleted."
msgstr "Vider automatiquement le cache lors de la suppression."
msgid "Flushes Batcache for the specific page when it is deleted."
msgstr "Vide Batcache de la page spécifique lors de sa suppression."
msgid "Global Controls"
msgstr "Contrôles globaux"
msgid "Hide Pressable Branding"
msgstr "Masquer la marque Pressable"
msgid "Hide or Show Plugin Branding"
msgstr "Masquer ou afficher la marque du plugin"
msgid "Hide or show plugin branding"
msgstr "Masquer ou afficher la marque du plugin"
msgid "LAST FLUSHED"
msgstr "DERNIER VIDAGE"
msgid "Last flushed at:"
msgstr "Dernier vidage :"
msgid "Manage Edge Cache settings below."
msgstr "Gérez les paramètres du cache de périphérie ci-dessous."
msgid "Modifying Batcache Times."
msgstr "Modification des durées Batcache."
msgid "Object Cache Flushed Successfully."
msgstr "Cache d'objets vidé avec succès."
msgid "Page URL:"
msgstr "URL de la page :"
msgid "Purge Edge Cache"
msgstr "Purger le cache de périphérie"
msgid "Purging cache will temporarily slow down your site for all visitors while the cache rebuilds."
msgstr "La purge du cache ralentira temporairement votre site pendant la reconstruction."
msgid "Settings to manage the object cache."
msgstr "Paramètres pour gérer le cache d'objets."
msgid "Show Pressable Branding"
msgstr "Afficher la marque Pressable"
msgid "Show or Hide Plugin Branding"
msgstr "Afficher ou masquer la marque du plugin"
msgid "Something went wrong trying to communicate with the Edge Cache system. Try again."
msgstr "Une erreur s'est produite avec le cache de périphérie. Réessayez."
msgid "These settings enable you to manage Edge Cache settings."
msgstr "Ces paramètres permettent de gérer les réglages du cache de périphérie."
msgid "These settings enable you to manage the object cache."
msgstr "Ces paramètres permettent de gérer le cache d'objets."
msgid "This setting allows you to show or hide the plugin branding."
msgstr "Ce paramètre permet d'afficher ou de masquer la marque du plugin."
msgid "To exclude a single page use"
msgstr "Pour exclure une page, utilisez"
msgid "for multiple pages separate with comma, e.g."
msgstr "pour plusieurs pages, séparez par une virgule, ex."
msgid "Manage Edge Cache Settings"
msgstr "Gérer les paramètres du cache de périphérie"
msgid "Enable or disable the edge cache for this site."
msgstr "Activer ou désactiver le cache Edge pour ce site."
msgid "SINGLE PAGE LAST FLUSHED"
msgstr "DERNIÈRE PURGE PAGE UNIQUE"
msgid "SINGLE PAGE URL"
msgstr "URL DE PAGE UNIQUE"
msgid "Failed to retrieve status."
msgstr "Impossible de récupérer le statut."
msgid "Could not connect to server."
msgstr "Impossible de se connecter au serveur."
msgid "Use the refresh button to manually check your cache status. If the cache status remains broken for more than 4 minutes after two visits are recorded on your site, it is likely that caching is failing due to cookie interference from your plugin, theme or custom code."
msgstr "Utilisez le bouton d'actualisation pour vérifier manuellement l'état de votre cache. Si l'état du cache reste cassé pendant plus de 4 minutes après deux visites enregistrées sur votre site, il est probable que la mise en cache échoue en raison d'interférences de cookies provenant de votre plugin, thème ou code personnalisé."
msgid "Flush Batcache for WooCommerce Product Pages — Enabled"
msgstr "Vider le Batcache pour les pages produits WooCommerce — Activé"
msgid "Automatically flush individual pages, including product pages updated via the WooCommerce API."
msgstr "Vider automatiquement les pages individuelles, y compris les pages produits mises à jour via l'API WooCommerce."
msgid "You can Flush Cache for Individual page or post from page preview."
msgstr "Vous pouvez vider le cache d'une page ou d'un article individuel depuis l'aperçu de la page."
msgid "Flush Object & Edge Cache"
msgstr "Vider le cache d'objets et Edge"
msgid "Cache Settings"
msgstr "Paramètres de cache"
msgid "Cache Management"
msgstr "Gestion du cache"
msgid "Cache Control"
msgstr "Contrôle du cache"
msgid "CURRENT CACHE MAX-AGE"
msgstr "MAX-AGE DU CACHE ACTUEL"
msgid "Checking…"
msgstr "Vérification…"
msgid "Object Cache Flushed successfully."
msgstr "Cache d'objets vidé avec succès."
msgid "Edge Cache Purged successfully."
msgstr "Cache Edge purgé avec succès."
msgid "Error: Edge Cache Plugin is not active. Purge aborted."
msgstr "Erreur : Le plugin Edge Cache n'est pas actif. Purge annulée."
msgid "Edge Cache purge failed (possibly disabled or rate-limited)."
msgstr "Échec de la purge du cache Edge."
msgid "Edge Cache Plugin not found; skipping Edge Cache purge."
msgstr "Plugin Edge Cache introuvable."
msgid "Edge Cache Defensive Mode"
msgstr "Mode Défensif Edge Cache"
msgid "Adds an extra layer of protection against spam bots and DDoS attacks. When enabled, visitors' browsers must complete a small challenge before accessing the site. Legitimate users may see a brief challenge page. Edge Cache must be enabled to use this feature."
msgstr "Ajoute une couche de protection supplémentaire contre les robots spam et les attaques DDoS. Lorsqu'il est activé, les navigateurs des visiteurs doivent relever un petit défi avant d'accéder au site. Les utilisateurs légitimes peuvent voir brièvement une page de défi. Edge Cache doit être activé pour utiliser cette fonctionnalité."
msgid "Checking status\u2026"
msgstr ""
msgid "Enable Defensive Mode"
msgstr ""
msgid "Disable Defensive Mode"
msgstr ""
msgid "Enabled"
msgstr ""
msgid "at"
msgstr ""
msgid "Enabled until"
msgstr "Actif jusqu'au"
msgid "Disabled"
msgstr "Désactivé"
msgid "Disabled \u2014 Edge Cache must be enabled first."
msgstr ""
msgid "Unable to retrieve Defensive Mode status."
msgstr ""
msgid "Could not retrieve Defensive Mode status."
msgstr ""
msgid "Defensive Mode enabled for %s."
msgstr ""
msgid "Defensive Mode disabled."
msgstr "Mode défensif désactivé."
msgid "Error: Edge Cache Plugin is not active."
msgstr ""
msgid "Unknown error enabling Defensive Mode."
msgstr ""
msgid "Unknown error disabling Defensive Mode."
msgstr ""
msgid "Could not retrieve Defensive Mode status from server."
msgstr ""
msgid "Edge Cache Defensive Mode"
msgstr "Mode Défensif du Edge Cache"
msgid "Adds an extra layer of protection against spam bots and DDoS attacks. When enabled, visitors' browsers must complete a small challenge before accessing the site. Legitimate users may see a brief challenge page. Edge Cache must be enabled to use this feature."
msgstr "Ajoute une couche de protection supplémentaire contre les robots spam et les attaques DDoS. Lorsqu'il est activé, les navigateurs des visiteurs doivent relever un petit défi avant d'accéder au site. Les utilisateurs légitimes peuvent voir une brève page de vérification. Edge Cache doit être activé pour utiliser cette fonctionnalité."
msgid "Disabled"
msgstr "Désactivé"
msgid "Enabled until:"
msgstr "Activé jusqu'au :"
msgid "Defensive Mode disabled."
msgstr "Mode Défensif désactivé."
msgid "Defensive Mode enabled for %s."
msgstr "Mode Défensif activé pour %s."

Some files were not shown because too many files have changed in this diff Show More