Step to open per form (from the resumed draft). */ private static $step = array(); /** Hooks. */ public static function init() { Helpers::boot(); add_filter( 'fwren/form_defaults', array( __CLASS__, 'defaults' ) ); add_action( 'rest_api_init', array( __CLASS__, 'routes' ) ); add_filter( 'fwren/prefill', array( __CLASS__, 'prefill' ), 10, 2 ); add_filter( 'fwren/frontend_config', array( __CLASS__, 'config' ), 10, 3 ); add_action( 'fwren/submission/inserted', array( __CLASS__, 'on_inserted' ), 10, 5 ); add_action( 'fwren/daily', array( __CLASS__, 'daily' ) ); add_filter( 'fwren/smartcodes', array( __CLASS__, 'catalog' ) ); add_filter( 'fwren/admin/form_tabs', array( __CLASS__, 'tab' ), 22, 2 ); add_action( 'fwren/admin/form_tab/save_resume', array( __CLASS__, 'render_tab' ), 10, 2 ); add_action( 'fwren/admin/entry_sidebar', array( __CLASS__, 'entry_sidebar' ) ); } /** Extra defaults. */ public static function defaults( $d ) { $d['save_resume'] = array_merge( array( 'email_subject' => __( 'Continue your form: {form_title}', 'fieldwren' ), 'email_message' => __( "Hi,\n\nYou saved your progress on {form_title}. Pick up where you left off:\n\n{resume_link}\n\nThank you.", 'fieldwren' ), 'partial' => false, 'partial_minutes' => 30, 'partial_notify' => false, 'partial_notify_email' => '{wp.admin_email}', ), (array) ( $d['save_resume'] ?? array() ) ); return $d; } /** Smartcode picker entry. */ public static function catalog( $groups ) { $groups[ __( 'Save & resume', 'fieldwren' ) ] = array( '{resume_link}' => __( 'Resume link (save & resume messages only)', 'fieldwren' ) ); return $groups; } /** @return string */ private static function table() { return Install::table( 'drafts' ); } /* ------------------------------------------------------------------ * * REST * ------------------------------------------------------------------ */ /** Routes. */ public static function routes() { register_rest_route( 'fwren/v1', '/forms/(?P\d+)/draft', array( 'methods' => 'POST', 'permission_callback' => '__return_true', 'callback' => array( __CLASS__, 'rest_save' ), ) ); } /** @return \WP_REST_Response */ private static function respond( array $body, $status = 200 ) { $r = rest_ensure_response( $body ); $r->set_status( $status ); $r->header( 'Cache-Control', 'no-store' ); return $r; } /** Save a draft. */ public static function rest_save( \WP_REST_Request $req ) { $form_id = (int) $req['id']; $post = get_post( $form_id ); $fail = array( 'success' => false, 'message' => __( 'Your progress could not be saved.', 'fieldwren' ), 'link' => '', 'hash' => '' ); if ( ! $post || Plugin::POST_TYPE !== $post->post_type || 'publish' !== $post->post_status ) { return self::respond( $fail, 404 ); } $settings = Form::settings( $form_id ); $sr = $settings['save_resume']; $data = (array) $req->get_body_params(); $partial = Helpers::on( $data['partial'] ?? $req->get_param( 'partial' ) ); if ( $partial ? empty( $sr['partial'] ) : empty( $sr['enabled'] ) ) { return self::respond( $fail, 403 ); } if ( ! empty( $settings['spam']['honeypot'] ) && '' !== (string) ( $data[ Spam::honeypot_name( $form_id ) ] ?? '' ) ) { return self::respond( $fail, 400 ); } $rl = 'fwren_drl_' . md5( Submission::ip() . '|' . $form_id ); $count = (int) get_transient( $rl ); if ( $count >= (int) apply_filters( 'fwren/drafts/rate_limit', 60, $form_id ) ) { $fail['message'] = __( 'Too many saves. Please wait a few minutes and try again.', 'fieldwren' ); return self::respond( $fail, 429 ); } set_transient( $rl, $count + 1, 10 * MINUTE_IN_SECONDS ); $values = self::collect( $form_id, $data ); $hash = sanitize_key( (string) ( $data['_fwren_draft'] ?? '' ) ); $row = Helpers::is_token( $hash ) ? self::get( $hash ) : null; if ( $row && (int) $row['form_id'] !== $form_id ) { $row = null; } if ( ! $row && $partial && ! self::has_value( $values, $form_id ) ) { return self::respond( array( 'success' => true, 'message' => '', 'link' => '', 'hash' => '' ) ); } $source = esc_url_raw( (string) ( $data['_fwren_source'] ?? wp_get_referer() ) ); $source = wp_validate_redirect( $source, home_url( '/' ) ); $meta = $row ? self::decode( $row['data'] ) : array( 'values' => array(), 'source' => '', 'partial_entry' => 0, 'emailed' => 0 ); $meta['values'] = $values; $meta['source'] = $source; $step = absint( $data['_fwren_step'] ?? ( $data['step'] ?? 0 ) ); $email = Helpers::email_of( $form_id, $values, (string) $settings['double_optin']['email_field'] ); $now = current_time( 'mysql', true ); global $wpdb; if ( $row ) { $wpdb->update( self::table(), array( 'step' => $step, 'email' => substr( $email, 0, 190 ), 'data' => wp_json_encode( $meta ), 'updated_at' => $now ), array( 'id' => (int) $row['id'] ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } else { $hash = Helpers::token(); $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery self::table(), array( 'form_id' => $form_id, 'hash' => $hash, 'user_id' => get_current_user_id(), 'email' => substr( $email, 0, 190 ), 'step' => $step, 'data' => wp_json_encode( $meta ), 'ip' => ! empty( $settings['entries']['store_ip'] ) ? Submission::ip( ! empty( $settings['privacy']['anonymize_ip'] ) ) : '', 'created_at' => $now, 'updated_at' => $now, ) ); } $link = add_query_arg( 'fwren_resume', $hash, remove_query_arg( array( 'fwren_resume', 'fwren_confirm', 'fwren_notice' ), $source ) ); $out = array( 'success' => true, 'message' => '', 'link' => esc_url_raw( $link ), 'hash' => $hash ); if ( ! $partial ) { $ctx = array( 'form_id' => $form_id, 'values' => $values, 'entry' => array(), 'extra' => array( '{resume_link}' => esc_url( $link ) ) ); $out['message'] = wp_kses_post( wpautop( make_clickable( Smartcodes::parse( (string) $sr['message'], $ctx, 'html' ) ) ) ); if ( ! empty( $sr['email_link'] ) && $email && time() - (int) $meta['emailed'] > 2 * MINUTE_IN_SECONDS ) { if ( self::email_link( $form_id, $email, $link, $values ) ) { $meta['emailed'] = time(); $wpdb->update( self::table(), array( 'data' => wp_json_encode( $meta ) ), array( 'hash' => $hash ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery /* translators: %s email */ $out['message'] .= '

' . esc_html( sprintf( __( 'We also sent the link to %s.', 'fieldwren' ), $email ) ) . '

'; } } } return self::respond( apply_filters( 'fwren/drafts/response', $out, $form_id, $hash, $partial ) ); } /** * Clean values worth saving. * * @param int $form_id Form id. * @param array $data Unslashed request data. * @return array */ public static function collect( $form_id, array $data ) { $values = array(); foreach ( Schema::fields( $form_id ) as $key => $f ) { if ( ! array_key_exists( $key, $data ) || ! empty( $f['is_upload'] ) || ! empty( $f['signature'] ) || ! empty( $f['sensitive'] ) || ! empty( $f['calculated'] ) || ! empty( $f['payment'] ) || 'password' === $f['type'] ) { continue; } $type = Fields::get( $f['type'] ); if ( $type ) { $values[ $key ] = $type->sanitize( $data[ $key ], $f ); } } return $values; } /** @return bool Whether any visible value was typed. */ private static function has_value( array $values, $form_id ) { foreach ( $values as $k => $v ) { $f = Schema::field( $form_id, $k ); $type = $f ? Fields::get( $f['type'] ) : null; if ( $f && 'hidden' !== $f['type'] && $type && ! $type->is_empty( $v ) ) { return true; } } return false; } /** Email the resume link. */ private static function email_link( $form_id, $email, $link, array $values ) { $sr = Form::settings( $form_id )['save_resume']; $message = str_replace( '{resume_link}', esc_url( $link ), (string) $sr['email_message'] ); $n = array( 'id' => 'resume_link', 'enabled' => true, 'name' => __( 'Resume link', 'fieldwren' ), 'to_type' => 'email', 'to' => $email, 'to_field' => '', 'routing' => array(), 'cc' => '', 'bcc' => '', 'reply_to' => '', 'from_name' => '', 'from_email' => '', 'subject' => (string) $sr['email_subject'], 'message' => make_clickable( $message ), 'attach_uploads' => false, ); return Notifications::send( $n, array( 'id' => 0, 'form_id' => $form_id ), $values ); } /* ------------------------------------------------------------------ * * Storage * ------------------------------------------------------------------ */ /** @return array|null Draft row. */ public static function get( $hash ) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . ' WHERE hash = %s', $hash ), ARRAY_A ); // phpcs:ignore return $row ? $row : null; } /** @return array Decoded data column. */ private static function decode( $json ) { $d = json_decode( (string) $json, true ); $d = is_array( $d ) ? $d : array(); return array_merge( array( 'values' => array(), 'source' => '', 'partial_entry' => 0, 'emailed' => 0 ), $d ); } /** Delete a draft. */ public static function delete( $hash ) { global $wpdb; $wpdb->delete( self::table(), array( 'hash' => $hash ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } /** @return bool Whether a draft is past the form's expiry. */ private static function expired( array $row ) { $days = max( 1, (int) Form::settings( (int) $row['form_id'] )['save_resume']['expiry_days'] ); return strtotime( $row['updated_at'] . ' UTC' ) < time() - $days * DAY_IN_SECONDS; } /* ------------------------------------------------------------------ * * Prefill * ------------------------------------------------------------------ */ /** ?fwren_resume=hash → values. */ public static function prefill( $prefill, $form_id ) { $hash = isset( $_GET['fwren_resume'] ) ? sanitize_key( wp_unslash( $_GET['fwren_resume'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification if ( ! Helpers::is_token( $hash ) ) { return $prefill; } $row = self::get( $hash ); if ( ! $row || (int) $row['form_id'] !== (int) $form_id || self::expired( $row ) ) { return $prefill; } self::$step[ (int) $form_id ] = (int) $row['step']; $meta = self::decode( $row['data'] ); return array_merge( (array) $meta['values'], (array) $prefill ); } /** Frontend config: step to open, partial capture. */ public static function config( $config, $form_id, $settings = array() ) { $s = $settings ? $settings : Form::settings( $form_id ); $config['prefillStep'] = self::$step[ (int) $form_id ] ?? 0; $config['partial'] = ! empty( $s['save_resume']['partial'] ); return $config; } /** Submitted: drop the draft (and its partial entry). */ public static function on_inserted( $entry_id, $values, $form_id, $row = array(), $data = array() ) { $hash = sanitize_key( (string) ( $data['_fwren_draft'] ?? '' ) ); if ( ! Helpers::is_token( $hash ) ) { return; } $draft = self::get( $hash ); if ( ! $draft || (int) $draft['form_id'] !== (int) $form_id ) { return; } $meta = self::decode( $draft['data'] ); if ( ! empty( $meta['partial_entry'] ) ) { $p = Entries::get( (int) $meta['partial_entry'] ); if ( $p && 'partial' === $p['status'] && (int) $p['id'] !== (int) $entry_id ) { Entries::delete( array( (int) $p['id'] ) ); } } self::delete( $hash ); } /* ------------------------------------------------------------------ * * Daily: partial entries + expiry * ------------------------------------------------------------------ */ /** Daily job. */ public static function daily() { global $wpdb; $t = self::table(); $forms = array_map( 'intval', (array) $wpdb->get_col( "SELECT DISTINCT form_id FROM $t" ) ); // phpcs:ignore foreach ( $forms as $form_id ) { if ( ! Form::exists( $form_id ) ) { $wpdb->delete( $t, array( 'form_id' => $form_id ) ); // phpcs:ignore continue; } $s = Form::settings( $form_id ); $sr = $s['save_resume']; if ( ! empty( $sr['partial'] ) && ! empty( $s['entries']['store'] ) ) { self::make_partials( $form_id, $s ); } $days = max( 1, (int) $sr['expiry_days'] ); $wpdb->query( $wpdb->prepare( "DELETE FROM $t WHERE form_id = %d AND updated_at < %s", $form_id, gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ) ) ); // phpcs:ignore } } /** * Idle drafts with an email → partial entries. * * @param int $form_id Form id. * @param array $settings Settings. */ public static function make_partials( $form_id, array $settings ) { global $wpdb; $t = self::table(); $sr = $settings['save_resume']; $before = gmdate( 'Y-m-d H:i:s', time() - max( 1, (int) $sr['partial_minutes'] ) * MINUTE_IN_SECONDS ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $t WHERE form_id = %d AND email <> '' AND updated_at < %s ORDER BY id ASC LIMIT 200", $form_id, $before ), ARRAY_A ); // phpcs:ignore $schema = Schema::get( $form_id ); foreach ( $rows as $row ) { $meta = self::decode( $row['data'] ); $values = (array) $meta['values']; if ( ! empty( $meta['partial_entry'] ) ) { $e = Entries::get( (int) $meta['partial_entry'] ); if ( $e && 'partial' === $e['status'] ) { if ( strtotime( $row['updated_at'] . ' UTC' ) > strtotime( $e['updated_at'] . ' UTC' ) ) { Entries::update( (int) $e['id'], array( 'response' => $values ) ); } continue; } if ( $e ) { continue; // Moved out of "partial" by an admin: leave it alone. } } $id = Entries::insert( array( 'form_id' => $form_id, 'status' => 'partial', 'user_id' => (int) $row['user_id'], 'ip' => (string) $row['ip'], 'user_agent' => '', 'source_url' => (string) $meta['source'], ), $values, $schema ); if ( ! $id ) { continue; } Entries::set_meta( $id, '_draft_hash', $row['hash'] ); $meta['partial_entry'] = $id; $wpdb->update( $t, array( 'data' => wp_json_encode( $meta ), 'updated_at' => $row['updated_at'] ), array( 'id' => (int) $row['id'] ) ); // phpcs:ignore do_action( 'fwren/drafts/partial_created', $id, $row, $values ); if ( ! empty( $sr['partial_notify'] ) ) { self::notify_admin( Entries::get( $id ), $values, (string) $sr['partial_notify_email'] ); } } } /** Partial entry email to the admin. */ private static function notify_admin( $entry, array $values, $to ) { if ( ! $entry ) { return; } $n = array( 'id' => 'partial_entry', 'enabled' => true, 'name' => __( 'Partial entry', 'fieldwren' ), 'to_type' => 'email', 'to' => $to ? $to : '{wp.admin_email}', 'to_field' => '', 'routing' => array(), 'cc' => '', 'bcc' => '', 'reply_to' => '', 'from_name' => '', 'from_email' => '', 'subject' => __( 'Partial entry: {form_title}', 'fieldwren' ), 'message' => '

' . esc_html__( 'Someone started this form but did not submit it.', 'fieldwren' ) . ' ' . esc_html__( 'View entry', 'fieldwren' ) . '

{all_data}', 'attach_uploads' => false, ); Notifications::send( $n, $entry, $values ); } /* ------------------------------------------------------------------ * * Admin * ------------------------------------------------------------------ */ /** Per-form tab. */ public static function tab( $tabs, $form_id = 0 ) { $tabs['save_resume'] = __( 'Save & Resume / Partial entries', 'fieldwren' ); return $tabs; } /** Tab content. */ public static function render_tab( $form_id, $settings ) { global $wpdb; $s = $settings['save_resume']; $n = 'fwren[save_resume]'; $drafts = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . self::table() . ' WHERE form_id = %d', $form_id ) ); // phpcs:ignore $parts = Entries::count( $form_id, 'partial' ); echo ''; Helpers::heading( __( 'Save & resume', 'fieldwren' ), __( 'Add a “Save and continue later” block to the form, or turn on auto-save. Uploads and passwords are never saved in drafts.', 'fieldwren' ) ); Helpers::row_toggle( $n . '[enabled]', ! empty( $s['enabled'] ), __( 'Enable save & resume', 'fieldwren' ) ); Helpers::row_text( $n . '[button_text]', $s['button_text'], __( 'Button text', 'fieldwren' ) ); Helpers::row_toggle( $n . '[auto_save]', ! empty( $s['auto_save'] ), __( 'Auto-save while typing', 'fieldwren' ) ); Helpers::row_textarea( $n . '[message]', $s['message'], __( 'Message after saving', 'fieldwren' ), __( '{resume_link} is the link to continue.', 'fieldwren' ), 3 ); Helpers::row_toggle( $n . '[email_link]', ! empty( $s['email_link'] ), __( 'Email the link', 'fieldwren' ), __( 'Sent when the form has an email value.', 'fieldwren' ) ); Helpers::row_text( $n . '[email_subject]', $s['email_subject'], __( 'Email subject', 'fieldwren' ) ); Helpers::row_textarea( $n . '[email_message]', $s['email_message'], __( 'Email message', 'fieldwren' ), '', 5 ); Helpers::row_text( $n . '[expiry_days]', (string) $s['expiry_days'], __( 'Delete drafts after (days)', 'fieldwren' ), '', 'number' ); Helpers::heading( __( 'Partial entries', 'fieldwren' ), __( 'Captures abandoned forms: the form saves silently as people type, and drafts that stay idle and have an email address become entries with the status “Partial”.', 'fieldwren' ) ); Helpers::row_toggle( $n . '[partial]', ! empty( $s['partial'] ), __( 'Capture partial entries', 'fieldwren' ) ); Helpers::row_text( $n . '[partial_minutes]', (string) $s['partial_minutes'], __( 'Idle minutes before a draft counts as abandoned', 'fieldwren' ), __( 'Checked once a day.', 'fieldwren' ), 'number' ); Helpers::row_toggle( $n . '[partial_notify]', ! empty( $s['partial_notify'] ), __( 'Email the admin about each partial entry', 'fieldwren' ) ); Helpers::row_text( $n . '[partial_notify_email]', $s['partial_notify_email'], __( 'Admin email', 'fieldwren' ) ); echo ''; echo ''; } /** Partial entry origin. */ public static function entry_sidebar( $entry ) { if ( empty( $entry['id'] ) || 'partial' !== ( $entry['status'] ?? '' ) ) { return; } $hash = (string) Entries::get_meta( (int) $entry['id'], '_draft_hash' ); $draft = Helpers::is_token( $hash ) ? self::get( $hash ) : null; echo '

' . esc_html__( 'Partial entry', 'fieldwren' ) . '

' . esc_html__( 'Started but not submitted.', 'fieldwren' ) . '

'; if ( $draft ) { $meta = self::decode( $draft['data'] ); $link = add_query_arg( 'fwren_resume', $hash, $meta['source'] ? $meta['source'] : home_url( '/' ) ); /* translators: %s date */ echo '

' . esc_html( sprintf( __( 'Last activity: %s', 'fieldwren' ), wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $draft['updated_at'] . ' UTC' ) ) ) ) . '

'; echo '

' . esc_html__( 'Resume link (send it to the person to let them finish).', 'fieldwren' ) . '

'; } echo '
'; } }