[ slug => [ label, dashicon, description ] ]. */
public static function nav() {
return array(
'Monitor' => array(
'activity' => array( 'Dashboard', 'chart-area', 'Live progress, push history and the activity log.' ),
'diagnostics' => array( 'Health Check', 'heart', 'Everything your server needs for exporting and pushing.' ),
),
'Configure' => array(
'general' => array( 'Export', 'admin-page', 'How pages are found and how links are rewritten.' ),
'deploy' => array( 'Destination', 'upload', 'Where your static site is published.' ),
'media' => array( 'Media Offload', 'format-gallery', 'Serve your media library from Cloudflare R2.' ),
'forms' => array( 'Forms', 'feedback', 'What happens to forms on the static site.' ),
'search' => array( 'Site Search', 'search', 'Search that works without WordPress.' ),
'llms' => array( 'AI & LLMs', 'format-chat', 'Help AI tools understand your site with llms.txt.' ),
'related' => array( 'Related Posts', 'admin-links', 'Related posts built into every page at export time.' ),
'optimize' => array( 'HTML Clean-up', 'editor-code', 'Remove markup a static site doesn\'t need.' ),
'hidewp' => array( 'Stealth', 'shield', 'Hide the signs that the site runs on WordPress.' ),
),
'System' => array(
'integrations' => array( 'Plugins', 'admin-plugins', 'How other plugins are handled.' ),
'workflow' => array( 'Automation', 'controls-repeat', 'Automatic pushes, schedules and alerts.' ),
'utilities' => array( 'Tools', 'admin-tools', 'Backups, downloads and housekeeping.' ),
'debug' => array( 'Advanced', 'dashboard', 'Performance tuning and internals.' ),
),
);
}
public static function init() {
add_action( 'admin_menu', array( __CLASS__, 'menu' ) );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'assets' ) );
add_action( 'wp_ajax_cfsp_status', array( __CLASS__, 'ajax_status' ) );
add_action( 'wp_ajax_cfsp_action', array( __CLASS__, 'ajax_action' ) );
add_action( 'admin_post_cfsp_zip', array( __CLASS__, 'download_zip' ) );
add_action( 'admin_post_cfsp_bar_push', array( __CLASS__, 'bar_push' ) );
add_filter( 'plugin_action_links_' . plugin_basename( CFSP_FILE ), array( __CLASS__, 'action_links' ) );
add_filter( 'plugin_row_meta', array( __CLASS__, 'row_meta' ), 10, 2 );
}
/** The toolbar menu and its live status: in wp-admin and on the front end (for administrators). */
public static function init_toolbar() {
add_action( 'admin_bar_menu', array( __CLASS__, 'admin_bar' ), 100 );
add_filter( 'heartbeat_received', array( __CLASS__, 'heartbeat' ), 10, 2 );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'heartbeat_script' ) );
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'heartbeat_script' ) );
}
public static function menu() {
add_menu_page( 'Static Push', 'Static Push', 'manage_options', self::SLUG, array( __CLASS__, 'render' ), CFSP_UI::menu_icon(), 81 );
}
/** "Donate" link under the plugin description on the Plugins screen. */
public static function row_meta( $links, $file ) {
if ( plugin_basename( CFSP_FILE ) === $file ) {
// "Version | By Quintaphon | Documentation": the author name already links to the plugin site,
// so WordPress's extra "Visit plugin site" link is dropped.
$links = array_values(
array_filter(
$links,
function ( $link ) {
// The "Visit plugin site" item is a bare link to the Plugin URI (any admin language);
// the author item starts with "By" and is kept.
return ! ( 0 === strpos( ltrim( $link ), 'Documentation';
}
return $links;
}
public static function action_links( $links ) {
array_unshift( $links, 'Settings' );
return $links;
}
/** Admin-bar text for the current state ('' when idle). */
public static function bar_title() {
$job = CFSP_Job::get();
if ( $job && CFSP_Job::is_active( $job ) ) {
return 'Static: pushing…';
}
if ( self::has_pending() ) {
return 'Static: changes pending';
}
return '';
}
/** Heartbeat: keep the admin-bar item current without a page reload. */
public static function heartbeat( $response, $data ) {
if ( isset( $data['cfsp_bar'] ) && current_user_can( 'manage_options' ) ) {
$response['cfsp_bar'] = self::bar_title();
}
return $response;
}
/** Tiny script on admin pages: update or remove the admin-bar item on each Heartbeat tick. */
public static function heartbeat_script() {
if ( ! current_user_can( 'manage_options' ) || ! is_admin_bar_showing() ) {
return;
}
wp_enqueue_script( 'heartbeat' );
wp_add_inline_script(
'heartbeat',
"jQuery( document ).on( 'heartbeat-send', function ( e, data ) { data.cfsp_bar = 1; } ).on( 'heartbeat-tick', function ( e, data ) {" .
" if ( ! data || typeof data.cfsp_bar === 'undefined' ) { return; }" .
" var node = document.getElementById( 'wp-admin-bar-cfsp-status' ); if ( ! node ) { return; }" .
" var label = node.querySelector( '.ab-label' ); if ( label ) { label.textContent = data.cfsp_bar || 'Static Push'; } } );"
);
}
public static function admin_bar( $bar ) {
if ( ! current_user_can( 'manage_options' ) || ! is_admin_bar_showing() ) {
return;
}
$title = self::bar_title();
$page = admin_url( 'admin.php?page=' . self::SLUG );
$bar->add_node(
array(
'id' => 'cfsp-status',
'title' => '' . esc_html( $title ? $title : 'Static Push' ) . '',
'href' => $page . '#/activity',
)
);
// Same options as the Push button on the plugin screen.
$run = function ( $mode ) {
return wp_nonce_url( admin_url( 'admin-post.php?action=cfsp_bar_push&mode=' . $mode ), 'cfsp_bar_push' );
};
// On the front end, "Specific pages" opens with the page being viewed already filled in.
$here = '';
if ( ! is_admin() && isset( $_SERVER['REQUEST_URI'] ) ) {
$here = (string) wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH );
}
$items = array(
'push_pending' => array( 'Pending changes', $run( 'push_pending' ), array() ),
'pages' => array( 'Specific pages', add_query_arg( array( 'cfsp_push' => 'pages', 'cfsp_urls' => rawurlencode( $here ) ), $page ) . '#/activity', array() ),
'full' => array( 'Full site', $run( 'full' ), array( 'onclick' => "return confirm('Push the full site? Every page is exported again and the whole site is pushed. On large sites this can take a while.');" ) ),
'deploy' => array( 'Current files', $run( 'deploy' ), array() ),
);
foreach ( $items as $id => $item ) {
$bar->add_node(
array(
'parent' => 'cfsp-status',
'id' => 'cfsp-push-' . str_replace( '_', '-', $id ),
'title' => esc_html( $item[0] ),
'href' => $item[1],
'meta' => $item[2],
)
);
}
}
public static function assets( $hook ) {
if ( 'toplevel_page_' . self::SLUG !== $hook ) {
return;
}
// Version by file modification time so browsers never keep an outdated copy after an update.
$ver = function ( $file ) {
$path = CFSP_DIR . 'assets/' . $file;
return CFSP_VERSION . '.' . ( is_file( $path ) ? filemtime( $path ) : '0' );
};
wp_enqueue_style( 'cfsp-admin', CFSP_URL . 'assets/admin.css', array( 'dashicons' ), $ver( 'admin.css' ) );
wp_enqueue_script( 'cfsp-admin', CFSP_URL . 'assets/admin.js', array(), $ver( 'admin.js' ), true );
// Result of a push started from the toolbar menu, shown once as a notification.
$notice = get_transient( 'cfsp_bar_notice_' . get_current_user_id() );
if ( $notice ) {
delete_transient( 'cfsp_bar_notice_' . get_current_user_id() );
}
wp_localize_script(
'cfsp-admin',
'CFSP',
array(
'ajax' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'cfsp' ),
'zipUrl' => wp_nonce_url( admin_url( 'admin-post.php?action=cfsp_zip' ), 'cfsp_zip' ),
'sections' => call_user_func_array( 'array_merge', array_values( self::nav() ) ),
'notice' => $notice ? $notice : null,
)
);
}
/* ------------------------------------------------------------------ *
* AJAX
* ------------------------------------------------------------------ */
private static function check() {
if ( ! current_user_can( 'manage_options' ) || ! check_ajax_referer( 'cfsp', 'nonce', false ) ) {
wp_send_json_error( array( 'message' => 'Permission denied.' ), 403 );
}
}
private static function param( $name, $default = '' ) {
return isset( $_POST[ $name ] ) ? wp_unslash( $_POST[ $name ] ) : $default; // phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput -- checked in check(); sanitized by callers.
}
private static function send( $result, $success_message = '' ) {
if ( is_wp_error( $result ) ) {
wp_send_json_error( array( 'message' => $result->get_error_message() ) );
}
wp_send_json_success( is_array( $result ) ? $result : array( 'message' => $success_message ) );
}
public static function ajax_status() {
self::check();
$job = CFSP_Job::get();
// Keep things moving while the admin is watching, in case loopbacks are blocked.
if ( $job && CFSP_Job::is_active( $job ) ) {
$idle = time() - (int) $job['updated'];
if ( $idle > 60 ) {
CFSP_Job::run_batch( false );
$job = CFSP_Job::get();
} elseif ( $idle > 10 ) {
CFSP_Job::spawn();
}
}
$pending = CFSP_Job::get_pending();
$last = get_option( CFSP_Job::LAST_OPTION );
$next = wp_next_scheduled( 'cfsp_run_pending' );
wp_send_json_success(
array(
'job' => $job ? array(
'id' => $job['id'],
'type' => $job['type'],
'phase' => $job['phase'],
'active' => CFSP_Job::is_active( $job ),
'processed' => $job['processed'],
'total' => $job['total'],
'errors' => $job['errors'],
'upload_total' => $job['upload_total'] ?? null,
'upload_remaining' => $job['upload_remaining'] ?? null,
'message' => $job['message'],
'reason' => $job['reason'] ?? '',
'started' => self::ago( $job['started'] ),
'waiting' => ! empty( $job['wait_until'] ) && $job['wait_until'] > time() ? $job['wait_until'] - time() : 0,
) : null,
'pending' => array(
'count' => count( $pending['urls'] ) + count( $pending['posts'] ) + count( $pending['deletes'] ),
'full' => (bool) $pending['full'],
'reasons' => $pending['reasons'],
'scheduled' => $next ? max( 0, $next - time() ) : null,
),
'last' => is_array( $last ) ? array( 'ago' => self::ago( $last['time'] ), 'url' => $last['url'] ) : null,
'media' => self::media_status(),
'history' => array_map(
function ( $h ) {
$h['ago'] = self::ago( $h['time'] );
return $h;
},
array_reverse( CFSP_Job::history() )
),
'log' => array_map(
function ( $row ) {
return array(
'time' => wp_date( 'M j H:i:s', $row['t'] ),
'level' => $row['l'],
'msg' => $row['m'],
);
},
array_reverse( CFSP_Logger::get( 150 ) )
),
)
);
}
/**
* Start one of the Push menu jobs (shared by the Push button and the toolbar menu).
*
* @param string $mode push_pending, push_urls, full or deploy.
* @param string $urls Addresses for push_urls, one per line.
* @return array|WP_Error [ 'message' => string ] on success.
*/
public static function start_push( $mode, $urls = '' ) {
switch ( $mode ) {
case 'full':
$started = CFSP_Job::start_full( 'Manual full export' );
return array( 'message' => $started ? 'Full export started.' : 'A job is running. The full export is queued to run next.' );
case 'deploy':
if ( 'local' === CFSP_Settings::get( 'target' ) ) {
return new WP_Error( 'cfsp_local', 'The destination is Local / ZIP. Download the ZIP from Tools instead.' );
}
if ( ! CFSP_Settings::is_configured() ) {
return new WP_Error( 'cfsp_setup', 'Finish the Destination settings first.' );
}
$started = CFSP_Job::start_deploy_only();
return array( 'message' => $started ? 'Pushing current files.' : 'A job is already running.' );
case 'push_urls':
if ( 'local' !== CFSP_Settings::get( 'target' ) && ! CFSP_Settings::is_configured() ) {
return new WP_Error( 'cfsp_setup', 'Finish the Destination settings first.' );
}
$queued = CFSP_Job::start_urls( preg_split( '/\r\n|\r|\n/', $urls ) );
if ( is_wp_error( $queued ) ) {
return $queued;
}
return array( 'message' => sprintf( 1 === $queued ? 'Pushing %d page.' : 'Pushing %d pages.', $queued ) );
case 'push_pending':
if ( ! self::has_pending() ) {
return new WP_Error( 'cfsp_none', 'There are no pending changes.' );
}
wp_clear_scheduled_hook( 'cfsp_run_pending' );
CFSP_Job::start_from_pending();
return array( 'message' => 'Pushing pending changes.' );
}
return new WP_Error( 'cfsp_mode', 'Unknown push option.' );
}
private static function has_pending() {
$pending = CFSP_Job::get_pending();
return (bool) ( $pending['full'] || $pending['posts'] || $pending['urls'] || $pending['deletes'] );
}
/**
* Toolbar menu: start a push, then open the Activity page, where the result shows as a notification.
*/
public static function bar_push() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Permission denied.', 403 );
}
check_admin_referer( 'cfsp_bar_push' );
$mode = isset( $_GET['mode'] ) ? sanitize_key( wp_unslash( $_GET['mode'] ) ) : '';
$result = in_array( $mode, array( 'push_pending', 'full', 'deploy' ), true ) ? self::start_push( $mode ) : new WP_Error( 'cfsp_mode', 'Unknown push option.' );
set_transient(
'cfsp_bar_notice_' . get_current_user_id(),
is_wp_error( $result ) ? array( $result->get_error_message(), 'error' ) : array( $result['message'], 'ok' ),
60
);
wp_safe_redirect( admin_url( 'admin.php?page=' . self::SLUG . '#/activity' ) );
exit;
}
public static function ajax_action() {
self::check();
$action = sanitize_key( self::param( 'do' ) );
switch ( $action ) {
/* --- Jobs ----------------------------------------------------- */
case 'full':
case 'deploy':
case 'push_urls':
case 'push_pending':
self::send( self::start_push( $action, (string) self::param( 'urls' ) ) );
break;
case 'cancel':
CFSP_Job::cancel();
wp_send_json_success( array( 'message' => 'Cancelled.' ) );
break;
/* --- Settings ------------------------------------------------- */
case 'save':
$data = json_decode( (string) self::param( 'settings' ), true );
if ( ! is_array( $data ) ) {
wp_send_json_error( array( 'message' => 'Invalid settings data.' ) );
}
$saved = CFSP_Settings::update( array_intersect_key( $data, CFSP_Settings::schema() ) );
CFSP_Diagnostics::reset(); // Results depend on settings.
wp_send_json_success(
array(
'message' => 'Settings saved.',
'settings' => CFSP_Settings::for_js(),
'rebuild' => self::needs_rebuild( $data ),
)
);
break;
case 'export_settings':
$settings = CFSP_Settings::for_js();
unset( $settings['gh_token'], $settings['api_token'] );
wp_send_json_success(
array(
'filename' => 'static-push-settings-' . gmdate( 'Y-m-d' ) . '.json',
'data' => array(
'plugin' => 'static-push',
'version' => CFSP_VERSION,
'exported' => gmdate( 'c' ),
'settings' => $settings,
),
)
);
break;
case 'import_settings':
$data = json_decode( (string) self::param( 'data' ), true );
if ( ! is_array( $data ) || ! in_array( $data['plugin'] ?? '', array( 'staticpush', 'static-push', 'static-site-push', 'wp-static-push', 'wp-static-push-static-site-generator', 'static-push-static-site-generator', 'quintaphon-static-push', 'cf-static-push' ), true ) || ! is_array( $data['settings'] ?? null ) ) {
wp_send_json_error( array( 'message' => 'That file isn\'t a Static Push settings export.' ) );
}
CFSP_Settings::update( array_intersect_key( $data['settings'], CFSP_Settings::schema() ) );
CFSP_Logger::log( 'Settings imported.' );
wp_send_json_success( array( 'message' => 'Settings imported. Reloading…', 'reload' => true ) );
break;
case 'reset_settings':
delete_option( CFSP_Settings::OPTION );
CFSP_Settings::update( array() );
CFSP_Logger::log( 'Settings reset to defaults.' );
wp_send_json_success( array( 'message' => 'Settings reset. Reloading…', 'reload' => true ) );
break;
/* --- Tools ---------------------------------------------------- */
case 'diagnostics':
$diag = CFSP_Diagnostics::get( (bool) self::param( 'fresh' ) );
$diag['ago'] = self::ago( $diag['time'] );
wp_send_json_success( $diag );
break;
case 'clear_log':
CFSP_Logger::clear();
wp_send_json_success( array( 'message' => 'Log cleared.' ) );
break;
case 'clear_history':
delete_option( CFSP_Job::HISTORY_OPTION );
wp_send_json_success( array( 'message' => 'History cleared.' ) );
break;
case 'clear_export':
if ( CFSP_Job::is_active() ) {
wp_send_json_error( array( 'message' => 'Wait for the running job to finish.' ) );
}
CFSP_Exporter::empty_export_dir();
foreach ( array( 'content-types', 'hash-cache', 'gh-hash-cache', 'manifest', 'upload-queue', 'gh-deploy' ) as $state ) {
CFSP_Deployer::write_state( $state, array() );
}
delete_post_meta_by_key( CFSP_Auto_Push::META );
CFSP_Logger::log( 'Export directory cleared.' );
wp_send_json_success( array( 'message' => 'Export directory cleared. Run a full export before pushing again.' ) );
break;
case 'reset_caches':
foreach ( array( 'hash-cache', 'gh-hash-cache', 'gh-pushed', 'manifest', 'upload-queue', 'gh-deploy' ) as $state ) {
CFSP_Deployer::write_state( $state, array() );
}
wp_send_json_success( array( 'message' => 'Caches reset. The next push re-checks every file.' ) );
break;
/* --- Debug ---------------------------------------------------- */
case 'debug_state':
$job = CFSP_Job::get();
if ( $job ) {
foreach ( array( 'queue', 'seen', 'written', 'roots' ) as $big ) {
if ( isset( $job[ $big ] ) && count( $job[ $big ] ) > 25 ) {
$job[ $big ] = array_merge( array_slice( $job[ $big ], 0, 25, true ), array( '…' => count( $job[ $big ] ) . ' total' ) );
}
}
}
wp_send_json_success(
array(
'state' => array(
'job' => $job,
'pending' => CFSP_Job::get_pending(),
'next_pending' => wp_next_scheduled( 'cfsp_run_pending' ) ? wp_date( 'c', wp_next_scheduled( 'cfsp_run_pending' ) ) : null,
'next_watchdog' => wp_next_scheduled( 'cfsp_watchdog' ) ? wp_date( 'c', wp_next_scheduled( 'cfsp_watchdog' ) ) : null,
'next_scheduled_full' => wp_next_scheduled( 'cfsp_scheduled_full' ) ? wp_date( 'c', wp_next_scheduled( 'cfsp_scheduled_full' ) ) : null,
),
)
);
break;
case 'run_batch':
$ran = CFSP_Job::run_batch( false );
wp_send_json_success( array( 'message' => $ran ? 'Batch processed.' : 'Nothing to run (no active job, rate-limited, or another worker holds the lock).' ) );
break;
case 'unlock':
CFSP_Job::force_unlock();
wp_send_json_success( array( 'message' => 'Lock released.' ) );
break;
/* --- GitHub --------------------------------------------------- */
case 'test':
if ( ! CFSP_Settings::is_configured() ) {
wp_send_json_error( array( 'message' => 'Fill in the required fields for the selected target and save first.' ) );
}
'cloudflare' === CFSP_Settings::get( 'target' ) ? self::test_cloudflare() : self::test_github();
break;
case 'gh_connect':
self::send( CFSP_GitHub_Auth::start() );
break;
case 'gh_poll':
self::send( CFSP_GitHub_Auth::poll() );
break;
case 'gh_disconnect':
CFSP_GitHub_Auth::disconnect();
wp_send_json_success( array( 'message' => 'Disconnected.' ) );
break;
case 'gh_repos':
$repos = ( new CFSP_GitHub() )->list_repos( (bool) self::param( 'refresh' ) );
is_wp_error( $repos ) ? self::send( $repos ) : wp_send_json_success( array( 'repos' => $repos ) );
break;
case 'gh_create_repo':
$repo_name = sanitize_text_field( self::param( 'name' ) );
if ( ! preg_match( '/^[A-Za-z0-9._-]{1,100}$/', $repo_name ) ) {
wp_send_json_error( array( 'message' => 'Use letters, numbers, dots, dashes or underscores for the repository name.' ) );
}
$repo = ( new CFSP_GitHub() )->create_repo( $repo_name, (bool) self::param( 'private' ) );
CFSP_GitHub::forget_repos();
if ( is_wp_error( $repo ) ) {
self::send( $repo );
}
CFSP_Settings::update( array( 'target' => 'github', 'gh_repo' => $repo['full_name'], 'gh_branch' => $repo['default_branch'] ?? 'main' ) );
CFSP_Logger::log( 'Created GitHub repository ' . $repo['full_name'] . '.' );
wp_send_json_success(
array(
'message' => 'Created ' . $repo['full_name'] . '.',
'repo' => array(
'full_name' => $repo['full_name'],
'private' => ! empty( $repo['private'] ),
'default_branch' => $repo['default_branch'] ?? 'main',
),
)
);
break;
case 'gh_select_repo':
$repo = sanitize_text_field( self::param( 'repo' ) );
$branch = sanitize_text_field( self::param( 'branch', 'main' ) );
if ( ! preg_match( '#^[\w.-]+/[\w.-]+$#', $repo ) ) {
wp_send_json_error( array( 'message' => 'Invalid repository.' ) );
}
CFSP_Settings::update( array( 'target' => 'github', 'gh_repo' => $repo, 'gh_branch' => $branch ) );
wp_send_json_success( array( 'message' => sprintf( 'Pushing to %s (%s).', $repo, $branch ) ) );
break;
/* --- Media (R2) ----------------------------------------------- */
case 'r2_test':
if ( ! CFSP_R2::is_configured() ) {
wp_send_json_error( array( 'message' => 'Fill in the account ID, access key, secret key and bucket, then save.' ) );
}
$r2 = new CFSP_R2();
$read = $r2->test_read();
if ( is_wp_error( $read ) ) {
self::send( $read );
}
$key = CFSP_Media::key( '.cfsp-connection-test.txt' );
$write = $r2->put( $key, 'Static Push connection test ' . gmdate( 'c' ), 'text/plain' );
if ( is_wp_error( $write ) ) {
wp_send_json_error( array( 'message' => 'Can read the bucket but not write to it: ' . $write->get_error_message() . '. The token needs "Object Read & Write".' ) );
}
$r2->delete( $key );
$public = CFSP_Settings::get( 'r2_public_url' );
wp_send_json_success( array( 'message' => 'Connected to bucket "' . CFSP_Settings::get( 'r2_bucket' ) . '": read and write OK.' . ( $public ? '' : ' Set the public media URL next.' ) ) );
break;
case 'media_sync':
$started = CFSP_Media::start_sync( 'Manual sync' );
self::send( $started, 'Media sync started. You can leave this page; it keeps running in the background.' );
break;
case 'llms_preview':
list( $cfsp_text, $cfsp_links ) = CFSP_LLMs::render();
wp_send_json_success(
array(
'message' => sprintf( 'Preview: %d links. This is what /llms.txt will contain after the next push.', $cfsp_links ),
'preview' => $cfsp_text,
)
);
break;
case 'related_preview':
self::send( CFSP_Related::preview( sanitize_text_field( self::param( 'post' ) ) ) );
break;
case 'media_skip_preview':
if ( function_exists( 'set_time_limit' ) ) {
@set_time_limit( 120 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors, Squiz.PHP.DiscouragedFunctions.Discouraged -- Scanning a large uploads folder for the preview can take longer than the default limit.
}
$preview = CFSP_Media::preview_skips( sanitize_textarea_field( self::param( 'rules' ) ) );
$preview['size'] = size_format( $preview['bytes'] );
wp_send_json_success( $preview );
break;
case 'media_cleanup':
self::send( CFSP_Media::start_cleanup(), 'Removing skipped files from R2. You can leave this page; it keeps running in the background.' );
break;
case 'media_pause':
self::send( CFSP_Media::pause(), 'Media sync paused. Resume it any time, even after updating the plugin.' );
break;
case 'media_resume':
self::send( CFSP_Media::resume(), 'Media sync resumed.' );
break;
case 'media_cancel':
CFSP_Media::cancel();
wp_send_json_success( array( 'message' => 'Media sync cancelled.' ) );
break;
/* --- Cloudflare ----------------------------------------------- */
case 'create_project':
$project_name = (string) CFSP_Settings::get( 'project_name' );
if ( ! CFSP_Settings::get( 'account_id' ) || ! CFSP_Settings::get( 'api_token' ) ) {
wp_send_json_error( array( 'message' => 'Enter your Account ID and API token, save, then create the project.' ) );
}
if ( ! preg_match( '/^[a-z0-9](?:[a-z0-9-]{0,56}[a-z0-9])?$/', $project_name ) ) {
wp_send_json_error( array( 'message' => 'Use a project name with lowercase letters, numbers and dashes (for example my-site), save, then try again.' ) );
}
$cloudflare = new CFSP_Cloudflare();
if ( ! is_wp_error( $cloudflare->get_project() ) ) {
wp_send_json_success( array( 'message' => 'The project "' . $project_name . '" already exists. You can push to it.' ) );
}
$result = $cloudflare->create_project();
if ( is_wp_error( $result ) ) {
self::send( $result );
}
CFSP_Logger::log( 'Created Cloudflare Pages project ' . $result['name'] );
wp_send_json_success( array( 'message' => 'Project created: https://' . ( $result['subdomain'] ?? $result['name'] . '.pages.dev' ) ) );
break;
}
wp_send_json_error( array( 'message' => 'Unknown action.' ) );
}
private static function media_status() {
if ( ! CFSP_Settings::get( 'r2_enabled' ) ) {
return null;
}
$job = CFSP_Media::job();
$stats = get_option( CFSP_Media::STATS );
$stats = is_array( $stats ) ? $stats : CFSP_Media::totals();
$queue = get_option( CFSP_Media::QUEUE, array() );
// Keep a sync moving while the admin is watching, in case background calls are blocked
// (for example a firewall refusing this server's requests to itself): same as push jobs.
if ( $job && CFSP_Media::is_running( $job ) ) {
$idle = time() - (int) $job['updated'];
if ( $idle > 60 ) {
CFSP_Media::run_batch( false );
$job = CFSP_Media::job();
} elseif ( $idle > 10 ) {
CFSP_Media::spawn();
}
} elseif ( is_array( $queue ) && $queue && ! CFSP_Media::pause_requested() ) {
CFSP_Media::spawn(); // Newly uploaded media waiting in the queue.
}
return array(
'running' => $job && CFSP_Media::is_running( $job ),
'paused' => $job && CFSP_Media::is_paused( $job ),
'job' => $job ? array(
'phase' => $job['phase'],
'kind' => $job['kind'] ?? 'sync',
'scanned' => (int) ( $job['scanned'] ?? 0 ),
'deleted' => (int) ( $job['deleted'] ?? 0 ),
'dirs' => count( $job['dirs'] ),
'dir_i' => (int) $job['dir_i'],
'checked' => (int) $job['checked'],
'uploaded' => (int) $job['uploaded'],
'bytes' => size_format( (int) $job['bytes'] ),
'errors' => (int) $job['errors'],
'last_error' => (string) ( $job['last_error'] ?? '' ),
'message' => $job['message'],
'id' => (string) $job['started'],
'started' => self::ago( $job['started'] ),
) : null,
'files' => number_format_i18n( $stats['files'] ),
'size' => size_format( $stats['bytes'] ),
'last' => $stats['last'] ? self::ago( $stats['last'] ) : 'never',
'queued' => is_array( $queue ) ? count( $queue ) : 0,
);
}
/** Settings that only apply to newly exported pages. */
private static function needs_rebuild( array $data ) {
$before = get_option( CFSP_Settings::OPTION . '_last_export_signature' );
$keys = array( 'url_mode', 'destination_url', 'relative_path', 'force_replace', 'hide_ver', 'search_enabled', 'r2_enabled', 'r2_rewrite', 'r2_public_url', 'r2_prefix', 'r2_exclude_export' );
foreach ( array_keys( CFSP_Settings::schema() ) as $key ) {
if ( 0 === strpos( $key, 'opt_' ) || 0 === strpos( $key, 'hide_' ) || 0 === strpos( $key, 'forms_' ) || 0 === strpos( $key, 'search_' ) || 0 === strpos( $key, 'hints_' ) || 0 === strpos( $key, 'related_' ) || 0 === strpos( $key, 'feed_' ) || 0 === strpos( $key, 'sitemap_' ) ) {
$keys[] = $key;
}
}
$sig = md5( wp_json_encode( array_intersect_key( CFSP_Settings::all(), array_flip( $keys ) ) ) );
update_option( CFSP_Settings::OPTION . '_last_export_signature', $sig, false );
return $before && $before !== $sig;
}
private static function test_cloudflare() {
$project = ( new CFSP_Cloudflare() )->get_project();
if ( is_wp_error( $project ) ) {
wp_send_json_error(
array(
'message' => $project->get_error_message(),
'offer_create' => 404 === ( $project->get_error_data()['status'] ?? 0 ),
)
);
}
$domains = isset( $project['domains'] ) ? implode( ', ', (array) $project['domains'] ) : '';
wp_send_json_success( array( 'message' => sprintf( 'Connected to project "%s". Domains: %s', $project['name'], $domains ) ) );
}
private static function test_github() {
$gh = new CFSP_GitHub();
$repo = $gh->get_repo();
if ( is_wp_error( $repo ) ) {
$hint = 404 === ( $repo->get_error_data()['status'] ?? 0 ) ? ' Check the repository name and that the account has access.' : '';
wp_send_json_error( array( 'message' => $repo->get_error_message() . $hint ) );
}
if ( isset( $repo['permissions']['push'] ) && ! $repo['permissions']['push'] ) {
wp_send_json_error( array( 'message' => 'Connected, but this account can\'t write to the repository.' ) );
}
$head = $gh->get_head();
$branch = CFSP_Settings::get( 'gh_branch' );
if ( is_wp_error( $head ) && 'cfsp_empty_repo' === $head->get_error_code() ) {
$state = 'The repository is empty; it will be initialised on the first push.';
} elseif ( is_wp_error( $head ) ) {
self::send( $head );
} elseif ( null === $head ) {
$state = sprintf( 'Branch "%s" doesn\'t exist yet; it will be created on the first push.', $branch );
} else {
$state = sprintf( 'Branch "%s" is at %s.', $branch, substr( $head['commit'], 0, 7 ) );
}
wp_send_json_success( array( 'message' => sprintf( 'Connected to %s (%s). %s', $repo['full_name'], ! empty( $repo['private'] ) ? 'private' : 'public', $state ) ) );
}
/** Stream the export directory as a ZIP. */
public static function download_zip() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Permission denied.' );
}
check_admin_referer( 'cfsp_zip' );
if ( ! class_exists( 'ZipArchive' ) ) {
wp_die( 'The PHP zip extension is not available on this server.' );
}
$files = CFSP_Deployer::files();
if ( ! $files ) {
wp_die( 'Nothing has been exported yet. Run a full export first.' );
}
if ( function_exists( 'set_time_limit' ) ) {
@set_time_limit( 0 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors, Squiz.PHP.DiscouragedFunctions.Discouraged -- Zipping and sending a whole static site can take longer than the default limit.
}
$zip_path = CFSP_Settings::work_dir() . '/static-site-' . wp_generate_password( 8, false, false ) . '.zip';
$zip = new ZipArchive();
if ( true !== $zip->open( $zip_path, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ) {
wp_die( 'Could not create the ZIP file.' );
}
foreach ( $files as $rel => $file ) {
$zip->addFile( $file->getPathname(), $rel );
}
foreach ( array( '_headers' => CFSP_Deployer::headers_file(), '_redirects' => CFSP_Deployer::redirects_file() ) as $name => $content ) {
if ( '' !== $content ) {
$zip->addFromString( $name, $content );
}
}
$zip->close();
nocache_headers();
header( 'Content-Type: application/zip' );
header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( wp_parse_url( home_url(), PHP_URL_HOST ) ) . '-static-' . gmdate( 'Y-m-d' ) . '.zip"' );
header( 'Content-Length: ' . filesize( $zip_path ) );
readfile( $zip_path ); // phpcs:ignore WordPress.WP.AlternativeFunctions
wp_delete_file( $zip_path );
exit;
}
private static function ago( $time ) {
return sprintf( '%s ago', human_time_diff( (int) $time, time() ) );
}
public static function render() {
require CFSP_DIR . 'includes/views/layout.php';
}
}