array{ files, missing } | WP_Error * upload( $deadline ) -> int remaining | WP_Error * finalize() -> array{ url, id, nochange? } | WP_Error * * WP_Error codes with special meaning for the job runner: * cfsp_rate_limited data['wait'] seconds to pause before retrying * cfsp_restart start the deploy again from prepare() */ if ( ! defined( 'ABSPATH' ) ) { exit; } class CFSP_Deployer { /** Files at the export root that the targets generate themselves. */ const RESERVED = array( '_headers', '_redirects', '_routes.json', '_worker.js' ); /** Cloudflare Pages limits for the _redirects file. */ const MAX_STATIC_REDIRECTS = 2000; const MAX_DYNAMIC_REDIRECTS = 100; public static function driver() { return 'cloudflare' === CFSP_Settings::get( 'target' ) ? 'CFSP_Deploy_Cloudflare' : 'CFSP_Deploy_GitHub'; } public static function target_label() { return 'cloudflare' === CFSP_Settings::get( 'target' ) ? 'Cloudflare Pages' : 'GitHub'; } public static function prepare( $job = array() ) { return call_user_func( array( self::driver(), 'prepare' ), $job ); } public static function upload( $deadline ) { return call_user_func( array( self::driver(), 'upload' ), $deadline ); } public static function finalize() { return call_user_func( array( self::driver(), 'finalize' ) ); } /** Runs every step synchronously (used by WP-CLI). */ public static function deploy_now( $job = array() ) { for ( $attempt = 0; $attempt < 3; $attempt++ ) { $prep = self::prepare( $job ); if ( is_wp_error( $prep ) ) { return $prep; } CFSP_Logger::log( sprintf( 'Deploy: %d files, %d to send.', $prep['files'], $prep['missing'] ) ); do { $remaining = self::upload( time() + 300 ); if ( is_wp_error( $remaining ) ) { if ( 'cfsp_rate_limited' !== $remaining->get_error_code() ) { return $remaining; } $wait = (int) ( $remaining->get_error_data()['wait'] ?? 60 ); CFSP_Logger::log( "Rate limited, waiting {$wait}s…" ); sleep( $wait ); $remaining = 1; } } while ( $remaining > 0 ); $result = self::finalize(); if ( ! is_wp_error( $result ) || 'cfsp_restart' !== $result->get_error_code() ) { return $result; } } return $result; } /* ------------------------------------------------------------------ * * Helpers shared by the targets * ------------------------------------------------------------------ */ /** @return SplFileInfo[] keyed by path relative to the export dir. */ public static function files() { $root = CFSP_Settings::export_dir(); $files = array(); if ( ! is_dir( $root ) ) { return $files; } // CATCH_GET_CHILD skips folders that cannot be read instead of aborting the whole request. $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $root, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ( $it as $file ) { if ( ! $file->isFile() ) { continue; } $rel = ltrim( str_replace( '\\', '/', substr( $file->getPathname(), strlen( $root ) ) ), '/' ); if ( '' === $rel || '.' === $rel[0] || in_array( $rel, self::RESERVED, true ) ) { continue; } $files[ $rel ] = $file; } ksort( $files ); return $files; } /** * Number of files in the export folder, for status displays. Counts without keeping a file * object per file (files() does, which runs out of memory on very large exports), skips * unreadable folders, and caches the result for five minutes. * * @param bool $fresh Ignore the cached value. * @return int */ public static function count_files( $fresh = false ) { $cached = get_transient( 'cfsp_export_count' ); if ( ! $fresh && false !== $cached ) { return (int) $cached; } $root = CFSP_Settings::export_dir(); $count = 0; if ( is_dir( $root ) ) { try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $root, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ( $it as $path => $file ) { $name = $file->getFilename(); if ( '' !== $name && '.' !== $name[0] && $file->isFile() ) { ++$count; } } } catch ( Exception $e ) { CFSP_Logger::log( 'Could not count exported files: ' . $e->getMessage() ); } } set_transient( 'cfsp_export_count', $count, 5 * MINUTE_IN_SECONDS ); return $count; } private static function state_path( $name ) { return CFSP_Settings::work_dir() . '/' . $name . '.json'; } public static function read_state( $name ) { $path = self::state_path( $name ); if ( ! is_file( $path ) ) { return array(); } $data = json_decode( file_get_contents( $path ), true ); return is_array( $data ) ? $data : array(); } public static function write_state( $name, $data ) { file_put_contents( self::state_path( $name ), wp_json_encode( $data, JSON_UNESCAPED_SLASHES ) ); } /** Remember the real Content-Type of non-HTML content stored as index.html (feeds, etc.). */ public static function set_content_type_override( $file, $type ) { $map = self::read_state( 'content-types' ); $file = ltrim( $file, '/' ); if ( $type ) { if ( ( $map[ $file ] ?? null ) === $type ) { return; } $map[ $file ] = $type; } elseif ( isset( $map[ $file ] ) ) { unset( $map[ $file ] ); } else { return; } self::write_state( 'content-types', $map ); } /** Contents of the Cloudflare Pages _headers file. */ public static function headers_file() { $out = trim( (string) CFSP_Settings::get( 'headers' ) ) . "\n" . CFSP_Feeds::header_rules(); foreach ( self::read_state( 'content-types' ) as $file => $type ) { $path = '/' . preg_replace( '#index\.html$#', '', $file ); $out .= "\n{$path}\n Content-Type: {$type}\n"; } $out = trim( $out ); return '' === $out ? '' : $out . "\n"; } /** * Contents of the Cloudflare Pages _redirects file. * * Cloudflare Pages allows 2,000 static and 100 dynamic redirects, and every line after the first * dynamic one (a * splat or :placeholder in the source) counts as dynamic. A single wildcard rule * near the top would silently switch off everything past the 100th line, so plain lines go first * and dynamic lines last, each group in its original order. */ public static function redirects_file() { $lines = array_unique( array_merge( CFSP_Settings::lines( 'redirects' ), CFSP_Integrations::redirection_rules(), CFSP_Moved::lines(), CFSP_Feeds::redirect_lines() ) ); $static = array(); $dynamic = array(); foreach ( $lines as $line ) { if ( self::is_dynamic_redirect( $line ) ) { $dynamic[] = $line; } else { $static[] = $line; } } if ( count( $static ) > self::MAX_STATIC_REDIRECTS || count( $dynamic ) > self::MAX_DYNAMIC_REDIRECTS ) { static $warned = false; if ( ! $warned ) { $warned = true; CFSP_Logger::error( sprintf( '_redirects has %1$d plain and %2$d wildcard rules; Cloudflare Pages applies at most %3$d and %4$d, and ignores the rest.', count( $static ), count( $dynamic ), self::MAX_STATIC_REDIRECTS, self::MAX_DYNAMIC_REDIRECTS ) ); } } $lines = array_merge( $static, $dynamic ); return $lines ? implode( "\n", $lines ) . "\n" : ''; } /** True for a _redirects line whose source has a * splat or a :placeholder segment. */ public static function is_dynamic_redirect( $line ) { $source = strtok( trim( (string) $line ), " \t" ); if ( false === $source ) { return false; } return false !== strpos( $source, '*' ) || (bool) preg_match( '#/:[A-Za-z_]#', $source ); } }