key => { max length, more than * one line, required (an empty one is the template's) }. */ const WORDS = array( 'content' => array( 'label' => array( 200, false, false ), 'heading' => array( 200, false, true ), 'text' => array( 500, true, false ), 'button' => array( 200, false, true ), 'placeholder' => array( 200, false, true ), 'proof' => array( 200, false, false ), 'consent' => array( 500, false, false ), 'signature' => array( 80, false, false ), // The tracking box's words; empty = the site's (Mailpuff_Tracking_Consent::label()). 'tracking' => array( 200, false, true ), ), 'after' => array( 'heading' => array( 200, false, true ), 'text' => array( 500, true, false ), ), 'teaser' => array( 'text' => array( 80, false, true ), ), ); /** after.action. */ const ACTIONS = array( 'message', 'page', 'file' ); /** rules.show_on: where an overlay shows. */ const SHOW_ON = array( 'everywhere', 'posts', 'pages', 'home', 'categories', 'specific' ); /** rules.trigger: when an overlay opens. */ const TRIGGERS = array( 'delay', 'scroll', 'exit', 'click' ); /** rules.devices. */ const DEVICES = array( 'both', 'desktop', 'phone' ); /** rules.visitors. */ const VISITORS = array( 'everyone', 'new', 'returning' ); /** The longest art_text line, and how many. */ const ART_LINE = 40; const ART_LINES = 4; /** The longest code on the thank-you step. */ const CODE_LENGTH = 40; /** @var bool A model method is saving: it rebuilds the live index once itself. */ private static $quiet = false; /** @var bool The count cache was cleared this request and not filled since. */ private static $count_gone = false; /** * Hook in. Called at boot. */ public static function register() { add_action( 'init', array( __CLASS__, 'register_post_type' ) ); // A form turned on or off, trashed or deleted some other way. add_action( 'transition_post_status', array( __CLASS__, 'status_changed' ), 10, 3 ); add_action( 'deleted_post', array( __CLASS__, 'post_deleted' ), 10, 2 ); add_action( 'mailpuff_erase_all', array( __CLASS__, 'forget_live' ) ); // The {count} number moves when people come, go or change status. foreach ( array( 'mailpuff_contact_created', 'mailpuff_contact_status_changed', 'mailpuff_contact_deleted' ) as $hook ) { add_action( $hook, array( __CLASS__, 'forget_count' ), 10, 0 ); } } /** * The private post type. No screens of WordPress's own: the Forms section * draws them. */ public static function register_post_type() { register_post_type( self::POST_TYPE, array( 'labels' => array( 'name' => __( 'Signup forms', 'mailpuff' ), 'singular_name' => __( 'Signup form', 'mailpuff' ), ), 'public' => false, 'show_ui' => false, 'show_in_rest' => false, 'exclude_from_search' => true, 'publicly_queryable' => false, 'query_var' => false, 'rewrite' => false, 'can_export' => true, 'delete_with_user' => false, 'supports' => array( 'title' ), ) ); } /** * The type's names, for screens and tools. * * @return array */ public static function type_labels() { return array( 'inline' => __( 'Inline', 'mailpuff' ), 'popup' => __( 'Pop-up', 'mailpuff' ), 'slide_in' => __( 'Slide-in', 'mailpuff' ), 'bar' => __( 'Bar', 'mailpuff' ), 'below_post' => __( 'Below posts', 'mailpuff' ), ); } /* Settings -------------------------------------------------------------- */ /** * A new form's settings for a type and template. Every text is null: the * template's own words. * * @param string $type One of TYPES. * @param string $template A template id; unknown is plain. * @return array */ public static function defaults( $type = 'inline', $template = Mailpuff_Form_Templates::FALLBACK ) { return array( 'template' => Mailpuff_Form_Templates::exists( $template ) ? $template : Mailpuff_Form_Templates::FALLBACK, 'design' => array( 'layout' => '', 'image' => array( 'id' => 0, 'url' => '', 'alt' => '', ), 'art_text' => null, 'colors' => array( 'background' => '', 'text' => '', 'button' => '', 'button_text' => '', ), 'font' => 'template', 'corners' => 'template', 'edge' => 'template', 'size' => 'm', 'backdrop' => array( 'dim' => 45, 'blur' => false, ), 'animation' => 'rise', 'phone' => array( 'as' => 'sheet', 'image' => true, ), ), 'content' => array( 'label' => null, 'heading' => null, 'text' => null, 'button' => null, 'placeholder' => null, 'proof' => null, 'consent' => null, 'signature' => null, 'tracking' => null, 'hide' => array(), 'fields' => null, ), 'after' => array( 'action' => 'message', 'heading' => null, 'text' => null, 'url' => '', 'file' => array( 'id' => 0, 'url' => '', 'name' => '', ), 'code' => '', 'tags' => array(), ), 'teaser' => array( 'on' => true, 'text' => null, ), 'rules' => array( 'show_on' => 'everywhere', 'page_ids' => array(), 'categories' => array(), 'trigger' => 'delay', // A pop-up waits longer than a corner box or a bar. 'delay' => 'popup' === $type ? 15 : 8, 'scroll' => 50, 'devices' => 'both', 'visitors' => 'everyone', 'hide_days' => 30, 'start' => '', 'end' => '', 'post_types' => array( 'post' ), ), 'embed_domains' => array(), ); } /** * Settings made safe and complete, all the way down: unknown keys dropped, * every enum, range and length checked, the rest from the type's * defaults. A null text stays null (the template's words). * * @param array $config Settings, maybe partial. * @param string $type One of TYPES. * @return array */ public static function normalize( array $config, $type ) { $type = in_array( $type, self::TYPES, true ) ? $type : 'inline'; $template = is_string( $config['template'] ?? null ) ? $config['template'] : ''; $out = self::defaults( $type, $template ); $design = self::group( $config, 'design' ); $colors = self::group( $design, 'colors' ); $backdrop = self::group( $design, 'backdrop' ); $phone = self::group( $design, 'phone' ); $d = $out['design']; $out['design'] = array( 'layout' => self::pick( $design['layout'] ?? null, self::LAYOUTS, $d['layout'] ), 'image' => self::image( self::group( $design, 'image' ) ), 'art_text' => self::art_text( $design['art_text'] ?? null ), 'colors' => array(), 'font' => self::pick( $design['font'] ?? null, self::FONTS, $d['font'] ), 'corners' => self::pick( $design['corners'] ?? null, self::CORNERS, $d['corners'] ), 'edge' => self::pick( $design['edge'] ?? null, self::EDGES, $d['edge'] ), 'size' => self::pick( $design['size'] ?? null, self::SIZES, $d['size'] ), 'backdrop' => array( 'dim' => self::range( $backdrop['dim'] ?? null, 0, 80, $d['backdrop']['dim'] ), 'blur' => self::flag( $backdrop['blur'] ?? $d['backdrop']['blur'] ), ), 'animation' => self::pick( $design['animation'] ?? null, self::ANIMATIONS, $d['animation'] ), 'phone' => array( 'as' => self::pick( $phone['as'] ?? null, self::PHONE_LOOKS, $d['phone']['as'] ), 'image' => self::flag( $phone['image'] ?? $d['phone']['image'] ), ), ); foreach ( Mailpuff_Form_Templates::COLORS as $key ) { $out['design']['colors'][ $key ] = is_string( $colors[ $key ] ?? null ) ? (string) sanitize_hex_color( $colors[ $key ] ) : ''; } foreach ( self::WORDS as $group => $keys ) { $given = self::group( $config, $group ); foreach ( $keys as $key => $rule ) { $out[ $group ][ $key ] = self::words( $given[ $key ] ?? null, $rule[0], $rule[1], $rule[2] ); } } $content = self::group( $config, 'content' ); $out['content']['hide'] = array_values( array_intersect( self::HIDEABLE, self::strings( $content['hide'] ?? array() ) ) ); $out['content']['fields'] = self::fields( $content['fields'] ?? null ); $after = self::group( $config, 'after' ); $out['after']['action'] = self::pick( $after['action'] ?? null, self::ACTIONS, 'message' ); $out['after']['url'] = self::url( $after['url'] ?? '' ); $out['after']['file'] = self::file( self::group( $after, 'file' ) ); $out['after']['code'] = is_scalar( $after['code'] ?? null ) ? mb_substr( sanitize_text_field( (string) $after['code'] ), 0, self::CODE_LENGTH ) : ''; $out['after']['tags'] = Mailpuff_Subscription::only_public_groups( self::id_list( $after['tags'] ?? array() ) ); $teaser = self::group( $config, 'teaser' ); $out['teaser']['on'] = self::flag( $teaser['on'] ?? $out['teaser']['on'] ); $rules = self::group( $config, 'rules' ); $r = $out['rules']; $post_types = array_values( array_intersect( array( 'post', 'page' ), self::strings( $rules['post_types'] ?? array() ) ) ); $out['rules'] = array( 'show_on' => self::pick( $rules['show_on'] ?? null, self::SHOW_ON, $r['show_on'] ), 'page_ids' => self::id_list( $rules['page_ids'] ?? array() ), 'categories' => self::id_list( $rules['categories'] ?? array() ), 'trigger' => self::pick( $rules['trigger'] ?? null, self::TRIGGERS, $r['trigger'] ), 'delay' => self::range( $rules['delay'] ?? null, 0, 600, $r['delay'] ), 'scroll' => self::range( $rules['scroll'] ?? null, 10, 100, $r['scroll'] ), 'devices' => self::pick( $rules['devices'] ?? null, self::DEVICES, $r['devices'] ), 'visitors' => self::pick( $rules['visitors'] ?? null, self::VISITORS, $r['visitors'] ), 'hide_days' => self::range( $rules['hide_days'] ?? null, 1, 365, $r['hide_days'] ), 'start' => self::date( $rules['start'] ?? '' ), 'end' => self::date( $rules['end'] ?? '' ), 'post_types' => $post_types ? $post_types : $r['post_types'], ); $out['embed_domains'] = Mailpuff_Form_Embed::hosts_in( is_array( $config['embed_domains'] ?? null ) || is_string( $config['embed_domains'] ?? null ) ? $config['embed_domains'] : array() ); return $out; } /** * Changes deep-merged into settings: objects merge key by key, lists and * plain values are replaced whole, unknown keys are dropped. Giving a * Media library item a new `id` or `url` replaces the item (its other * address, description and name start again). * * @param array $config Settings, from normalize(). * @param array $changes Some settings. * @return array Not normalized yet. */ public static function merge( array $config, array $changes ) { return self::merge_into( $config, $changes, self::defaults() ); } /** * @param array $base What is there. * @param array $changes What changes. * @param array $shape The defaults at this level: which keys are objects. * @return array */ private static function merge_into( array $base, array $changes, array $shape ) { foreach ( $changes as $key => $value ) { if ( ! is_string( $key ) || ! array_key_exists( $key, $shape ) ) { continue; } $default = $shape[ $key ]; if ( ! is_array( $default ) || ! $default || array_is_list( $default ) || ! is_array( $value ) ) { $base[ $key ] = $value; continue; } $current = isset( $base[ $key ] ) && is_array( $base[ $key ] ) ? $base[ $key ] : $default; if ( isset( $default['id'], $default['url'] ) && ( array_key_exists( 'id', $value ) || array_key_exists( 'url', $value ) ) ) { $current = $default; } $base[ $key ] = self::merge_into( $current, $value, $default ); } return $base; } /** * What a form shows once the template fills what its own settings leave * empty: its words, fields, layout, colours and art lines. * * @param array $config Settings, from normalize(). * @return array{template:array,words:array,fields:string[],layout:string,colors:array,art_text:string[]} */ public static function resolved( array $config ) { $template = Mailpuff_Form_Templates::get( (string) ( $config['template'] ?? '' ) ); $copy = $template['copy']; // The tracking box asks in the site's words, not a template's. $copy['tracking'] = Mailpuff_Tracking_Consent::label(); $words = array(); foreach ( array_keys( self::WORDS['content'] ) as $key ) { $words[ $key ] = $config['content'][ $key ] ?? $copy[ $key ]; } $words['thanks_heading'] = $config['after']['heading'] ?? $copy['thanks_heading']; $words['thanks_text'] = $config['after']['text'] ?? $copy['thanks_text']; $words['teaser'] = $config['teaser']['text'] ?? $copy['teaser']; $colors = array(); foreach ( Mailpuff_Form_Templates::COLORS as $key ) { $own = (string) ( $config['design']['colors'][ $key ] ?? '' ); $colors[ $key ] = '' !== $own ? $own : $template['palettes'][0][ $key ]; } $layout = (string) ( $config['design']['layout'] ?? '' ); return array( 'template' => $template, 'words' => $words, 'fields' => self::fields( $config['content']['fields'] ?? null ) ?? (array) self::fields( $template['fields'] ), 'layout' => '' !== $layout ? $layout : $template['layout'], 'colors' => $colors, 'art_text' => $config['design']['art_text'] ?? $template['art_text'], ); } /** * The one JSON Schema for a form's settings (REST, the create-form and * update-form tools, docs). It says what each option looks like, for * people and AI apps alike. * * @return array */ public static function schema() { $text = static function ( $max, $description ) { return array( 'type' => array( 'string', 'null' ), 'maxLength' => $max, 'description' => $description, ); }; $enum = static function ( array $values, $description ) { return array( 'type' => 'string', 'enum' => $values, 'description' => $description, ); }; $object = static function ( array $properties, $description = '' ) { $schema = array( 'type' => 'object', 'additionalProperties' => false, 'properties' => $properties, ); if ( '' !== $description ) { $schema['description'] = $description; } return $schema; }; $color = array( 'type' => 'string', 'pattern' => '^(#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6})?$', ); $ids = static function ( $description ) { return array( 'type' => 'array', 'items' => array( 'type' => 'integer', 'minimum' => 1, ), 'description' => $description, ); }; $date = array( 'type' => 'string', 'pattern' => '^(\d{4}-\d{2}-\d{2})?$', 'description' => 'A date as Y-m-d in the site\'s time zone, or "" for none.', ); $fields = array_merge( array( 'email' ), self::NAME_FIELDS, wp_list_pluck( Mailpuff_Fields::all(), 'key' ) ); $num = static function ( $min, $max, $description ) { return array( 'type' => 'integer', 'minimum' => $min, 'maximum' => $max, 'description' => $description, ); }; $library = array( 'type' => 'integer', 'minimum' => 0, 'description' => 'A Media library id; 0 for none.', ); $address = array( 'type' => 'string', 'description' => 'An http(s) address. One not in the Media library yet is saved there first (needs the upload_files permission).', ); return $object( array( 'template' => array( 'type' => 'string', 'enum' => Mailpuff_Form_Templates::ids(), 'description' => 'The look, from list-form-templates (unknown ids become plain). Switching template keeps every word that was written; layout, colors, font, corners and edge go back to the new template\'s unless the same change sets them.', ), 'design' => $object( array( 'layout' => $enum( self::LAYOUTS, '"" = the template\'s own. art-left / art-right: the art or image in a column beside the words; art-top: a band above them; art-behind: behind them, the words on top; no-art: words only.' ), 'image' => $object( array( 'id' => $library, 'url' => $address, 'alt' => array( 'type' => 'string', 'maxLength' => 200, 'description' => 'What the image shows, for people who cannot see it.', ), ), 'Your own image in place of the template\'s drawn art: give id, or url. id 0 and url "" = the template\'s art.' ), 'art_text' => array( 'type' => array( 'array', 'null' ), 'maxItems' => self::ART_LINES, 'items' => array( 'type' => 'string', 'maxLength' => self::ART_LINE, ), 'description' => 'Up to 4 short lines drawn inside the template\'s art (such as the date on the ticket\'s stub). null = the template\'s own.', ), 'colors' => $object( array( 'background' => $color, 'text' => $color, 'button' => $color, 'button_text' => $color, ), 'Hex colours. "" = the template\'s first palette (list-form-templates gives four per template). Keep text and button_text at 4.5:1 contrast or better; get-form checks.' ), 'font' => $enum( self::FONTS, 'template: the template\'s own fonts; theme: the site\'s; serif (Fraunces), sans (Schibsted Grotesk), mono (JetBrains Mono). The fonts ship with Mailpuff: nothing loads from Google.' ), 'corners' => $enum( self::CORNERS, 'template; sharp: square; soft: slightly rounded; round: very rounded with a pill button.' ), 'edge' => $enum( self::EDGES, 'template; none; line: a thin border; shadow: a soft shadow.' ), 'size' => $enum( self::SIZES, 'How wide: s, m or l. A pop-up with an image beside the words on l is wider than most laptop screens.' ), 'backdrop' => $object( array( 'dim' => $num( 0, 80, 'How dark the page behind a pop-up goes, in percent.' ), 'blur' => array( 'type' => 'boolean', 'description' => 'Blur the page behind a pop-up.', ), ), 'Pop-up only.' ), 'animation' => $enum( self::ANIMATIONS, 'How it opens: none, fade, rise (slides up a little) or pop (grows in).' ), 'phone' => $object( array( 'as' => $enum( self::PHONE_LOOKS, 'sheet: a panel up from the bottom; box: a small centred box; bar: a strip along the bottom.' ), 'image' => array( 'type' => 'boolean', 'description' => 'Show the art or image on phones.', ), ), 'Pop-up and slide-in on phones.' ), ) ), 'content' => $object( array( 'label' => $text( 200, 'A small line above the heading. Founder note reads "Name · Role" as an avatar.' ), 'heading' => $text( 200, 'Keep it to 60 characters or fewer so it fits on phones.' ), 'text' => $text( 500, 'The line under the heading. Receipt reads each "item | price" line as a row.' ), 'button' => $text( 200, 'The button\'s words.' ), 'placeholder' => $text( 200, 'The hint inside the email box.' ), 'proof' => $text( 200, 'The signup count line: {count} becomes the number of subscribers, such as "Join {count} readers".' ), 'consent' => $text( 500, 'A line under the form: {privacy} becomes a link to the site\'s privacy page.' ), 'signature' => $text( 80, 'The signed name the Founder note draws.' ), 'tracking' => $text( 200, 'The words beside the unticked box that asks to count opens and clicks. It shows only while Settings, Privacy counts only people who agreed. null = the site\'s question. Hide it with "tracking" in hide: people who sign up there are not counted.' ), 'hide' => array( 'type' => 'array', 'uniqueItems' => true, 'items' => array( 'type' => 'string', 'enum' => self::HIDEABLE, ), 'description' => 'Parts to leave out.', ), 'fields' => array( 'type' => array( 'array', 'null' ), 'items' => array( 'type' => 'string', 'enum' => $fields, ), 'description' => 'Boxes asked before the email, in order: first_name, last_name or a custom field key from list-fields. The email is always asked. null = the template\'s.', ), ), 'Every text: null = the template\'s own words.' ), 'after' => $object( array( 'action' => $enum( self::ACTIONS, 'After signing up: message (the thank-you step), page (opens url) or file (the thank-you step with a download of file).' ), 'heading' => $text( 200, 'The thank-you heading.' ), 'text' => $text( 500, 'The thank-you text.' ), 'url' => array( 'type' => 'string', 'description' => 'The http(s) page action page opens.', ), 'file' => $object( array( 'id' => $library, 'url' => $address, 'name' => array( 'type' => 'string', 'maxLength' => 200, 'description' => 'The name on the download link; "" for the file\'s own.', ), ), 'The file action file gives: id, or url.' ), 'code' => array( 'type' => 'string', 'maxLength' => self::CODE_LENGTH, 'description' => 'A code shown with a Copy button on the thank-you step, such as a discount code.', ), 'tags' => $ids( 'Public tag ids people who sign up here get (list-audiences); internal tags are dropped.' ), ) ), 'teaser' => $object( array( 'on' => array( 'type' => 'boolean', 'description' => 'After a visitor closes it, a small tab stays to open it again.', ), 'text' => $text( 80, 'The tab\'s words.' ), ), 'Pop-up, slide-in and bar.' ), 'rules' => $object( array( 'show_on' => $enum( self::SHOW_ON, 'Pop-up, slide-in and bar: every page, single posts, pages, the home page, posts in categories, or the pages in page_ids.' ), 'page_ids' => $ids( 'The posts and pages show_on specific means.' ), 'categories' => $ids( 'Category ids: for show_on categories, and for a below-post form only posts in them ([] = every post).' ), 'trigger' => $enum( self::TRIGGERS, 'When it opens: after delay seconds, at scroll percent of the page, when the mouse leaves the window (phones wait for the scroll instead), or only from a link to #mailpuff-.' ), 'delay' => $num( 0, 600, 'Seconds, for trigger delay.' ), 'scroll' => $num( 10, 100, 'Percent of the page, for trigger scroll.' ), 'devices' => $enum( self::DEVICES, 'both, desktop or phone.' ), 'visitors' => $enum( self::VISITORS, 'everyone; new: no visit stored from more than 30 minutes ago; returning: the others.' ), 'hide_days' => $num( 1, 365, 'Days it stays away after a visitor closes it. After a signup it never shows again.' ), 'start' => $date, 'end' => $date, 'post_types' => array( 'type' => 'array', 'items' => array( 'type' => 'string', 'enum' => array( 'post', 'page' ), ), 'description' => 'Below posts: which kinds of content.', ), ), 'Where and when it shows. People already subscribed never see a pop-up, slide-in, bar or below-post form.' ), 'embed_domains' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ), 'description' => 'Other websites (hosts such as shop.example.com; subdomains count) that may show it with its embed tag.', ), ), 'A signup form\'s settings. Send only what changes: objects merge key by key, lists replace whole.' ); } /* Images and files ------------------------------------------------------ */ /** * The Media library items in some settings resolved: an `id` checked, a * `url` matched to the library or saved into it (needs upload_files). * Each comes back with its id and address; an image without a description * takes the library's. * * @param array $config Some settings. * @return array|WP_Error */ public static function take_media( array $config ) { foreach ( array( 'design' => 'image', 'after' => 'file', ) as $group => $key ) { if ( ! isset( $config[ $group ][ $key ] ) || ! is_array( $config[ $group ][ $key ] ) ) { continue; } $media = $config[ $group ][ $key ]; $image = 'image' === $key; $id = absint( $media['id'] ?? 0 ); $url = is_scalar( $media['url'] ?? null ) ? trim( (string) $media['url'] ) : ''; if ( ! $id && '' === $url ) { continue; } $alt = is_scalar( $media['alt'] ?? null ) ? sanitize_text_field( (string) $media['alt'] ) : ''; $id = $id ? self::check_media( $id, $image ) : self::media_from_url( $url, $image, $alt ); if ( is_wp_error( $id ) ) { return $id; } $media['id'] = $id; $media['url'] = (string) wp_get_attachment_url( $id ); if ( $image && ! array_key_exists( 'alt', $media ) ) { $media['alt'] = (string) get_post_meta( $id, '_wp_attachment_image_alt', true ); } if ( ! $image && '' === trim( (string) ( $media['name'] ?? '' ) ) ) { $media['name'] = wp_basename( (string) get_attached_file( $id ) ); } $config[ $group ][ $key ] = $media; } return $config; } /** * A Media library item by id, or why it cannot be used. * * @param int $id Attachment id. * @param bool $image It must be an image. * @return int|WP_Error */ private static function check_media( $id, $image ) { $post = get_post( (int) $id ); if ( ! $post || 'attachment' !== $post->post_type ) { /* translators: %d: a Media library id. */ return new WP_Error( 'mailpuff_form_media_missing', sprintf( __( 'There is nothing with id %d in the Media library.', 'mailpuff' ), (int) $id ), array( 'status' => 400 ) ); } if ( $image && ! wp_attachment_is_image( $post ) ) { /* translators: %d: a Media library id. */ return new WP_Error( 'mailpuff_form_media_type', sprintf( __( 'Media library item %d is not an image.', 'mailpuff' ), (int) $id ), array( 'status' => 400 ) ); } if ( ! current_user_can( 'read_post', $post->ID ) ) { return new WP_Error( 'mailpuff_form_media_forbidden', __( 'You cannot use that Media library item.', 'mailpuff' ), array( 'status' => 403 ) ); } return (int) $post->ID; } /** * A web address as a Media library item: the one it already is, or a new * one Mailpuff saves it as. * * @param string $url The address. * @param bool $image It must be an image. * @param string $alt The image's description. * @return int|WP_Error */ private static function media_from_url( $url, $image, $alt ) { $clean = esc_url_raw( (string) $url, array( 'http', 'https' ) ); if ( '' === $clean || ! preg_match( '#^https?://#i', (string) $url ) ) { return new WP_Error( 'mailpuff_form_media_url', __( 'Give the address starting with https:// (or a Media library id).', 'mailpuff' ), array( 'status' => 400 ) ); } $local = attachment_url_to_postid( $clean ); if ( $local ) { return self::check_media( $local, $image ); } if ( ! current_user_can( 'upload_files' ) ) { return new WP_Error( 'mailpuff_form_media_forbidden', __( 'Saving a file into the Media library needs permission to upload files. Upload it there first and give its id.', 'mailpuff' ), array( 'status' => 403 ) ); } require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $tmp = download_url( $clean, 30 ); if ( is_wp_error( $tmp ) ) { /* translators: 1: a web address, 2: why it failed. */ return new WP_Error( 'mailpuff_form_media_download', sprintf( __( 'Mailpuff could not download %1$s: %2$s', 'mailpuff' ), $clean, $tmp->get_error_message() ), array( 'status' => 400 ) ); } if ( (int) filesize( $tmp ) > wp_max_upload_size() ) { wp_delete_file( $tmp ); return new WP_Error( 'mailpuff_form_media_size', __( 'That file is larger than this site lets you upload.', 'mailpuff' ), array( 'status' => 400 ) ); } $name = sanitize_file_name( wp_basename( (string) wp_parse_url( $clean, PHP_URL_PATH ) ) ); if ( $image ) { $mime = wp_get_image_mime( $tmp ); $exts = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp', 'image/avif' => 'avif', ); if ( ! $mime || ! isset( $exts[ $mime ] ) ) { wp_delete_file( $tmp ); return new WP_Error( 'mailpuff_form_media_type', __( 'That address is not an image (JPEG, PNG, GIF, WebP or AVIF).', 'mailpuff' ), array( 'status' => 400 ) ); } // The name carries the image's own type, so the library takes it. if ( wp_check_filetype( $name )['type'] !== $mime ) { $base = pathinfo( $name, PATHINFO_FILENAME ); $name = ( '' !== $base ? $base : 'image' ) . '.' . $exts[ $mime ]; } } $id = media_handle_sideload( array( 'name' => '' !== $name ? $name : 'file', 'tmp_name' => $tmp, ), 0 ); if ( is_wp_error( $id ) ) { wp_delete_file( $tmp ); /* translators: %s: why the Media library refused a file. */ return new WP_Error( 'mailpuff_form_media_refused', sprintf( __( 'The Media library refused that file: %s', 'mailpuff' ), $id->get_error_message() ), array( 'status' => 400 ) ); } if ( $image && '' !== $alt ) { update_post_meta( (int) $id, '_wp_attachment_image_alt', $alt ); } return (int) $id; } /* Reading --------------------------------------------------------------- */ /** * A form as screens and tools read it, or null. * * @param int|WP_Post $post Form id or post. * @return array|null { id, name, type, active, config, template, shortcode, created_at, updated_at }. */ public static function find( $post ) { $post = get_post( $post ); if ( ! $post || self::POST_TYPE !== $post->post_type || 'trash' === $post->post_status ) { return null; } $stored = get_post_meta( $post->ID, self::META, true ); $stored = is_array( $stored ) ? $stored : array(); $type = in_array( $stored['type'] ?? '', self::TYPES, true ) ? $stored['type'] : 'inline'; $config = self::normalize( (array) ( $stored['config'] ?? array() ), $type ); return array( 'id' => (int) $post->ID, 'name' => (string) $post->post_title, 'type' => $type, 'active' => 'publish' === $post->post_status, 'config' => $config, 'template' => $config['template'], 'shortcode' => '[mailpuff_form id="' . (int) $post->ID . '"]', 'created_at' => (string) $post->post_date_gmt, 'updated_at' => (string) $post->post_modified_gmt, ); } /** * Every form, newest first. * * @param array $args { type?: string|string[], active?: bool }. * @return array[] */ public static function all( array $args = array() ) { $posts = get_posts( array( 'post_type' => self::POST_TYPE, 'post_status' => isset( $args['active'] ) ? ( $args['active'] ? 'publish' : 'draft' ) : array( 'publish', 'draft' ), 'posts_per_page' => 100, 'orderby' => 'date', 'order' => 'DESC', ) ); $forms = array(); foreach ( $posts as $post ) { $form = self::find( $post ); if ( $form && ( empty( $args['type'] ) || in_array( $form['type'], (array) $args['type'], true ) ) ) { $forms[] = $form; } } return $forms; } /* Writing --------------------------------------------------------------- */ /** * Make a form. New forms start off, so nothing shows before the owner * looks at it, unless `active` says so. * * @param string $name Name. * @param string $type One of TYPES. * @param array $config Settings, maybe partial, `template` among them. * @param bool $active Show it at once. * @return int|WP_Error Form id. */ public static function create( $name, $type, array $config = array(), $active = false ) { if ( ! in_array( $type, self::TYPES, true ) ) { return self::type_error(); } $config = self::take_media( $config ); if ( is_wp_error( $config ) ) { return $config; } $config = self::normalize( $config, $type ); $name = trim( sanitize_text_field( (string) $name ) ); self::$quiet = true; $id = wp_insert_post( array( 'post_type' => self::POST_TYPE, 'post_title' => '' !== $name ? $name : self::type_labels()[ $type ], 'post_status' => $active ? 'publish' : 'draft', ), true ); if ( ! is_wp_error( $id ) ) { update_post_meta( $id, self::META, wp_slash( self::stored( $type, $config ) ) ); } self::$quiet = false; if ( is_wp_error( $id ) ) { return $id; } self::rebuild_live(); return (int) $id; } /** * Change a form: its name, on or off, type and settings, deep-merged into * what is there (only what is sent changes). A new template brings its * own look (layout, colours, font, corners, edge) unless the same change * sets it; every word stays. * * @param int $id Form id. * @param array $changes { name?, active?, type?, config? }. * @return array|WP_Error The form. */ public static function update( $id, array $changes ) { $form = self::find( (int) $id ); if ( ! $form ) { return self::missing(); } $type = $form['type']; if ( isset( $changes['type'] ) ) { if ( ! in_array( $changes['type'], self::TYPES, true ) ) { return self::type_error(); } $type = $changes['type']; } $config = $form['config']; if ( isset( $changes['config'] ) && is_array( $changes['config'] ) ) { $incoming = self::take_media( $changes['config'] ); if ( is_wp_error( $incoming ) ) { return $incoming; } if ( is_string( $incoming['template'] ?? null ) ) { $template = Mailpuff_Form_Templates::exists( $incoming['template'] ) ? $incoming['template'] : Mailpuff_Form_Templates::FALLBACK; if ( $template !== $config['template'] ) { $fresh = self::defaults( $type )['design']; foreach ( self::LOOK as $key ) { $config['design'][ $key ] = $fresh[ $key ]; } } } $config = self::merge( $config, $incoming ); } $config = self::normalize( $config, $type ); $post = array( 'ID' => (int) $id ); if ( isset( $changes['name'] ) && '' !== trim( (string) $changes['name'] ) ) { $post['post_title'] = trim( sanitize_text_field( (string) $changes['name'] ) ); } if ( array_key_exists( 'active', $changes ) ) { $post['post_status'] = rest_sanitize_boolean( $changes['active'] ) ? 'publish' : 'draft'; } self::$quiet = true; wp_update_post( $post ); update_post_meta( (int) $id, self::META, wp_slash( self::stored( $type, $config ) ) ); self::$quiet = false; self::rebuild_live(); return self::find( (int) $id ); } /** * Delete a form for good. People who signed up through it stay. * * @param int $id Form id. * @return bool */ public static function delete( $id ) { if ( ! self::find( (int) $id ) ) { return false; } self::$quiet = true; $done = (bool) wp_delete_post( (int) $id, true ); self::$quiet = false; self::rebuild_live(); return $done; } /** * A copy, off, named "… (copy)". * * @param int $id Form id. * @return int|WP_Error */ public static function duplicate( $id ) { $form = self::find( (int) $id ); if ( ! $form ) { return self::missing(); } /* translators: %s: a form's name. */ return self::create( sprintf( __( '%s (copy)', 'mailpuff' ), $form['name'] ), $form['type'], $form['config'] ); } /** * What the meta holds. * * @param string $type Type. * @param array $config Settings, from normalize(). * @return array */ private static function stored( $type, array $config ) { return array( 'type' => $type, 'config' => $config, ); } /* The live index --------------------------------------------------------- */ /** * The forms the site places by itself (pop-ups, slide-ins, bars and * below-post forms) that are on, newest first, with their rules: what a * page view reads, from one autoloaded option, before it loads a form. * * @return array */ public static function live() { $live = get_option( self::LIVE_OPTION, false ); return is_array( $live ) ? $live : self::rebuild_live(); } /** * Build the live index again from the forms. * * @return array The index. */ public static function rebuild_live() { $index = array(); foreach ( self::all( array( 'active' => true, 'type' => self::LIVE_TYPES, ) ) as $form ) { $index[] = array( 'id' => $form['id'], 'type' => $form['type'], 'template' => $form['template'], 'rules' => $form['config']['rules'], ); } update_option( self::LIVE_OPTION, $index, true ); return $index; } /** * A form turned on or off or trashed outside the model's own methods. * * @param string $new_status New status. * @param string $old_status Old status. * @param WP_Post $post The post. */ public static function status_changed( $new_status, $old_status, $post ) { if ( ! self::$quiet && $new_status !== $old_status && $post instanceof WP_Post && self::POST_TYPE === $post->post_type ) { self::rebuild_live(); } } /** * A form deleted outside the model's own methods (Delete all data). * * @param int $post_id Post id. * @param WP_Post|null $post The post. */ public static function post_deleted( $post_id, $post = null ) { if ( ! self::$quiet && $post instanceof WP_Post && self::POST_TYPE === $post->post_type ) { self::rebuild_live(); } } /** * Delete all data: the index and the count go with the forms. */ public static function forget_live() { delete_option( self::LIVE_OPTION ); delete_transient( self::COUNT_CACHE ); } /* Numbers ----------------------------------------------------------------- */ /** * How many people are subscribed: the `{count}` in a form's proof line. * Cached an hour. * * @return int */ public static function subscriber_count() { $count = get_transient( self::COUNT_CACHE ); if ( false !== $count ) { return (int) $count; } $count = Mailpuff_Contact::count_by_status( Mailpuff_Schema::SUBSCRIBER_SUBSCRIBED ); set_transient( self::COUNT_CACHE, $count, HOUR_IN_SECONDS ); self::$count_gone = false; return $count; } /** * Someone came, went or changed status: count again on the next read. * Once a request is enough (an import changes thousands). */ public static function forget_count() { if ( self::$count_gone ) { return; } delete_transient( self::COUNT_CACHE ); self::$count_gone = true; } /** * Where people who signed up through a form are counted from: their * consent source, `form::`. * * @param int $id Form id. * @return string */ public static function source( $id ) { return 'form:' . (int) $id; } /** * People who signed up through a form: all, in the last 30 days, and how * many of them confirmed. * * @param int $id Form id. * @return array{total:int,last_30_days:int,confirmed:int} */ public static function signups( $id ) { global $wpdb; $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $like = $wpdb->esc_like( self::source( $id ) . ':' ) . '%'; // created_at is site time. $since = wp_date( 'Y-m-d H:i:s', time() - 30 * DAY_IN_SECONDS ); $row = $wpdb->get_row( $wpdb->prepare( 'SELECT COUNT(*) AS total, SUM( CASE WHEN created_at >= %s THEN 1 ELSE 0 END ) AS recent, SUM( CASE WHEN status = %s THEN 1 ELSE 0 END ) AS confirmed FROM %i WHERE consent_source LIKE %s', $since, Mailpuff_Schema::SUBSCRIBER_SUBSCRIBED, $table, $like ) ); return array( 'total' => (int) ( $row->total ?? 0 ), 'last_30_days' => (int) ( $row->recent ?? 0 ), 'confirmed' => (int) ( $row->confirmed ?? 0 ), ); } /** * Where and when a form shows, in a few words, for the list. * * @param array $form A form from find(). * @return string */ public static function where( array $form ) { $r = $form['config']['rules']; if ( 'inline' === $form['type'] ) { return __( 'Where you place it', 'mailpuff' ); } if ( 'below_post' === $form['type'] ) { $types = $r['post_types']; if ( in_array( 'post', $types, true ) && in_array( 'page', $types, true ) ) { $where = __( 'Below posts and pages', 'mailpuff' ); } else { $where = in_array( 'page', $types, true ) ? __( 'Below pages', 'mailpuff' ) : __( 'Below posts', 'mailpuff' ); } if ( $r['categories'] ) { /* translators: 1: where, such as "Below posts", 2: a number of categories. */ $where = sprintf( _n( '%1$s in %2$d category', '%1$s in %2$d categories', count( $r['categories'] ), 'mailpuff' ), $where, count( $r['categories'] ) ); } return $where; } $where = array( 'everywhere' => __( 'Every page', 'mailpuff' ), 'posts' => __( 'Posts', 'mailpuff' ), 'pages' => __( 'Pages', 'mailpuff' ), 'home' => __( 'Home page', 'mailpuff' ), /* translators: %d: a number of categories. */ 'categories' => sprintf( _n( 'Posts in %d category', 'Posts in %d categories', count( $r['categories'] ), 'mailpuff' ), count( $r['categories'] ) ), /* translators: %d: a number of pages. */ 'specific' => sprintf( _n( '%d page', '%d pages', count( $r['page_ids'] ), 'mailpuff' ), count( $r['page_ids'] ) ), ); $when = array( /* translators: %d: seconds. */ 'delay' => sprintf( __( 'after %ds', 'mailpuff' ), $r['delay'] ), /* translators: %d: a percentage of the page. */ 'scroll' => sprintf( __( 'at %d%% of the page', 'mailpuff' ), $r['scroll'] ), 'exit' => __( 'on leaving', 'mailpuff' ), 'click' => __( 'from a link', 'mailpuff' ), ); $parts = array( $where[ $r['show_on'] ], $when[ $r['trigger'] ] ); if ( 'both' !== $r['devices'] ) { $parts[] = 'phone' === $r['devices'] ? __( 'phones only', 'mailpuff' ) : __( 'desktop only', 'mailpuff' ); } if ( 'everyone' !== $r['visitors'] ) { $parts[] = 'new' === $r['visitors'] ? __( 'new visitors', 'mailpuff' ) : __( 'returning visitors', 'mailpuff' ); } if ( '' !== $r['start'] ) { /* translators: %s: a date. */ $parts[] = sprintf( __( 'from %s', 'mailpuff' ), mysql2date( get_option( 'date_format' ), $r['start'] ) ); } if ( '' !== $r['end'] ) { /* translators: %s: a date. */ $parts[] = sprintf( __( 'until %s', 'mailpuff' ), mysql2date( get_option( 'date_format' ), $r['end'] ) ); } return implode( ', ', $parts ); } /* Helpers ------------------------------------------------------------------ */ /** * @return WP_Error */ private static function missing() { return new WP_Error( 'mailpuff_form_missing', __( 'There is no such form.', 'mailpuff' ), array( 'status' => 404 ) ); } /** * @return WP_Error */ private static function type_error() { return new WP_Error( 'mailpuff_form_type', __( 'Pick a form type: inline, popup, slide_in, bar or below_post.', 'mailpuff' ), array( 'status' => 400 ) ); } /** * One object of the settings, or an empty one. * * @param array $config Settings. * @param string $key Key. * @return array */ private static function group( array $config, $key ) { return isset( $config[ $key ] ) && is_array( $config[ $key ] ) ? $config[ $key ] : array(); } /** * @param mixed $value Given. * @param string[] $allowed The choices. * @param string $fallback When it is none of them. * @return string */ private static function pick( $value, array $allowed, $fallback ) { return is_string( $value ) && in_array( $value, $allowed, true ) ? $value : $fallback; } /** * @param mixed $value Given. * @param int $min Lowest. * @param int $max Highest. * @param int $fallback When it is not a number. * @return int */ private static function range( $value, $min, $max, $fallback ) { return is_numeric( $value ) ? min( $max, max( $min, (int) $value ) ) : (int) $fallback; } /** * @param mixed $value Given. * @return bool */ private static function flag( $value ) { return is_bool( $value ) ? $value : rest_sanitize_boolean( is_scalar( $value ) ? $value : false ); } /** * A text, or null for the template's. * * @param mixed $value Given. * @param int $max Longest. * @param bool $lines May hold more than one line. * @param bool $required An empty one is the template's. * @return string|null */ private static function words( $value, $max, $lines, $required ) { if ( null === $value || is_bool( $value ) || ! is_scalar( $value ) ) { return null; } $text = $lines ? sanitize_textarea_field( (string) $value ) : sanitize_text_field( (string) $value ); $text = mb_substr( $text, 0, $max ); return '' === $text && $required ? null : $text; } /** * @param mixed $value Given. * @return string[] */ private static function strings( $value ) { return array_values( array_unique( array_map( 'strval', array_filter( is_array( $value ) ? $value : array(), 'is_scalar' ) ) ) ); } /** * @param mixed $value A list of ids, or a comma-separated string. * @return int[] */ private static function id_list( $value ) { return array_values( array_filter( wp_parse_id_list( is_array( $value ) || is_scalar( $value ) ? $value : array() ) ) ); } /** * @param mixed $value Given. * @return string An http(s) address, or ''. */ private static function url( $value ) { return is_scalar( $value ) && '' !== trim( (string) $value ) ? esc_url_raw( trim( (string) $value ), array( 'http', 'https' ) ) : ''; } /** * @param mixed $value Given. * @return string Y-m-d, or ''. */ private static function date( $value ) { $value = is_string( $value ) ? trim( $value ) : ''; return preg_match( '/^(\d{4})-(\d{2})-(\d{2})$/', $value, $m ) && checkdate( (int) $m[2], (int) $m[3], (int) $m[1] ) ? $value : ''; } /** * design.art_text: up to four short lines, or null for the template's. * * @param mixed $value Given. * @return string[]|null */ private static function art_text( $value ) { if ( is_string( $value ) ) { $value = preg_split( '/\R/', $value ); } if ( ! is_array( $value ) ) { return null; } $lines = array(); foreach ( array_slice( array_values( array_filter( $value, 'is_scalar' ) ), 0, self::ART_LINES ) as $line ) { $lines[] = mb_substr( sanitize_text_field( (string) $line ), 0, self::ART_LINE ); } return $lines; } /** * content.fields: null for the template's, else the name fields and the * custom fields that exist, in order. The email is always asked, so it is * never listed. * * @param mixed $value Given. * @return string[]|null */ private static function fields( $value ) { if ( ! is_array( $value ) ) { return null; } $out = array(); foreach ( self::strings( $value ) as $key ) { $key = sanitize_key( $key ); if ( in_array( $key, self::NAME_FIELDS, true ) || ( 'email' !== $key && null !== Mailpuff_Fields::find( $key ) ) ) { $out[] = $key; } } return array_values( array_unique( $out ) ); } /** * design.image: a Media library image with its address and description, * or none (the template's art). * * @param array $image Given. * @return array{id:int,url:string,alt:string} */ private static function image( array $image ) { $id = absint( $image['id'] ?? 0 ); if ( ! $id || ! wp_attachment_is_image( $id ) ) { return array( 'id' => 0, 'url' => '', 'alt' => '', ); } return array( 'id' => $id, 'url' => (string) wp_get_attachment_url( $id ), 'alt' => is_scalar( $image['alt'] ?? null ) ? mb_substr( sanitize_text_field( (string) $image['alt'] ), 0, 200 ) : '', ); } /** * after.file: a Media library file with its address and name, or none. * * @param array $file Given. * @return array{id:int,url:string,name:string} */ private static function file( array $file ) { $id = absint( $file['id'] ?? 0 ); $post = $id ? get_post( $id ) : null; if ( ! $post || 'attachment' !== $post->post_type ) { return array( 'id' => 0, 'url' => '', 'name' => '', ); } $name = is_scalar( $file['name'] ?? null ) ? mb_substr( sanitize_text_field( (string) $file['name'] ), 0, 200 ) : ''; return array( 'id' => $id, 'url' => (string) wp_get_attachment_url( $id ), 'name' => '' !== $name ? $name : wp_basename( (string) get_attached_file( $id ) ), ); } }