namespace, '/forms/subscribe', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'subscribe' ), // Public on purpose: visitors sign up and load forms with no account, on cached pages, so there is no nonce. Signed form settings, a honeypot, a rate limit and the spam rules guard it. 'permission_callback' => '__return_true', ) ); // The Forms section: saved forms, their live preview and the choices // the editor offers; and Settings, Spam protection's numbers. register_rest_route( $this->namespace, '/forms', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'list_forms' ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create_form' ), 'permission_callback' => array( $this, 'check_permission' ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/forms/(?P\d+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_form' ), 'permission_callback' => array( $this, 'check_permission' ), ), // POST, PUT and PATCH: the settings sent are deep-merged. array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_form' ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_form' ), 'permission_callback' => array( $this, 'check_permission' ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/forms/templates', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'templates' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/forms/(?P\d+)/duplicate', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'duplicate_form' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // Forms made with other plugins (Mailpuff_Form_Plugins). register_rest_route( $this->namespace, '/form-plugins', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'list_form_plugins' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/form-plugins/(?P[a-z0-9_-]+)/(?P
[A-Za-z0-9_.-]+)', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'connect_form_plugin' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // Another website's page asks for a form through the embed script. register_rest_route( $this->namespace, '/forms/(?P\d+)/embed', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'embed' ), // Public on purpose: the form is drawn on another website for visitors with no account. It answers only for a form that is on, and only to the sites that form lists. 'permission_callback' => '__return_true', ) ); register_rest_route( $this->namespace, '/forms/preview', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'preview' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/forms/choices', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'choices' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/forms/spam', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'spam' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); } /** * A form as screens and tools read it: with its type's name, where it * shows, its signups, its preview address, its embed tag and its design * check. * * @param array $form From Mailpuff_Form::find(). * @return array */ public static function present( array $form ) { return array_merge( $form, array( 'type_label' => Mailpuff_Form::type_labels()[ $form['type'] ], 'where' => Mailpuff_Form::where( $form ), 'signups' => Mailpuff_Form::signups( $form['id'] ), 'preview_url' => Mailpuff_Forms::preview_url( $form ), 'embed' => Mailpuff_Form_Embed::snippet( $form ), 'checks' => Mailpuff_Form_Checks::run( $form ), ) ); } /** * The shape of a form these routes answer with, for OPTIONS requests and * docs. Its `config` is Mailpuff_Form::schema(). * * @return array */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $this->schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'mailpuff-form', 'type' => 'object', 'properties' => array( 'id' => array( 'type' => 'integer', 'readonly' => true, ), 'name' => array( 'type' => 'string' ), 'type' => array( 'type' => 'string', 'enum' => Mailpuff_Form::TYPES, ), 'active' => array( 'type' => 'boolean' ), 'template' => array( 'type' => 'string', 'description' => 'On create: the template to start from (also config.template).', ), 'config' => Mailpuff_Form::schema(), 'shortcode' => array( 'type' => 'string', 'readonly' => true, ), 'embed' => array( 'type' => 'string', 'readonly' => true, ), 'preview_url' => array( 'type' => 'string', 'readonly' => true, ), 'where' => array( 'type' => 'string', 'readonly' => true, ), 'checks' => array( 'type' => 'array', 'readonly' => true, ), ), ); return $this->add_additional_fields_schema( $this->schema ); } /** * GET /forms: every saved form, newest first. * * @return WP_REST_Response */ public function list_forms() { return $this->success( array( 'items' => array_map( array( __CLASS__, 'present' ), Mailpuff_Form::all() ) ) ); } /** * POST /forms { name, type, template?, config?, active? }. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function create_form( $request ) { $config = $request->get_param( 'config' ); $config = is_array( $config ) ? $config : array(); if ( is_string( $request->get_param( 'template' ) ) && '' !== $request->get_param( 'template' ) ) { $config['template'] = $request->get_param( 'template' ); } $id = Mailpuff_Form::create( (string) $request->get_param( 'name' ), (string) $request->get_param( 'type' ), $config, rest_sanitize_boolean( $request->get_param( 'active' ) ?? false ) ); if ( is_wp_error( $id ) ) { return $id; } return $this->success( self::present( Mailpuff_Form::find( $id ) ), 201 ); } /** * GET /forms/{id}. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function get_form( $request ) { $form = Mailpuff_Form::find( (int) $request['id'] ); return $form ? $this->success( self::present( $form ) ) : $this->error( 'mailpuff_form_missing', __( 'There is no such form.', 'mailpuff' ), 404 ); } /** * POST|PUT|PATCH /forms/{id} { name?, active?, type?, config? }: only * what is sent changes; config is deep-merged (objects key by key, lists * whole). * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function update_form( $request ) { $changes = array(); foreach ( array( 'name', 'active', 'type', 'config' ) as $key ) { if ( null !== $request->get_param( $key ) ) { $changes[ $key ] = $request->get_param( $key ); } } if ( isset( $changes['active'] ) ) { $changes['active'] = rest_sanitize_boolean( $changes['active'] ); } if ( isset( $changes['config'] ) && ! is_array( $changes['config'] ) ) { return $this->error( 'mailpuff_form_config', __( 'config must be an object of settings.', 'mailpuff' ), 400 ); } $form = Mailpuff_Form::update( (int) $request['id'], $changes ); return is_wp_error( $form ) ? $form : $this->success( self::present( $form ) ); } /** * DELETE /forms/{id}. People who signed up through it stay. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function delete_form( $request ) { return Mailpuff_Form::delete( (int) $request['id'] ) ? $this->success( array( 'deleted' => true ) ) : $this->error( 'mailpuff_form_missing', __( 'There is no such form.', 'mailpuff' ), 404 ); } /** * POST /forms/{id}/duplicate: a copy, off. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function duplicate_form( $request ) { $id = Mailpuff_Form::duplicate( (int) $request['id'] ); return is_wp_error( $id ) ? $id : $this->success( self::present( Mailpuff_Form::find( $id ) ), 201 ); } /** * GET /forms/templates: every template (an add-on's too) with its look, * words, art and stylesheets, and the fonts that ship with Mailpuff. * * @return WP_REST_Response */ public function templates() { return $this->success( array( 'items' => Mailpuff_Form_Templates::for_js(), 'fonts' => Mailpuff_Form_Templates::fonts_for_js(), ) ); } /** * GET /form-plugins: the active form plugins, their forms, fields, how * each is connected and its signups. * * @return WP_REST_Response */ public function list_form_plugins() { return $this->success( array( 'plugins' => Mailpuff_Form_Plugins::catalog() ) ); } /** * POST /form-plugins// { active?, email?, first_name?, * last_name?, consent?, tags? }: connect a form, change it or turn it off. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function connect_form_plugin( $request ) { $input = array(); foreach ( array( 'active', 'email', 'first_name', 'last_name', 'consent', 'tags' ) as $key ) { if ( null !== $request->get_param( $key ) ) { $input[ $key ] = $request->get_param( $key ); } } if ( isset( $input['active'] ) ) { $input['active'] = rest_sanitize_boolean( $input['active'] ); } foreach ( array( 'email', 'first_name', 'last_name', 'consent' ) as $key ) { if ( isset( $input[ $key ] ) ) { $input[ $key ] = sanitize_text_field( (string) $input[ $key ] ); } } $result = Mailpuff_Form_Plugins::save( (string) $request['plugin'], (string) $request['form'], $input ); if ( is_wp_error( $result ) ) { $data = (array) $result->get_error_data(); return $this->error( 'mailpuff_' . $result->get_error_code(), $result->get_error_message(), (int) ( $data['status'] ?? 400 ) ); } return $this->success( $result ); } /** * POST /forms/preview { id?, type, template?, config }: the form as the * site would draw it, from settings not saved yet, with the stylesheets * and fonts it needs. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function preview( $request ) { $type = (string) $request->get_param( 'type' ); if ( ! in_array( $type, Mailpuff_Form::TYPES, true ) ) { return $this->error( 'mailpuff_form_type', __( 'Pick a form type.', 'mailpuff' ), 400 ); } $config = $request->get_param( 'config' ); $config = is_array( $config ) ? $config : array(); if ( is_string( $request->get_param( 'template' ) ) && '' !== $request->get_param( 'template' ) ) { $config['template'] = $request->get_param( 'template' ); } $config = Mailpuff_Form::normalize( $config, $type ); $form = array( 'id' => absint( $request->get_param( 'id' ) ), 'name' => '', 'type' => $type, 'active' => true, 'config' => $config, 'template' => $config['template'], ); return $this->success( array( 'html' => Mailpuff_Forms::preview_html( $form ), 'styles' => Mailpuff_Form_Embed::style_urls( $form ), 'fonts' => Mailpuff_Form_Embed::font_urls( $form ), 'checks' => Mailpuff_Form_Checks::run( $form ), ) ); } /** * GET /forms/{id}/embed: a form for a page on one of its sites. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function embed( $request ) { $payload = Mailpuff_Form_Embed::payload( (int) $request['id'] ); if ( is_wp_error( $payload ) ) { return $payload; } $response = $this->success( $payload ); $response->header( 'Cache-Control', 'no-store' ); return $response; } /** * GET /forms/choices: what the builder's pickers offer: public tags, * pages, categories, custom fields, the `{count}` number, the privacy * page and the tracking box (whether forms ask, and the site's question). * * @return WP_REST_Response */ public function choices() { $tags = array(); foreach ( (array) Mailpuff_Group::all() as $group ) { if ( Mailpuff_Schema::GROUP_PUBLIC === (string) ( $group->visibility ?? '' ) ) { $tags[] = array( 'id' => (int) $group->id, 'name' => (string) $group->name, ); } } $categories = array(); foreach ( (array) get_categories( array( 'hide_empty' => false ) ) as $term ) { $categories[] = array( 'id' => (int) $term->term_id, 'name' => html_entity_decode( (string) $term->name, ENT_QUOTES, 'UTF-8' ), ); } $pages = array(); foreach ( get_posts( array( 'post_type' => array( 'page', 'post' ), 'post_status' => 'publish', 'posts_per_page' => 100, 'orderby' => 'title', 'order' => 'ASC', ) ) as $post ) { $pages[] = array( 'id' => (int) $post->ID, 'title' => html_entity_decode( get_the_title( $post ), ENT_QUOTES, 'UTF-8' ), 'type' => (string) $post->post_type, ); } $fields = array(); foreach ( Mailpuff_Fields::all() as $field ) { $fields[] = array( 'key' => $field['key'], 'label' => $field['label'], 'type' => $field['type'], ); } return $this->success( array( 'tags' => $tags, 'categories' => $categories, 'pages' => $pages, 'fields' => $fields, 'subscribers' => Mailpuff_Form::subscriber_count(), 'privacy_url' => (string) get_privacy_policy_url(), 'site_host' => (string) wp_parse_url( home_url(), PHP_URL_HOST ), // Whether forms ask to count opens and clicks, and in the site's words. 'tracking' => array( 'asks' => Mailpuff_Tracking_Consent::asks(), 'question' => Mailpuff_Tracking_Consent::label(), ), ) ); } /** * GET /forms/spam: spam protection and what it refused. Never the * Turnstile secret (its keys are settings fields). * * @return WP_REST_Response */ public function spam() { return $this->success( Mailpuff_Spam::status() ); } /** * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function subscribe( $request ) { if ( ! $this->within_rate_limit( 'forms' ) ) { return $this->error( 'rate_limit', __( 'Too many requests. Try again in a minute.', 'mailpuff' ), 429 ); } $ip = $this->client_ip(); $wait = Mailpuff_Spam::wait( $ip ); if ( $wait > 0 ) { Mailpuff_Spam::count( 'throttled' ); /* translators: %s: how long, such as "2 mins". */ return $this->error( 'throttled', sprintf( __( 'Too many tries. Try again in %s.', 'mailpuff' ), human_time_diff( time(), time() + $wait ) ), 429 ); } $settings = Mailpuff_Subscription::verify( (string) $request->get_param( 'settings' ), (string) $request->get_param( 'sig' ) ); if ( null === $settings ) { return $this->error( 'invalid_form', __( 'This form is out of date. Reload the page and try again.', 'mailpuff' ), 400 ); } // Double opt-in is off only for a form on published content. Anyone who // can edit posts can have the block rendered with any attributes (a // draft's preview, the block renderer, a Query Loop that signs another // post's ID), so the published post itself must hold a signup block // with double opt-in off. Only published content is the site speaking. $post_id = isset( $settings['post'] ) ? absint( $settings['post'] ) : 0; $doi = ! array_key_exists( 'doi', $settings ) || ! empty( $settings['doi'] ) || ! $post_id || 'publish' !== get_post_status( $post_id ) || ! self::has_form_without_doi( parse_blocks( (string) get_post_field( 'post_content', $post_id ) ) ); $message = isset( $settings['success'] ) && '' !== trim( (string) $settings['success'] ) ? sanitize_text_field( (string) $settings['success'] ) : ( $doi ? __( 'Thanks. Check your email to confirm your subscription.', 'mailpuff' ) : __( 'Thanks. You are subscribed.', 'mailpuff' ) ); $ok = $this->success( array( 'message' => $message ) ); // A bot filled the hidden field. Look like it worked. if ( '' !== trim( (string) $request->get_param( 'hp_url' ) ) ) { Mailpuff_Spam::refused( $ip, 'honeypot' ); return $ok; } $email = sanitize_email( (string) $request->get_param( 'email' ) ); if ( ! is_email( $email ) ) { return $this->error( 'invalid_email', __( 'A valid email address is required.', 'mailpuff' ), 400 ); } // The custom fields the form asks for (signed), each checked as the // subscriber page checks it. A bad value says which field and why. $values = self::field_values( $settings, $request->get_param( 'fields' ) ); if ( is_wp_error( $values ) ) { return $this->error( 'invalid_field', $values->get_error_message(), 400 ); } /** * Seconds a visitor needs between the form rendering and the post. * * @param int $seconds Default 2. */ $min = (int) apply_filters( 'mailpuff_signup_min_seconds', self::MIN_SECONDS ); $rendered = isset( $settings['ts'] ) ? (int) $settings['ts'] : 0; if ( $rendered <= 0 || ( time() - $rendered ) < $min ) { Mailpuff_Spam::refused( $ip, 'too_fast' ); return $this->error( 'too_fast', __( 'That was quick. Wait a moment and try again.', 'mailpuff' ), 400 ); } // A form on another website signs people up only from the sites its // owner listed (the browser's Origin says which page sent it). $embedded = isset( $settings['place'] ) && 'embed' === $settings['place']; if ( $embedded ) { $embed_form = Mailpuff_Form::find( absint( $settings['form'] ?? 0 ) ); if ( ! $embed_form || ! $embed_form['active'] || ! Mailpuff_Form_Embed::allows( $embed_form, Mailpuff_Form_Embed::origin_host() ) ) { return $this->error( 'embed_not_allowed', __( 'This form can\'t take signups from this site.', 'mailpuff' ), 403 ); } } // A throwaway inbox or one of the owner's blocked domains. Nothing // about the address itself is told, only about its domain. $refusal = Mailpuff_Spam::address_refusal( $email ); if ( '' !== $refusal ) { Mailpuff_Spam::refused( $ip, $refusal ); return $this->error( $refusal, Mailpuff_Spam::address_message( $refusal ), 400 ); } // Turnstile, while it is on: a missing token or no answer refuses. $hosts = $embedded ? array( Mailpuff_Form_Embed::origin_host() ) : array(); if ( '' !== Mailpuff_Spam::turnstile_site_key() && ! Mailpuff_Spam::turnstile_passes( (string) $request->get_param( 'cf-turnstile-response' ), $ip, $hosts ) ) { Mailpuff_Spam::refused( $ip, 'turnstile' ); return $this->error( 'turnstile', __( 'Reload the page, complete the check that you are a person, and try again.', 'mailpuff' ), 400 ); } $first = ! empty( $settings['name'] ) ? (string) $request->get_param( 'first_name' ) : ''; // Akismet, while it is on: spam looks like it worked, as the honeypot does. if ( Mailpuff_Spam::akismet_says_spam( $email, $first, $ip, $post_id ) ) { Mailpuff_Spam::refused( $ip, 'akismet' ); return $ok; } // Where they signed up: a saved form as `form::` (its numbers // count these), anything else as `:`. $form = isset( $settings['form'] ) ? absint( $settings['form'] ) : 0; $place = isset( $settings['place'] ) && in_array( $settings['place'], Mailpuff_Forms::PLACES, true ) ? (string) $settings['place'] : 'block'; $source = $form ? Mailpuff_Form::source( $form ) . ':' . $post_id : $place . ':' . $post_id; // A new contact gets their field values before any email goes out, so // the confirmation's {{field:…}} tags can use them. $fill = static function ( $contact_id ) use ( $values ) { self::fill_fields( (int) $contact_id, $values ); }; if ( $values ) { add_action( 'mailpuff_contact_created', $fill, 1 ); } $result = Mailpuff_Subscription::signup( $email, array( 'first_name' => $first, 'last_name' => ! empty( $settings['last'] ) ? (string) $request->get_param( 'last_name' ) : '', 'group_ids' => isset( $settings['groups'] ) ? (array) $settings['groups'] : array(), 'double_opt_in' => $doi, 'consent_source' => $source, 'post_delivery' => (string) $request->get_param( 'post_delivery' ), 'tracking' => '1' === (string) $request->get_param( 'tracking_consent' ) && Mailpuff_Tracking_Consent::asks(), ) ); if ( $values ) { remove_action( 'mailpuff_contact_created', $fill, 1 ); // Someone signing up again (pending, or back after leaving) fills // the fields they left empty. A subscribed contact is left alone, // as their names are: a form never rewrites another person. $contact = in_array( $result, array( 'pending', 'subscribed' ), true ) ? Mailpuff_Contact::find_by_email( $email ) : null; if ( $contact ) { self::fill_fields( (int) $contact->id, $values ); } } return $ok; } /** * The custom field values a signup carries: only the keys the signed * settings list, each cleaned strictly (Mailpuff_Fields::clean()). * * @param array $settings The verified settings. * @param mixed $given The request's `fields`. * @return array|WP_Error Key => value, only the ones given. */ private static function field_values( array $settings, $given ) { $given = is_array( $given ) ? $given : array(); $values = array(); foreach ( array_unique( array_map( 'strval', (array) ( $settings['fields'] ?? array() ) ) ) as $key ) { $field = Mailpuff_Fields::find( $key ); if ( ! $field || ! array_key_exists( $key, $given ) ) { continue; } $value = Mailpuff_Fields::clean( $field, is_scalar( $given[ $key ] ) ? (string) $given[ $key ] : $given[ $key ], true ); if ( is_wp_error( $value ) ) { return $value; } if ( '' !== $value ) { $values[ $field['key'] ] = $value; } } return $values; } /** * Store the values a contact does not have yet; never one they have. * * @param int $contact_id Contact ID. * @param array $values Cleaned values. */ private static function fill_fields( $contact_id, array $values ) { $values = array_diff_key( $values, Mailpuff_Fields::values_of( $contact_id ) ); if ( $values ) { Mailpuff_Fields::set_values( $contact_id, $values ); } } /** * Whether these blocks hold a signup block with double opt-in off, looking * inside inner blocks and published synced patterns. * * @param array[] $blocks Parsed blocks. * @param int $depth Synced-pattern nesting so far. * @return bool */ private static function has_form_without_doi( array $blocks, $depth = 0 ) { foreach ( $blocks as $block ) { $name = (string) ( $block['blockName'] ?? '' ); $attrs = (array) ( $block['attrs'] ?? array() ); if ( 'mailpuff/signup-form' === $name && array_key_exists( 'doubleOptIn', $attrs ) && false === $attrs['doubleOptIn'] ) { return true; } if ( 'core/block' === $name && ! empty( $attrs['ref'] ) && $depth < 3 && 'wp_block' === get_post_type( (int) $attrs['ref'] ) && 'publish' === get_post_status( (int) $attrs['ref'] ) && self::has_form_without_doi( parse_blocks( (string) get_post_field( 'post_content', (int) $attrs['ref'] ) ), $depth + 1 ) ) { return true; } if ( ! empty( $block['innerBlocks'] ) && self::has_form_without_doi( (array) $block['innerBlocks'], $depth ) ) { return true; } } return false; } }