'maintenance',
'design' => 'template',
'page_id' => '0',
'headline' => 'We’ll be back soon!',
'message' => 'Our website is currently undergoing scheduled maintenance. Thank you for your patience.',
'launch_date' => '',
'logo' => '',
'bg_image' => '',
'bg_color' => '#0f172a',
'text_color' => '#f8fafc',
'allow_roles' => array( 'administrator', 'editor' ),
'public_urls' => '',
'retry_after' => 60,
);
}
/**
* Settings fields.
*
* @return array
*/
public function get_fields() {
$pages = array( '0' => __( '— Select a page —', 'toolvane' ) );
foreach ( get_pages( array( 'post_status' => 'publish' ) ) as $page ) {
$pages[ (string) $page->ID ] = $page->post_title ? $page->post_title : '#' . $page->ID;
}
return array(
'mode' => array(
'type' => 'select',
'label' => __( 'Mode', 'toolvane' ),
'options' => array(
'maintenance' => __( 'Maintenance (HTTP 503, search engines come back later)', 'toolvane' ),
'coming_soon' => __( 'Coming Soon (HTTP 200)', 'toolvane' ),
),
),
'design' => array(
'type' => 'select',
'label' => __( 'Design', 'toolvane' ),
'options' => array(
'template' => __( 'Built-in template', 'toolvane' ),
'page' => __( 'A page of my site (block editor, Elementor or any builder)', 'toolvane' ),
),
'description' => __( 'With "A page of my site" visitors see the selected page at every URL, with your theme and page builder styles.', 'toolvane' ),
),
'page_id' => array(
'type' => 'select',
'label' => __( 'Page', 'toolvane' ),
'options' => $pages,
),
'template' => array(
'type' => 'heading',
'label' => __( 'Built-in template', 'toolvane' ),
),
'headline' => array(
'type' => 'text',
'label' => __( 'Headline', 'toolvane' ),
),
'message' => array(
'type' => 'textarea',
'label' => __( 'Message', 'toolvane' ),
),
'launch_date' => array(
'type' => 'text',
'label' => __( 'Back online / launch date', 'toolvane' ),
'placeholder' => 'YYYY-MM-DD HH:MM',
'description' => __( 'Optional. Shown on the page and used for the Retry-After header. Uses the site time zone.', 'toolvane' ),
),
'logo' => array(
'type' => 'image',
'label' => __( 'Logo', 'toolvane' ),
),
'bg_image' => array(
'type' => 'image',
'label' => __( 'Background image', 'toolvane' ),
),
'bg_color' => array(
'type' => 'color',
'label' => __( 'Background color', 'toolvane' ),
),
'text_color' => array(
'type' => 'color',
'label' => __( 'Text color', 'toolvane' ),
),
'access' => array(
'type' => 'heading',
'label' => __( 'Access', 'toolvane' ),
'description' => $this->preview_link_description(),
),
'allow_roles' => array(
'type' => 'checkboxes',
'label' => __( 'Roles that can see the site', 'toolvane' ),
'options' => $this->role_options(),
'description' => __( 'Logged-in users with these roles see the normal site. Administrators always do.', 'toolvane' ),
),
'public_urls' => array(
'type' => 'lines',
'label' => __( 'Always reachable URLs', 'toolvane' ),
'rows' => 4,
'placeholder' => "/contact\n/landing/*",
'description' => __( 'One path per line. These pages stay public. Use * at the end to match a whole section.', 'toolvane' ),
),
'retry_after' => array(
'type' => 'number',
'label' => __( 'Retry-After', 'toolvane' ),
'unit' => __( 'minutes', 'toolvane' ),
'min' => 1,
'max' => 10080,
'description' => __( 'Sent with the 503 status when no date is set, so search engines know when to come back.', 'toolvane' ),
),
);
}
/**
* Sanitizes settings and validates the launch date.
*
* @param mixed $input Raw input.
* @return array
*/
public function sanitize( $input ) {
$clean = parent::sanitize( $input );
if ( '' !== $clean['launch_date'] && ! $this->launch_timestamp( $clean['launch_date'] ) ) {
$clean['launch_date'] = '';
}
return $clean;
}
/**
* Registers hooks.
*/
public function init() {
add_action( 'init', array( $this, 'maybe_set_preview_cookie' ), 1 );
add_filter( 'request', array( $this, 'filter_request' ), 99 );
add_action( 'template_redirect', array( $this, 'maybe_show' ), 0 );
add_action( 'admin_bar_menu', array( $this, 'admin_bar' ), 100 );
add_action( 'wp_enqueue_scripts', array( $this, 'admin_bar_style' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'admin_bar_style' ) );
}
/**
* Purges page caches when the module is switched on or off.
*
* @param bool $enabled New state.
*/
public function on_toggle( $enabled ) {
Cache::purge_all();
}
/**
* Purges page caches after saving.
*/
public function on_settings_saved() {
Cache::purge_all();
}
/**
* Secret key for the preview link.
*
* @return string
*/
private function preview_key() {
$key = get_option( self::KEY_OPTION );
if ( ! $key ) {
$key = wp_generate_password( 20, false );
update_option( self::KEY_OPTION, $key, false );
}
return (string) $key;
}
/**
* Help text with the preview link.
*
* @return string
*/
private function preview_link_description() {
$url = add_query_arg( self::PREVIEW_PARAM, $this->preview_key(), home_url( '/' ) );
return sprintf(
/* translators: %s: preview URL */
__( 'Share this link with clients so they can see the real site without an account (valid for 7 days per browser): %s', 'toolvane' ),
'' . esc_html( $url ) . ''
);
}
/**
* Sets the preview cookie when the secret link is opened.
*/
public function maybe_set_preview_cookie() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The secret key is the authorization.
if ( ! isset( $_GET[ self::PREVIEW_PARAM ] ) ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The secret key is the authorization.
$key = sanitize_text_field( wp_unslash( $_GET[ self::PREVIEW_PARAM ] ) );
if ( hash_equals( $this->preview_key(), $key ) && ! headers_sent() ) {
setcookie( self::COOKIE, wp_hash( $key ), time() + WEEK_IN_SECONDS, COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN, is_ssl(), true );
$_COOKIE[ self::COOKIE ] = wp_hash( $key );
}
}
/**
* Whether the current visitor bypasses maintenance mode.
*
* @return bool
*/
private function can_bypass() {
$bypass = current_user_can( 'manage_options' ) || $this->current_user_has_role( (array) $this->get( 'allow_roles', array() ) );
if ( ! $bypass && isset( $_COOKIE[ self::COOKIE ] ) ) {
$bypass = hash_equals( wp_hash( $this->preview_key() ), sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE ] ) ) );
}
/**
* Filters whether the current request bypasses maintenance mode.
*
* @param bool $bypass Whether to bypass.
*/
return (bool) apply_filters( 'toolvane_maintenance_bypass', $bypass );
}
/**
* Request path relative to the home URL.
*
* @return string
*/
private function request_path() {
$uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '/';
$path = strtolower( (string) wp_parse_url( $uri, PHP_URL_PATH ) );
$home_path = strtolower( untrailingslashit( (string) wp_parse_url( home_url(), PHP_URL_PATH ) ) );
if ( $home_path && 0 === strpos( $path, $home_path ) ) {
$path = substr( $path, strlen( $home_path ) );
}
return '/' . trim( $path, '/' );
}
/**
* Whether the current URL is in the exclusion list.
*
* @return bool
*/
private function is_excluded() {
$path = $this->request_path();
foreach ( $this->get_lines( 'public_urls' ) as $rule ) {
$rule = '/' . trim( strtolower( (string) wp_parse_url( $rule, PHP_URL_PATH ) ), '/' );
if ( '*' === substr( $rule, -1 ) ) {
$prefix = rtrim( substr( $rule, 0, -1 ), '/' );
if ( '' === $prefix || $path === $prefix || 0 === strpos( $path, $prefix . '/' ) ) {
return true;
}
} elseif ( $path === $rule ) {
return true;
}
}
return false;
}
/**
* Whether the maintenance page applies to this request.
*
* @return bool
*/
private function is_active() {
if ( null !== $this->active ) {
return $this->active;
}
$this->active = ! (
is_admin()
|| wp_doing_ajax()
|| wp_doing_cron()
|| ( defined( 'REST_REQUEST' ) && REST_REQUEST )
|| isset( $_GET['wc-ajax'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WooCommerce AJAX endpoint detection only.
|| isset( $_GET['wc-api'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WooCommerce payment callback detection only.
|| ( defined( 'WP_CLI' ) && WP_CLI )
|| $this->can_bypass()
|| $this->is_excluded()
);
return $this->active;
}
/**
* Selected design page, if valid.
*
* @return \WP_Post|null
*/
private function design_page() {
if ( 'page' !== $this->get( 'design' ) ) {
return null;
}
$page = get_post( absint( $this->get( 'page_id' ) ) );
return ( $page && 'page' === $page->post_type && 'publish' === $page->post_status ) ? $page : null;
}
/**
* Serves the selected page at every URL (no redirect, so every URL returns the 503 status).
*
* @param array $query_vars Parsed query variables.
* @return array
*/
public function filter_request( $query_vars ) {
$page = $this->design_page();
if ( ! $page || ! $this->is_active() ) {
return $query_vars;
}
// Keep the REST API, WooCommerce endpoints, robots.txt, favicon and sitemaps working.
foreach ( array( 'rest_route', 'wc-api', 'wc-ajax', 'robots', 'favicon', 'sitemap', 'sitemap-subtype', 'sitemap-stylesheet' ) as $keep ) {
if ( ! empty( $query_vars[ $keep ] ) ) {
return $query_vars;
}
}
remove_action( 'template_redirect', 'redirect_canonical' );
return array( 'page_id' => $page->ID );
}
/**
* Timestamp of the launch date.
*
* @param string $date Date string in the site time zone.
* @return int 0 when invalid.
*/
private function launch_timestamp( $date ) {
if ( '' === trim( (string) $date ) ) {
return 0;
}
try {
$dt = new \DateTimeImmutable( (string) $date, wp_timezone() );
return $dt->getTimestamp();
} catch ( \Exception $e ) {
return 0;
}
}
/**
* Sends status headers and outputs the built-in page when needed.
*/
public function maybe_show() {
if ( ! $this->is_active() || is_robots() || is_favicon() ) {
return;
}
// Tell caching plugins (WP Rocket, LiteSpeed, W3 Total Cache and others) not to cache this response.
if ( ! defined( 'DONOTCACHEPAGE' ) ) {
define( 'DONOTCACHEPAGE', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Standard constant read by caching plugins.
}
nocache_headers();
$launch = $this->launch_timestamp( $this->get( 'launch_date' ) );
if ( 'maintenance' === $this->get( 'mode' ) ) {
status_header( 503 );
$retry = $launch > time() ? min( $launch - time(), WEEK_IN_SECONDS ) : absint( $this->get( 'retry_after', 60 ) ) * MINUTE_IN_SECONDS;
header( 'Retry-After: ' . (int) $retry );
} else {
status_header( 200 );
}
if ( $this->design_page() ) {
if ( 'maintenance' === $this->get( 'mode' ) ) {
add_filter( 'wp_robots', 'wp_robots_no_robots' );
}
return; // The theme renders the selected page.
}
$this->render_template( $launch );
exit;
}
/**
* Outputs the built-in template.
*
* @param int $launch Launch timestamp or 0.
*/
private function render_template( $launch ) {
header( 'Content-Type: text/html; charset=' . get_bloginfo( 'charset' ) );
$bg = $this->get( 'bg_color' ) ? $this->get( 'bg_color' ) : '#0f172a';
$color = $this->get( 'text_color' ) ? $this->get( 'text_color' ) : '#f8fafc';
$image = $this->get( 'bg_image' );
$logo = $this->get( 'logo' );
$headline = (string) $this->get( 'headline' );
$css = sprintf( ':root{--toolvane-bg:%1$s;--toolvane-color:%2$s}', $bg, $color );
if ( $image ) {
$css .= 'body{background-image:url("' . esc_url_raw( $image ) . '")}';
}
wp_register_style( 'toolvane-maintenance', TOOLVANE_URL . 'assets/css/maintenance.css', array(), TOOLVANE_VERSION );
wp_add_inline_style( 'toolvane-maintenance', $css );
?>
>