caps = $caps;
$this->formsRepo = $formsRepo ?? new FormsRepository();
$this->submissionsRepo = $submissionsRepo ?? new SubmissionsRepository();
// Add-on submenu pages can draw inside the SubtleForms frame (registerAdminPage).
add_filter( 'subtleforms/admin_pages_supported', '__return_true' );
add_action( 'admin_menu', array( $this, 'register_menu' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'menu_icon_styles' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
// WordPress checks access to a page right after `admin_menu`, so the
// old Tools URL is sent on before that check.
add_action( 'admin_menu', array( $this, 'redirect_legacy_pages' ), 1 );
add_action( 'admin_init', array( $this, 'handle_actions' ) );
add_filter( 'admin_body_class', array( $this, 'filter_admin_body_class' ) );
// Hook title filter with highest priority to catch null values first
add_filter( 'admin_title', array( $this, 'filter_admin_title' ), 1, 2 );
// Fix globals early before WordPress uses them
add_action( 'admin_init', array( $this, 'fix_admin_globals' ), 1 );
// Fix menu highlighting for correct active states
add_filter( 'parent_file', array( $this, 'fix_parent_file' ) );
add_filter( 'submenu_file', array( $this, 'fix_submenu_file' ) );
add_action( 'admin_menu', array( $this, 'pin_menu_order' ), 99 );
add_action( 'admin_print_footer_scripts', array( self::class, 'upgrade_link_script' ) );
add_action(
'admin_menu',
function () {
global $submenu;
if ( isset( $submenu['subtleforms'][0] ) ) {
$submenu['subtleforms'][0][0] = __( 'Dashboard', 'subtleforms' );
}
},
100
);
}
/**
* Get submission menu title with unread count badge.
*/
/**
* Get the site domain (host without scheme/path), lowercased.
*
* Used by the Settings screen to flag a sender email whose domain does
* not match the site domain (Part B20).
*
* @return string
*/
private function get_site_domain(): string {
$host = wp_parse_url( home_url(), PHP_URL_HOST );
if ( empty( $host ) ) {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.NonceVerification.Recommended -- Read-only fallback.
$host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
}
if ( empty( $host ) ) {
$host = 'localhost';
}
return strtolower( $host );
}
/**
* Number of unread submissions, for the navigation badge.
*
* @return int
*/
private function get_unread_count(): int {
return self::unread_count( $this->submissionsRepo );
}
/**
* Number of unread entries, counted once per request. The menu badge, the
* admin bar and the admin data all read it from here.
*
* @param SubmissionsRepository|null $repo Entries.
* @return int
*/
public static function unread_count( ?SubmissionsRepository $repo = null ): int {
if ( null !== self::$unread ) {
return self::$unread;
}
try {
$repo = $repo ?? new SubmissionsRepository();
self::$unread = (int) $repo->count( array( 'is_read' => 0 ) );
return self::$unread;
} catch ( \Throwable $e ) {
return 0;
}
}
/**
* Forget the per-request unread count (after this request changed entries).
*/
public static function forget_unread_count(): void {
self::$unread = null;
self::$total = null;
}
/**
* Every entry the Submissions screen can list (not the Trash, not builder
* previews), for the Submissions badge in the plugin navigation.
*
* Cached in a transient named after the counts generation, which the
* entries repository bumps on every new, changed or removed entry, so a
* new entry shows on the next page load without a count on every request.
*
* @return int
*/
public static function total_count(): int {
if ( null !== self::$total ) {
return self::$total;
}
$key = 'subtleforms_total_entries_' . (int) get_option( 'subtleforms_counts_generation', 1 );
$cached = get_transient( $key );
if ( false !== $cached ) {
self::$total = (int) $cached;
return self::$total;
}
try {
self::$total = (int) ( new SubmissionsRepository() )->count();
} catch ( \Throwable $e ) {
return 0;
}
set_transient( $key, self::$total, DAY_IN_SECONDS );
return self::$total;
}
/**
* Total entries as counted earlier in this request.
*
* @var int|null
*/
private static $total = null;
/**
* Unread entries as counted earlier in this request.
*
* @var int|null
*/
private static $unread = null;
/**
* Unread count bubble for a menu label, styled like core's comment count.
* Counts above 9 show as "9+".
*
* @param int $count Unread entries.
* @return string Empty when there is nothing unread.
*/
public static function unread_badge( int $count ): string {
if ( $count < 1 ) {
return '';
}
$label = $count > 9 ? '9+' : number_format_i18n( $count );
return sprintf(
' %2$s %3$s ',
min( $count, 10 ),
esc_html( $label ),
esc_html(
sprintf(
/* translators: %s: number of unread entries. */
_n( '%s unread entry', '%s unread entries', $count, 'subtleforms' ),
number_format_i18n( $count )
)
)
);
}
private function getSubmissionMenuTitle(): string {
return esc_html__( 'Submissions', 'subtleforms' ) . self::unread_badge( $this->get_unread_count() );
}
/**
* Path data of the SubtleForms mark (512 by 512): a rounded tile with the
* S cut out as empty space. Never edit the geometry.
*/
private const MARK_TILE_TOP = 'M0 122.88 C0 55.015 55.015 0 122.88 0 L389.12 0 C406.467 0 422.974 3.594 437.937 10.079 L170.586 117.679 C131.238 133.516 112.178 178.252 128.015 217.6 L128 217.6 C128 260.015 162.385 294.4 204.8 294.4 L383.975 294.4 L12.8 443.787 C4.607 427.322 0 408.759 0 389.12 Z';
private const MARK_TILE_BOTTOM = 'M128.015 217.6 L499.199 68.21 C507.392 84.676 512 103.24 512 122.88 L512 389.12 C512 456.985 456.985 512 389.12 512 L122.88 512 C105.531 512 89.023 508.405 74.058 501.919 L341.403 394.321 C380.751 378.484 399.811 333.748 383.975 294.4 L384 294.4 C384 251.985 349.615 217.6 307.2 217.6 Z';
/**
* Menu mark as a data URI. Core paints `fill` attributes of a base64 SVG
* icon in the admin colour scheme (grey, white on hover and for the current
* page), so the mark is a single-colour silhouette with `fill="black"`.
* The viewBox pads the 512 tile so it draws at 16 of the 20 pixels, the
* visual size of the core menu icons; a full-bleed tile looks too big.
*
* @return string
*/
public static function default_menu_icon(): string {
$svg = ''
. ' '
. ' '
. ' ';
return 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- builds a static data URI icon, as core documents for add_menu_page().
}
/**
* Menu icon: the filtered `menuIcon` or the default mark.
*
* @return string
*/
private static function menu_icon(): string {
$icon = self::branding()['menuIcon'];
return '' !== $icon ? $icon : self::default_menu_icon();
}
/**
* Keep an image-URL menu icon at 16 by 16, the visual size of core icons. Core draws a URL icon as an
* and pads and fades it. A data-URI icon needs no styles.
*/
public function menu_icon_styles(): void {
$row = '#adminmenu #toplevel_page_subtleforms';
// The name and the unread bubble stay on one line, and the bubble keeps
// its contrast on the highlighted row, whose background is the same
// colour as the bubble.
$css = $row . ' > a .wp-menu-name{white-space:nowrap;padding-right:4px;}'
. $row . '.wp-has-current-submenu > a .awaiting-mod,' . $row . '.current > a .awaiting-mod{background:#fff;color:var(--wp-admin-theme-color,#2271b1);}';
if ( 0 !== strpos( self::menu_icon(), 'data:' ) ) {
$css .= $row . ' .wp-menu-image img{width:16px;height:16px;padding:9px 0 0;opacity:1;object-fit:contain;}';
}
// The upgrade item is a button: lime background, dark text, regular
// weight, no icon. Hover and focus keep the same colours in every scheme.
$css .= '#adminmenu .sf-menu-upgrade,#adminmenu a:hover .sf-menu-upgrade,#adminmenu a:focus .sf-menu-upgrade{display:inline-block;padding:3px 10px;border-radius:4px;background:#C6F432;color:#0E0E2C;font-weight:400;line-height:1.5;}'
. '#adminmenu a:hover .sf-menu-upgrade,#adminmenu a:focus .sf-menu-upgrade{background:#b4e01c;}';
wp_register_style( 'subtleforms-menu-icon', false, array(), SUBTLEFORMS_VERSION );
wp_enqueue_style( 'subtleforms-menu-icon' );
wp_add_inline_style( 'subtleforms-menu-icon', $css );
}
/**
* Accept a menu icon: an SVG data URI with valid base64, or an http(s) URL.
* Anything else is dropped so the default mark is used.
*
* @param mixed $icon Raw value from the branding filter.
* @return string
*/
public static function sanitize_menu_icon( $icon ): string {
if ( ! is_string( $icon ) ) {
return '';
}
$icon = trim( $icon );
$prefix = 'data:image/svg+xml;base64,';
if ( 0 === strpos( $icon, $prefix ) ) {
$payload = substr( $icon, strlen( $prefix ) );
$decoded = '' === $payload ? false : base64_decode( $payload, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- validates a data URI icon.
if ( false === $decoded || false === stripos( $decoded, ' 20000 ) {
return '';
}
$allowed = array(
'svg' => array(
'xmlns' => true,
'viewbox' => true,
),
'g' => array( 'fill' => true ),
'path' => array(
'd' => true,
'fill' => true,
),
);
// Drop element bodies kses would keep as text, then keep allowed tags only.
$svg = (string) preg_replace( '#<(script|style|title|desc|metadata)\b[^>]*>.*?\1\s*>#is', '', $svg );
$clean = wp_kses( $svg, $allowed );
$clean = (string) preg_replace( '/>[^<]+', '><', $clean );
$clean = str_replace( ' viewbox=', ' viewBox=', $clean );
// Keep fills to plain colours and path data to path characters.
$clean = (string) preg_replace_callback(
'/\s(fill|d|viewBox)="([^"]*)"/i',
static function ( array $m ): string {
$name = strtolower( $m[1] );
$value = $m[2];
if ( 'fill' === $name ) {
$ok = preg_match( '/^(#[0-9a-f]{3,8}|[a-z]+|var\(--[a-z0-9-]+(,\s*#[0-9a-f]{3,8})?\))$/i', $value );
} elseif ( 'd' === $name ) {
$ok = preg_match( '/^[0-9a-z\s,.+\-]*$/i', $value );
} else {
$ok = preg_match( '/^[0-9.\s-]+$/', $value );
}
return $ok ? $m[0] : '';
},
$clean
);
if ( false === stripos( $clean, 'get_unread_count() ),
$this->caps->manage_cap(),
'subtleforms',
array( $this, 'render_dashboard' ),
self::menu_icon(),
56
);
// Dashboard submenu (rename the first item)
// add_submenu_page(
// 'subtleforms',
// __('Dashboard', 'subtleforms'),
// __('Dashboard', 'subtleforms'),
// $this->caps->manage_cap(),
// 'subtleforms',
// [$this, 'render_dashboard']
// );
// All Forms
add_submenu_page(
'subtleforms',
__( 'All Forms', 'subtleforms' ),
__( 'All Forms', 'subtleforms' ),
$this->caps->manage_cap(),
'subtleforms-forms',
array( $this, 'render_forms' )
);
// Add New Form
add_submenu_page(
'subtleforms',
__( 'Add New Form', 'subtleforms' ),
__( 'Add New', 'subtleforms' ),
$this->caps->manage_cap(),
'subtleforms-new-form',
array( $this, 'render_new_form' )
);
// Submissions with count badge
$submissionMenuTitle = $this->getSubmissionMenuTitle();
add_submenu_page(
'subtleforms',
__( 'Submissions', 'subtleforms' ),
$submissionMenuTitle,
$this->caps->manage_cap(),
'subtleforms-submissions',
array( $this, 'render_submissions' )
);
// Reports.
add_submenu_page(
'subtleforms',
__( 'Reports', 'subtleforms' ),
__( 'Reports', 'subtleforms' ),
$this->caps->manage_cap(),
'subtleforms-reports',
array( $this, 'render_reports' )
);
/**
* Add-ons add their own submenu pages here. They land between Reports
* and Settings, in the order the add-on adds them.
*
* @param Capabilities $caps Capabilities of this plugin.
*/
do_action( 'subtleforms/admin_menu', $this->caps );
// Settings is the last working page.
add_submenu_page(
'subtleforms',
__( 'Settings', 'subtleforms' ),
__( 'Settings', 'subtleforms' ),
$this->caps->manage_cap(),
'subtleforms-settings',
array( $this, 'render_settings' )
);
// The upgrade item, after Settings, until an add-on is installed. It is
// a link to the Pro page on subtleforms.com, not a page: WordPress prints
// a submenu slug that is not a registered page as the link itself. The
// footer script opens it in a new tab.
if ( self::show_upgrade_item() ) {
global $submenu;
$submenu['subtleforms'][] = array( // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Adds a link to this plugin's own submenu.
self::upgrade_menu_title(),
$this->caps->manage_cap(),
self::upgrade_url( 'menu' ),
__( 'Upgrade to Pro', 'subtleforms' ),
);
}
}
/**
* Whether the upgrade item is in the menu.
*
* It is there while no add-on is installed. An add-on that adds the
* features the page lists returns false from
* `subtleforms/admin/upgrade_menu_item`.
*
* @return bool
*/
public static function show_upgrade_item(): bool {
/**
* Whether the upgrade item is in the menu.
*
* @param bool $show True unless the add-on from the SubtleForms team is active.
* @since 2.7.5
*/
return (bool) apply_filters( 'subtleforms/admin/upgrade_menu_item', ! self::companion_active() );
}
/**
* Menu label of the Upgrade item, drawn as a lime button with dark text
* by menu_icon_styles().
*
* @return string HTML.
*/
public static function upgrade_menu_title(): string {
return '';
}
/**
* Label of the Upgrade item, for the admin bar.
*
* @return string Escaped text.
*/
public static function upgrade_label(): string {
return esc_html__( 'Upgrade to Pro', 'subtleforms' );
}
/**
* Address of the Pro page on subtleforms.com, tagged with where the click came from.
*
* @param string $medium Where the link is shown.
* @return string
*/
public static function upgrade_url( string $medium = 'menu' ): string {
return add_query_arg(
array(
'utm_source' => 'wp-admin',
'utm_medium' => sanitize_key( $medium ),
),
self::MORE_FEATURES_URL
);
}
/**
* Keep Settings and the Upgrade item at the end of the submenu, whoever
* added items and whenever they did it. An add-on that hooks `admin_menu`
* itself, after this class, still lands before Settings.
*/
public function pin_menu_order(): void {
global $submenu;
if ( empty( $submenu['subtleforms'] ) || ! is_array( $submenu['subtleforms'] ) ) {
return;
}
$pinned = array( 'subtleforms-settings', self::upgrade_url( 'menu' ) );
$head = array();
$tail = array();
foreach ( $submenu['subtleforms'] as $item ) {
if ( isset( $item[2] ) && in_array( $item[2], $pinned, true ) ) {
$tail[ array_search( $item[2], $pinned, true ) ] = $item;
continue;
}
$head[] = $item;
}
ksort( $tail );
$items = array_merge( $head, array_values( $tail ) );
$submenu['subtleforms'] = $items; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Reorders this plugin's own submenu.
}
/**
* Open the Upgrade menu item in a new tab. WordPress has no target
* attribute for menu items, so the footer sets it on the link.
*/
public static function upgrade_link_script(): void {
if ( ! self::show_upgrade_item() ) {
return;
}
wp_print_inline_script_tag(
'document.querySelectorAll("#adminmenu .sf-menu-upgrade").forEach(function(s){var a=s.closest("a");if(a){a.target="_blank";a.rel="noopener noreferrer";}});'
);
}
/**
* Enqueue admin assets.
*/
public function enqueue_assets( string $hook ): void {
// Ensure $hook is never null
$hook = Helpers::normalize_string( $hook );
// Only load on our admin pages
if ( strpos( $hook, 'subtleforms' ) === false ) {
return;
}
$this->currentPage = $hook;
// Base styling for every @wordpress/components primitive this app uses -
// Button, Panel, ToggleControl, SelectControl, DropdownMenu, Popover,
// Modal, SnackbarList and the rest. `wp-components` is registered as a
// script handle AND a separate style handle; depending on the script (as
// the bundle below does) pulls in none of the CSS. Without this, every
// one of those elements renders with no background, border, spacing or
// shadow from WordPress core, only the few `.components-*` rules this
// plugin overrides, which is what made the admin look unstyled rather
// than merely differently themed.
wp_enqueue_style( 'wp-components' );
// Component styles from wp-scripts build (Settings, Dashboard, etc.)
wp_enqueue_style(
'subtleforms-components',
SUBTLEFORMS_PLUGIN_URL . 'build/admin/index.jsx.css',
array( 'wp-components' ),
SUBTLEFORMS_VERSION
);
// The picker styles: the builder canvas draws the real picker controls.
if ( file_exists( SUBTLEFORMS_PLUGIN_DIR . 'build/frontend/picker.css' ) ) {
wp_enqueue_style(
'subtleforms-admin-picker',
SUBTLEFORMS_PLUGIN_URL . 'build/frontend/picker.css',
array( 'subtleforms-components' ),
(string) filemtime( SUBTLEFORMS_PLUGIN_DIR . 'build/frontend/picker.css' )
);
wp_style_add_data( 'subtleforms-admin-picker', 'rtl', 'replace' );
}
// Main admin JS (built bundle at build/admin/admin.js)
$asset_file = SUBTLEFORMS_PLUGIN_DIR . 'build/admin/admin.asset.php';
if ( file_exists( $asset_file ) ) {
$asset = include $asset_file;
wp_enqueue_script(
'subtleforms-admin',
SUBTLEFORMS_PLUGIN_URL . 'build/admin/admin.js',
$asset['dependencies'] ?? array( 'wp-element', 'wp-components', 'wp-data', 'wp-i18n' ),
$asset['version'] ?? SUBTLEFORMS_VERSION,
true
);
} else {
wp_enqueue_script(
'subtleforms-admin',
SUBTLEFORMS_PLUGIN_URL . 'build/admin/admin.js',
array( 'wp-element', 'wp-components', 'wp-data', 'wp-i18n' ),
SUBTLEFORMS_VERSION,
true
);
}
// Expose build URL so webpack async chunks (code-split pages) load correctly.
// This must run BEFORE the admin script executes.
wp_add_inline_script(
'subtleforms-admin',
sprintf(
'window.__subtleformsPublicPath = %s;',
wp_json_encode( SUBTLEFORMS_PLUGIN_URL . 'build/admin/' )
),
'before'
);
// Rebuild Capabilities fresh at enqueue time, so filters that add-ons
// added after this class was built are included.
$live_caps = new Capabilities();
$admin_data = array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'restUrl' => rest_url( 'subtleforms/v1' ),
'nonce' => wp_create_nonce( 'subtleforms_admin' ),
'restNonce' => wp_create_nonce( 'wp_rest' ),
'version' => SUBTLEFORMS_VERSION,
'unreadCount' => $this->get_unread_count(),
// Every entry, for the Submissions badge in the plugin navigation.
'totalCount' => self::total_count(),
'capabilities' => $live_caps->all(),
'hasProPlugin' => self::companion_active(),
'knownFieldTypes' => \SubtleForms\Fields\FieldTypeAvailability::knownTypes(),
// What the builder needs to know about add-on field types (2.7.2).
'fieldTypeFlags' => (object) \SubtleForms\Fields\FieldTypeAvailability::typeFlags(),
// Features an active add-on provides (see Support\ExtensionPoints).
'addonFeatures' => \SubtleForms\Support\ExtensionPoints::provided(),
// The More features card on the Dashboard (see more_features()).
'moreFeatures' => self::more_features(),
// Cloudflare is in front of the site and the setting is off (2.8.1).
'cloudflareNotice' => self::cloudflare_notice(),
// Today in the site's time zone (Y-m-d), the end of the Reports date range.
'siteToday' => wp_date( 'Y-m-d' ),
// Settings > General formats, for date fields set to the site format (2.9.0).
'dateFormat' => (string) get_option( 'date_format', 'F j, Y' ),
'timeFormat' => (string) get_option( 'time_format', 'g:i a' ),
'timezone' => wp_timezone_string(),
// The Pro page on subtleforms.com, for the Upgrade page.
// Addresses of the admin screens that connection instructions link to (2.8.1).
'adminUrls' => array(
'forms' => admin_url( 'admin.php?page=subtleforms-forms' ),
'newForm' => admin_url( 'admin.php?page=subtleforms-new-form' ),
'entries' => admin_url( 'admin.php?page=subtleforms-submissions' ),
'settings' => admin_url( 'admin.php?page=subtleforms-settings' ),
'plugins' => admin_url( 'plugins.php' ),
),
'extensions' => $this->buildExtensionsData(),
// Email marketing: the services, who adds extras to them and the Pro note.
'emailMarketing' => self::email_marketing_data(),
// CRM: the services, who adds extras to them and the Pro note.
'crm' => self::crm_data(),
'isDev' => defined( 'WP_DEBUG' ) && WP_DEBUG,
// The builder preview renders the real frontend markup inside an
// iframe, so it needs the public stylesheet to look like production
// rather than approximating it with admin styles.
'frontendStyles' => array_values(
array_filter(
array(
file_exists( SUBTLEFORMS_PLUGIN_DIR . 'build/frontend/index.jsx.css' )
? add_query_arg(
'ver',
(string) filemtime( SUBTLEFORMS_PLUGIN_DIR . 'build/frontend/index.jsx.css' ),
SUBTLEFORMS_PLUGIN_URL . 'build/frontend/index.jsx.css'
)
: null,
file_exists( SUBTLEFORMS_PLUGIN_DIR . 'assets/css/conversational.css' )
? SUBTLEFORMS_PLUGIN_URL . 'assets/css/conversational.css'
: null,
)
)
),
// What the page prints for a form that inherits the theme: only these
// layout lines. The preview loads the same, so the two cannot drift.
'layoutCss' => FrontendAssets::layoutCss(),
'plainTypes' => FrontendAssets::plainTypes(),
// The picker stylesheet every form with a dropdown, country, date,
// time or date and time field loads, and the types that need it (2.9.0).
'pickerCss' => file_exists( SUBTLEFORMS_PLUGIN_DIR . 'build/frontend/picker.css' )
? add_query_arg(
'ver',
(string) filemtime( SUBTLEFORMS_PLUGIN_DIR . 'build/frontend/picker.css' ),
SUBTLEFORMS_PLUGIN_URL . 'build/frontend/picker.css'
)
: '',
'pickerTypes' => FrontendAssets::pickerTypes(),
'i18n' => array(
'confirmDelete' => __( 'Are you sure you want to delete this item?', 'subtleforms' ),
'error' => __( 'An error occurred. Please try again.', 'subtleforms' ),
'success' => __( 'Action completed successfully.', 'subtleforms' ),
),
// Country flag files, for the builder canvas and the previews (2.7.2).
'flagBaseUrl' => SUBTLEFORMS_PLUGIN_URL . 'build/frontend/flags/',
// Nonce for admin download links to uploaded files (2.1).
'fileNonce' => \SubtleForms\Uploads\Uploads::nonce(),
// The streamed CSV download: its address and nonce (2.8.1).
'exportCsvUrl' => admin_url( 'admin-post.php?action=subtleforms_export_csv' ),
'exportCsvNonce' => wp_create_nonce( \SubtleForms\Api\SubmissionsApi::EXPORT_NONCE_ACTION ),
// Name, menu name and logo (2.1).
'branding' => self::branding(),
// Preview device widths and the active theme's styles, so "inherit
// from theme" and desktop/tablet/mobile match the site (2.3.5).
'previewBreakpoints' => \SubtleForms\Support\Appearance::previewBreakpoints( self::themeJsonSettings() ),
'themeStylesheets' => self::themeStylesheets(),
'themeGlobalCss' => function_exists( 'wp_get_global_stylesheet' ) ? wp_get_global_stylesheet() : '',
'themeFontFaces' => self::themeFontFaces(),
// Submissions inbox. A personal choice wins; otherwise these are the site defaults.
'submissionsView' => ( new Settings() )->resolvedInboxView( get_current_user_id() ),
// REST answers sent with the page, served to apiFetch before the
// app renders (see AdminPreload and the subtleforms/admin/preload_paths filter).
'preloaded' => (object) AdminPreload::collect( AdminPreload::currentScreen() ),
);
/**
* Filter the data the admin app receives as `window.subtleformsAdmin`.
* Add-ons add their own keys here.
*
* @param array $admin_data Data.
* @param string $hook Admin page hook.
* @since 2.1.0
*/
$admin_data = (array) apply_filters( 'subtleforms/admin_data', $admin_data, $hook );
// Localize script with data
wp_localize_script( 'subtleforms-admin', 'subtleformsAdmin', $admin_data );
wp_set_script_translations( 'subtleforms-admin', 'subtleforms', SUBTLEFORMS_PLUGIN_DIR . 'languages' );
// Additional data for Settings page
wp_localize_script(
'subtleforms-admin',
'subtleformsData',
array(
'siteName' => get_option( 'blogname' ),
'adminEmail' => get_option( 'admin_email' ),
'siteDomain' => $this->get_site_domain(),
)
);
// Allow extensions to enqueue their assets
do_action( 'subtleforms/admin_enqueue_scripts', $hook );
}
/**
* theme.json settings for the active theme, or an empty array.
*
* @return array
*/
private static function themeJsonSettings(): array {
if ( ! class_exists( '\WP_Theme_JSON_Resolver' ) ) {
return array();
}
$data = \WP_Theme_JSON_Resolver::get_merged_data( 'theme' );
if ( ! is_object( $data ) || ! method_exists( $data, 'get_settings' ) ) {
return array();
}
$settings = $data->get_settings();
return is_array( $settings ) ? $settings : array();
}
/**
* Stylesheet URLs for the active theme. Global styles are passed separately
* through wp_get_global_stylesheet(). This does not run front-end hooks.
*
* @return string[]
*/
/**
* Font faces the front end prints, so the builder preview can use them.
*
* @return string
*/
public static function themeFontFaces(): string {
return \SubtleForms\Support\ThemeStyles::fontFaceCss();
}
private static function themeStylesheets(): array {
$hrefs = array();
if ( function_exists( 'is_child_theme' ) && is_child_theme() && function_exists( 'get_template_directory_uri' ) ) {
$hrefs[] = get_template_directory_uri() . '/style.css';
}
if ( function_exists( 'get_stylesheet_uri' ) ) {
$child = get_stylesheet_uri();
if ( is_string( $child ) && '' !== $child && ! in_array( $child, $hrefs, true ) ) {
$hrefs[] = $child;
}
}
return $hrefs;
}
/**
* How the admin app names the plugin: name, menu name and logo.
*
* @return array{name:string,menuName:string,logoUrl:string,menuIcon:string,markSvg:string}
*/
public static function branding(): array {
static $cache = null;
if ( $cache !== null && ! ( defined( 'SUBTLEFORMS_TESTING' ) && SUBTLEFORMS_TESTING ) ) {
return $cache;
}
$defaults = array(
'name' => 'SubtleForms',
'menuName' => __( 'SubtleForms', 'subtleforms' ),
'logoUrl' => '',
'menuIcon' => '',
'markSvg' => '',
);
/**
* Filter how the admin app names the plugin.
*
* @param array $branding {
* @type string $name Product name in the app header and copy.
* @type string $menuName wp-admin menu label.
* @type string $logoUrl Logo image URL; empty for the default mark.
* @type string $menuIcon Menu icon: a data URI (data:image/svg+xml;base64,...) or an image URL;
* empty for the default mark. A data URI is repainted by core in the admin
* colour scheme; an image URL is drawn as it is.
* @type string $markSvg Inline SVG (svg, g and path only) that replaces the built-in mark in the
* app header; empty for the default mark. A logoUrl still wins over it.
* }
* @since 2.1.0
*/
$b = apply_filters( 'subtleforms/admin_branding', $defaults );
$b = is_array( $b ) ? array_merge( $defaults, $b ) : $defaults;
$name = trim( wp_strip_all_tags( (string) $b['name'] ) );
$menu = trim( wp_strip_all_tags( (string) $b['menuName'] ) );
$cache = array(
'name' => $name !== '' ? $name : $defaults['name'],
'menuName' => $menu !== '' ? $menu : ( $name !== '' && $name !== $defaults['name'] ? $name : $defaults['menuName'] ),
'logoUrl' => esc_url_raw( (string) $b['logoUrl'] ),
'menuIcon' => self::sanitize_menu_icon( $b['menuIcon'] ),
'markSvg' => self::sanitize_mark_svg( $b['markSvg'] ),
);
return $cache;
}
/**
* User meta key that remembers a dismissed More features card.
*/
public const MORE_FEATURES_META = 'subtleforms_more_features_dismissed';
/**
* User meta that remembers the Cloudflare notice was dismissed.
*/
public const CLOUDFLARE_NOTICE_META = 'subtleforms_cloudflare_notice_dismissed';
/**
* Product page the More features card links to.
*/
public const MORE_FEATURES_URL = 'https://subtleforms.com/pro/';
/**
* Whether the companion add-on from the SubtleForms team is active. Used
* only to leave out the More features card, never to switch code on or off.
*
* @return bool
*/
public static function companion_active(): bool {
return defined( 'SUBTLEFORMS_PRO_VERSION' ) || ( function_exists( 'subtleforms_is_pro_active' ) && subtleforms_is_pro_active() );
}
/**
* The More features card on the Dashboard: the one place in this plugin
* that says what the separate add-on adds. Shown to people who can manage
* SubtleForms until they dismiss it
* or the add-on is already active.
*
* @return array{show:bool,url:string}
*/
public static function more_features(): array {
$user_id = get_current_user_id();
$dismissed = $user_id > 0 && (bool) get_user_meta( $user_id, self::MORE_FEATURES_META, true );
$show = ! $dismissed && ! self::companion_active();
return array(
'show' => $show,
'url' => self::MORE_FEATURES_URL,
);
}
/**
* Whether Security & privacy shows the Cloudflare notice: this request
* came through Cloudflare, the "Site is behind Cloudflare" setting is off
* and this user has not dismissed it.
*
* @return bool
*/
public static function cloudflare_notice(): bool {
$user_id = get_current_user_id();
if ( $user_id <= 0 || get_user_meta( $user_id, self::CLOUDFLARE_NOTICE_META, true ) ) {
return false;
}
$settings = get_option( 'subtleforms_settings', array() );
if ( is_array( $settings ) && ! empty( $settings['trust_cloudflare'] ) ) {
return false;
}
return \SubtleForms\Security\ClientIp::cloudflare_detected();
}
/**
* What the Email marketing screens need beside the integration list.
*
* `services` lists every service (this plugin's and an add-on's) with its
* switch and whether it is connected. `extras` names the services an add-on
* adds options to. `banner.show` is false for a user who dismissed the
* note about SubtleForms Pro and while an add-on adds extras.
*
* @return array{services:array,extras:string[],banner:array{show:bool,url:string}}
*/
public static function email_marketing_data(): array {
$extras = \SubtleForms\Integrations\EmailMarketing\Services::extras();
$dismissed = \SubtleForms\Api\EmailMarketingApi::bannerDismissed( get_current_user_id() );
return array(
'services' => (object) \SubtleForms\Integrations\EmailMarketing\Services::all(),
'extras' => $extras,
'banner' => array(
'show' => ! $dismissed && array() === $extras,
'url' => self::MORE_FEATURES_URL,
),
);
}
/**
* What the CRM screens need beside the integration list; the same shape as
* email_marketing_data(). Services are listed with their switch and whether
* they are connected, `extras` names the services an add-on adds options
* to, and `banner.show` is false for a user who dismissed the note about
* SubtleForms Pro and while an add-on adds extras.
*
* @return array{services:object,extras:string[],banner:array{show:bool,url:string}}
*/
public static function crm_data(): array {
$extras = \SubtleForms\Integrations\Crm\Services::extras();
$dismissed = \SubtleForms\Api\CrmApi::bannerDismissed( get_current_user_id() );
return array(
'services' => (object) \SubtleForms\Integrations\Crm\Services::all(),
'extras' => $extras,
'banner' => array(
'show' => ! $dismissed && array() === $extras,
'url' => self::MORE_FEATURES_URL,
),
);
}
/**
* The integrations the Settings screen lists.
*
* Webhooks, Email marketing and CRM are part of this plugin. Any other
* integration comes from an add-on, which adds its entry through the
* `subtleforms/admin/integrations` filter (see Integrations\Registry).
*
* @return array Map of slug to { slug, label, description,
* available, enabled, configured }.
*/
private function buildExtensionsData(): array {
return \SubtleForms\Integrations\Registry::all();
}
private function is_builder_screen( string $hook ): bool {
$hook = Helpers::normalize_string( $hook );
if ( strpos( $hook, 'subtleforms-new-form' ) !== false ) {
return true;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check for admin screen routing.
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
return $page === 'subtleforms-new-form';
}
public function filter_admin_body_class( $classes ) {
// Handle different input types (string or array)
if ( is_array( $classes ) ) {
$classes = implode( ' ', $classes );
} elseif ( ! is_string( $classes ) || $classes === null ) {
$classes = '';
}
// Ensure $classes is never null
$classes = (string) $classes;
if ( $this->is_builder_screen( $this->currentPage ?: '' ) ) {
$classes .= ' subtleforms-builder-page';
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin page slug; no form data processed.
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
// Every SubtleForms screen renders inside the app frame. The class is
// printed server-side so the frame layout applies before React mounts.
if ( $page === 'subtleforms' || strpos( $page, 'subtleforms-' ) === 0 ) {
$classes .= ' subtleforms-admin-page subtleforms-admin-scope';
}
if ( $page === 'subtleforms-new-form' && strpos( Helpers::normalize_string( $classes ), 'subtleforms-builder-page' ) === false ) {
$classes .= ' subtleforms-builder-page';
}
return trim( $classes );
}
/**
* Whether a SubtleForms admin action nonce is valid.
*
* Sanitizes the same way as Uploads::download before wp_verify_nonce().
*
* @param mixed $nonce Raw `_wpnonce` value (typically from $_GET).
*/
public static function actionNonceValid( $nonce ): bool {
if ( null === $nonce || false === $nonce || is_array( $nonce ) || is_object( $nonce ) ) {
return false;
}
$clean = sanitize_text_field( wp_unslash( (string) $nonce ) );
return '' !== $clean && false !== wp_verify_nonce( $clean, 'subtleforms_action' );
}
/**
* Handle admin actions (delete, duplicate, etc.).
*/
public function handle_actions(): void {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified below via actionNonceValid() before any state change.
if ( ! isset( $_GET['action'] ) ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Action key read for routing only; nonce verified below before processing.
$action = sanitize_key( Helpers::safe_string_get( $_GET, 'action' ) );
// Only handle SubtleForms-specific admin actions here.
$allowed = array(
'delete_form',
'duplicate_form',
'delete_submission',
);
if ( ! in_array( $action, $allowed, true ) ) {
return;
}
// For our actions, require nonce and validate it (same pattern as Uploads).
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- This reads the nonce itself; actionNonceValid() verifies it on the next line.
$nonce = isset( $_GET['_wpnonce'] )
? sanitize_text_field( wp_unslash( (string) $_GET['_wpnonce'] ) )
: null;
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ( ! self::actionNonceValid( $nonce ) ) {
wp_die( esc_html__( 'Security check failed.', 'subtleforms' ) );
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified above.
$id = isset( $_GET['id'] ) ? intval( $_GET['id'] ) : 0;
switch ( $action ) {
case 'delete_form':
$this->handle_delete_form( $id );
break;
case 'duplicate_form':
$this->handle_duplicate_form( $id );
break;
case 'delete_submission':
$this->handle_delete_submission( $id );
break;
}
}
/**
* Render dashboard page.
*/
public function render_dashboard(): void {
if ( ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'subtleforms' ) );
}
$stats = $this->get_dashboard_stats();
$this->get_template( 'dashboard', $stats );
}
/**
* Render forms list page.
*/
public function render_forms(): void {
if ( ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'subtleforms' ) );
}
$forms = $this->formsRepo->all(
array(
'limit' => 50,
'orderby' => 'updated_at',
'order' => 'DESC',
)
);
$this->get_template( 'forms-list', array( 'forms' => $forms ) );
}
/**
* Render new form page.
*/
public function render_new_form(): void {
if ( ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'subtleforms' ) );
}
// Check if editing an existing form
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin URL param; nonce verified separately for write actions.
$formId = isset( $_GET['form_id'] ) ? intval( $_GET['form_id'] ) : null;
$form = null;
if ( $formId ) {
$form = $this->formsRepo->find( $formId );
if ( ! $form ) {
wp_die( esc_html__( 'Form not found.', 'subtleforms' ) );
}
}
$this->get_template( 'form-editor', array( 'form' => $form ) );
}
/**
* Render submissions page.
*/
public function render_submissions(): void {
if ( ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'subtleforms' ) );
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL param for filter display, not processing form data.
$formId = isset( $_GET['form_id'] ) ? intval( $_GET['form_id'] ) : null;
$submissions = $formId
? $this->submissionsRepo->findByForm( $formId, array( 'limit' => 50 ) )
: array();
$forms = $this->formsRepo->all( array( 'limit' => 100 ) );
$this->get_template(
'submissions-list',
array(
'submissions' => $submissions,
'forms' => $forms,
'currentFormId' => $formId,
)
);
}
/**
* Where the old Tools screen went.
*
* Tools is a tab of Settings now. The old URL, admin.php?page=subtleforms-tools,
* still works: it opens Settings on that tab, so bookmarks and links from
* add-ons keep working. The three logs (activity, webhooks and API) moved
* on to the Logs tab, so a link to one of them opens that section there.
*
* @param string $section Section named in the old link, if any.
* @return string Admin URL of the Settings tab that now holds it.
*/
public static function tools_tab_url( string $section = '' ): string {
$base = admin_url( 'admin.php?page=subtleforms-settings' );
if ( in_array( $section, array( 'activity', 'webhooks', 'api' ), true ) ) {
return $base . '#tab=logs§ion=' . $section;
}
if ( in_array( $section, array( 'transfer', 'migrate' ), true ) ) {
return $base . '#tab=tools§ion=' . $section;
}
return $base . '#tab=tools';
}
/**
* Send the old Tools URL to the Tools tab of Settings.
*/
public function redirect_legacy_pages(): void {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the page slug of a navigation request.
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
if ( 'subtleforms-tools' !== $page || ! current_user_can( $this->caps->manage_cap() ) ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the section of a navigation request.
$section = isset( $_GET['section'] ) ? sanitize_key( wp_unslash( $_GET['section'] ) ) : '';
wp_safe_redirect( self::tools_tab_url( $section ) );
exit;
}
/**
* Render reports page.
*/
public function render_reports(): void {
if ( ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'subtleforms' ) );
}
$this->get_template( 'reports' );
}
/**
* Render settings page.
*/
public function render_settings(): void {
if ( ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'You do not have permission to access this page.', 'subtleforms' ) );
}
$this->get_template( 'settings' );
}
/**
* Get dashboard statistics.
*/
private function get_dashboard_stats(): array {
return array(
'total_forms' => $this->formsRepo->count(),
'active_forms' => $this->formsRepo->count( array( 'status' => 'published' ) ),
'draft_forms' => $this->formsRepo->count( array( 'status' => 'draft' ) ),
'total_submissions' => $this->submissionsRepo->count(),
'recent_submissions' => $this->submissionsRepo->count(
array(
'status' => 'completed',
)
),
);
}
/**
* Handle form deletion.
*/
private function handle_delete_form( int $id ): void {
if ( ! $id || ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'Invalid request.', 'subtleforms' ) );
}
$this->formsRepo->delete( $id );
wp_safe_redirect(
add_query_arg(
array(
'page' => 'subtleforms-forms',
'message' => 'deleted',
),
admin_url( 'admin.php' )
)
);
exit;
}
/**
* Handle form duplication.
*/
private function handle_duplicate_form( int $id ): void {
if ( ! $id || ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'Invalid request.', 'subtleforms' ) );
}
$form = $this->formsRepo->find( $id );
if ( ! $form ) {
wp_die( esc_html__( 'Form not found.', 'subtleforms' ) );
}
$newId = $this->formsRepo->create(
array(
'title' => $form['title'] . ' (Copy)',
'config' => $form['config'],
'status' => 'draft',
)
);
wp_safe_redirect(
add_query_arg(
array(
'page' => 'subtleforms-forms',
'message' => 'duplicated',
),
admin_url( 'admin.php' )
)
);
exit;
}
/**
* Handle submission deletion.
*/
private function handle_delete_submission( int $id ): void {
if ( ! $id || ! current_user_can( $this->caps->manage_cap() ) ) {
wp_die( esc_html__( 'Invalid request.', 'subtleforms' ) );
}
$this->submissionsRepo->delete( $id );
wp_safe_redirect(
add_query_arg(
array(
'page' => 'subtleforms-submissions',
'message' => 'deleted',
),
admin_url( 'admin.php' )
)
);
exit;
}
/**
* Include an admin template.
*/
private function get_template( string $name, array $data = array() ): void {
$templatePath = SUBTLEFORMS_PLUGIN_DIR . 'templates/admin/' . $name . '.php';
if ( file_exists( $templatePath ) ) {
// $data is available to the template via the local scope.
include $templatePath;
return;
}
wp_die( esc_html__( 'This screen could not be loaded.', 'subtleforms' ) );
}
/**
* Filter admin title to ensure proper titles for SubtleForms pages.
*/
public function filter_admin_title( $admin_title, $title ): string {
// Ensure both parameters are strings to prevent deprecation warnings
$admin_title = Helpers::normalize_string( $admin_title );
$title = Helpers::normalize_string( $title );
// If both are empty, provide a fallback for SubtleForms pages
if ( empty( $title ) && empty( $admin_title ) ) {
$current_screen = get_current_screen();
if ( $current_screen && isset( $current_screen->id ) ) {
$screen_id = Helpers::normalize_string( $current_screen->id );
if ( ! empty( $screen_id ) && strpos( $screen_id, 'subtleforms' ) !== false ) {
return self::branding()['menuName'] . ' — WordPress';
}
}
return __( 'WordPress Admin', 'subtleforms' );
}
// Return admin_title if title is empty, otherwise return admin_title (or fallback)
if ( empty( $title ) ) {
return ! empty( $admin_title ) ? $admin_title : __( 'WordPress Admin', 'subtleforms' );
}
return ! empty( $admin_title ) ? $admin_title : $title;
}
/**
* Fix admin global variables to prevent null deprecation warnings.
*/
public function fix_admin_globals(): void {
global $title, $parent_file, $submenu_file;
// Ensure $title is never null using Helpers
if ( $title === null || $title === '' ) {
$current_screen = get_current_screen();
if ( $current_screen && isset( $current_screen->id ) ) {
$screen_id = Helpers::normalize_string( $current_screen->id );
if ( ! empty( $screen_id ) && strpos( $screen_id, 'subtleforms' ) !== false ) {
$title = __( 'SubtleForms', 'subtleforms' );
} else {
$title = '';
}
} else {
$title = '';
}
} else {
// Always ensure $title is a string
$title = Helpers::normalize_string( $title );
}
// Ensure other globals are strings
if ( $parent_file === null ) {
$parent_file = '';
} else {
$parent_file = Helpers::normalize_string( $parent_file );
}
if ( $submenu_file === null ) {
$submenu_file = '';
} else {
$submenu_file = Helpers::normalize_string( $submenu_file );
}
}
/**
* Fix parent_file to ensure correct top-level menu highlighting.
*
* WordPress needs parent_file to match the top-level menu slug
* for all SubtleForms admin pages.
*
* @param string $parent_file The current parent file.
* @return string The corrected parent file.
*/
public function fix_parent_file( $parent_file ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check for admin screen routing.
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
// For all SubtleForms pages, ensure parent is 'subtleforms'
if ( ! empty( $page ) && strpos( $page, 'subtleforms' ) === 0 ) {
return 'subtleforms';
}
return $parent_file;
}
/**
* Fix submenu_file to ensure correct submenu highlighting.
*
* This tells WordPress which submenu item should be highlighted as active.
* The dashboard page uses 'subtleforms' (same as parent), which WordPress
* auto-converts to the first submenu item.
*
* @param string $submenu_file The current submenu file.
* @return string The corrected submenu file.
*/
public function fix_submenu_file( $submenu_file ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check for admin screen routing.
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
if ( empty( $page ) ) {
return $submenu_file;
}
// Map each page to its correct submenu slug
// Dashboard uses the parent slug, which WordPress highlights as first submenu
if ( $page === 'subtleforms' ) {
return 'subtleforms';
}
// The builder reuses the "Add New" slug (subtleforms-new-form) for both
// creating and editing. When a form_id is present we are editing an
// existing form, so highlight "All Forms" (where the user came from)
// rather than "Add New" (Part B18).
if ( $page === 'subtleforms-new-form' ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check for admin menu highlighting.
$form_id = isset( $_GET['form_id'] ) ? sanitize_key( wp_unslash( $_GET['form_id'] ) ) : '';
if ( ! empty( $form_id ) ) {
return 'subtleforms-forms';
}
return 'subtleforms-new-form';
}
// All other pages should highlight themselves
if ( strpos( $page, 'subtleforms' ) === 0 ) {
return $page;
}
return $submenu_file;
}
}