get_col( $wpdb->prepare( "SELECT id FROM {$submissions} WHERE created_at < %s LIMIT 500", $cutoff ) ); foreach ( $ids as $id ) { $this->delete_submission( (int) $id ); } } public function delete_submission( int $id ) : bool { global $wpdb; do_action( 'funnelnode_submission_deleting', $id ); return (bool) $wpdb->delete( Migrations::table( Migrations::TABLE_SUBMISSIONS ), [ 'id' => $id, ] ); } public function register_routes() : void { $route = [ 'methods' => 'POST', 'callback' => [$this, 'handle_submission'], 'permission_callback' => '__return_true', ]; register_rest_route( Api::NAMESPACE, '/funnel/(?P\\d+)/submission', [$route] ); register_rest_route( Api::NAMESPACE, '/funnel/(?P\\d+)/submission/(?P[A-Za-z0-9_]{8,64})', [array_merge( $route, [ 'methods' => 'POST,PUT', ] )] ); } public function handle_submission( WP_REST_Request $request ) : WP_REST_Response|WP_Error { $funnel_id = absint( $request['id'] ); $post = get_post( $funnel_id ); if ( !$post instanceof \WP_Post || FunnelCpt::POST_TYPE !== $post->post_type || 'publish' !== $post->post_status ) { return new WP_Error('funnelnode_not_found', __( 'Funnel not found.', 'funnelnode' ), [ 'status' => 404, ]); } if ( $this->is_rate_limited() ) { return new WP_Error('funnelnode_rate_limited', __( 'Too many requests.', 'funnelnode' ), [ 'status' => 429, ]); } $session_id = sanitize_text_field( (string) ($request['session'] ?? $request->get_param( 'session_id' ) ?? '') ); $step_id = sanitize_text_field( (string) $request->get_param( 'step_id' ) ); if ( !self::is_valid_session_id( $session_id ) || !preg_match( self::STEP_RE, $step_id ) ) { return new WP_Error('funnelnode_invalid', __( 'Invalid request.', 'funnelnode' ), [ 'status' => 400, ]); } if ( !empty( Settings::all()['spam']['honeypot'] ) && '' !== trim( (string) $request->get_param( 'hp' ) ) ) { return new WP_REST_Response([ 'ok' => true, ], 200); } $settings = $this->funnel_settings( $funnel_id ); $answers = $this->sanitize_answers( $request->get_param( 'step_data' ) ); $extra = $this->sanitize_extra( apply_filters( 'funnelnode_submission_extra', [], $request ) ); $last_seen = sanitize_text_field( (string) $request->get_param( 'last_seen_step' ) ); if ( !preg_match( self::STEP_RE, $last_seen ) ) { $last_seen = $step_id; } $completed = rest_sanitize_boolean( $request->get_param( 'completed' ) ); $path = []; if ( $completed && is_array( $request->get_param( 'path' ) ) ) { foreach ( array_slice( (array) $request->get_param( 'path' ), 0, 200 ) as $p ) { $p = sanitize_text_field( (string) $p ); if ( preg_match( self::STEP_RE, $p ) ) { $path[] = $p; } } } global $wpdb; $table = Migrations::table( Migrations::TABLE_SUBMISSIONS ); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE funnel_id = %d AND session_id = %s LIMIT 1", // phpcs:ignore $funnel_id, $session_id ), ARRAY_A ); if ( $row && !$this->owns_row( $funnel_id, $session_id, (string) $request->get_param( 'token' ) ) ) { return new WP_Error('funnelnode_forbidden', __( 'Invalid request.', 'funnelnode' ), [ 'status' => 403, ]); } $handled = apply_filters( 'funnelnode_submission_pre_write', null, $request, $row ); if ( $handled instanceof WP_REST_Response ) { return $handled; } $earlier = $this->sanitize_earlier( $request->get_param( 'earlier' ) ); $elapsed_hint = min( DAY_IN_SECONDS, absint( $request->get_param( 'elapsed' ) ) ); foreach ( $earlier as [$earlier_id, $earlier_answers] ) { if ( !$row ) { $earlier_row = $this->insert_row( $funnel_id, $session_id, $earlier_id, $earlier_answers, $request, $settings, [], $earlier_id ); } else { $this->update_row( $row, $earlier_id, $earlier_answers, [], [], $earlier_id ); $earlier_row = (int) $row['id']; } $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $earlier_row ), // phpcs:ignore ARRAY_A ); } if ( !$row ) { $row_id = $this->insert_row( $funnel_id, $session_id, $step_id, $answers, $request, $settings, $extra, $last_seen ); } else { $row_id = (int) $row['id']; $this->update_row( $row, $step_id, $answers, $extra, $path, $last_seen ); } $consent = $request->get_param( 'consent' ); if ( is_array( $consent ) && !empty( $consent['given'] ) ) { $wpdb->update( $table, [ 'consent_given' => 1, 'consent_text' => sanitize_textarea_field( (string) ($consent['text'] ?? '') ), 'consent_version' => sanitize_text_field( (string) ($settings['privacy']['consent_version'] ?? '1.0') ), 'consent_at' => current_time( 'mysql', true ), ], [ 'id' => $row_id, ] ); } do_action( 'funnelnode_submission_synced', $row_id, $funnel_id, $session_id, $row, $completed ); if ( $completed && !($row && 1 === (int) $row['completed']) ) { $this->maybe_complete( $row_id, $funnel_id, $settings, $elapsed_hint ); } return new WP_REST_Response([ 'ok' => true, 'session_id' => $session_id, 'token' => self::row_token( $funnel_id, $session_id ), ], 200); } public static function has_last_seen_column() : bool { return self::has_column( 'last_seen_step' ); } public static function has_column( string $column ) : bool { static $cache = []; if ( !isset( $cache[$column] ) ) { global $wpdb; $table = Migrations::table( Migrations::TABLE_SUBMISSIONS ); $cache[$column] = (bool) $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM {$table} LIKE %s", $column ) ); } return $cache[$column]; } private function insert_row( int $funnel_id, string $session_id, string $step_id, array $answers, WP_REST_Request $request, array $settings, array $extra = [], string $last_seen = '' ) : int { global $wpdb; $meta = (array) ($request->get_param( 'meta' ) ?? []); $privacy = (array) ($settings['privacy'] ?? []); $data = array_merge( $extra, [ $step_id => $answers, ] ); $fields = [ 'funnel_id' => $funnel_id, 'session_id' => $session_id, 'current_step' => $step_id, 'step_data' => wp_json_encode( $data ), 'ip_address' => ( $privacy['anonymize_ip'] ?? true ? $this->anonymize_ip( $this->client_ip() ) : $this->client_ip() ), 'user_agent' => ( !empty( $privacy['store_user_agent'] ) ? substr( sanitize_text_field( wp_unslash( (string) ($_SERVER['HTTP_USER_AGENT'] ?? '') ) ), 0, 255 ) : '' ), 'referrer' => substr( esc_url_raw( (string) ($meta['referrer'] ?? '') ), 0, 500 ), 'created_at' => current_time( 'mysql', true ), 'updated_at' => current_time( 'mysql', true ), ]; if ( self::has_last_seen_column() ) { $fields['last_seen_step'] = ( '' !== $last_seen ? $last_seen : $step_id ); } if ( self::has_column( 'page_url' ) ) { $fields['page_url'] = substr( esc_url_raw( (string) ($meta['page_url'] ?? '') ), 0, 500 ); } $fields = (array) apply_filters( 'funnelnode_submission_insert_fields', $fields, $meta ); $wpdb->insert( Migrations::table( Migrations::TABLE_SUBMISSIONS ), $fields ); return (int) $wpdb->insert_id; } private function update_row( array $row, string $step_id, array $answers, array $extra = [], array $path = [], string $last_seen = '' ) : void { global $wpdb; $data = json_decode( (string) $row['step_data'], true ); $data = ( is_array( $data ) ? $data : [] ); if ( $path ) { foreach ( array_keys( $data ) as $key ) { if ( !str_starts_with( (string) $key, '_' ) && $key !== $step_id && !in_array( $key, $path, true ) ) { unset($data[$key]); } } } $data = (array) apply_filters( 'funnelnode_submission_update_data', $data, $row, $step_id, $path ); $data[$step_id] = $answers; foreach ( $extra as $key => $value ) { if ( is_array( $value ) ) { $data[$key] = array_merge( (array) ($data[$key] ?? []), $value ); } elseif ( empty( $data[$key] ) ) { $data[$key] = $value; } } $fields = [ 'step_data' => wp_json_encode( $data ), 'current_step' => $step_id, 'updated_at' => current_time( 'mysql', true ), ]; if ( self::has_last_seen_column() ) { $fields['last_seen_step'] = ( '' !== $last_seen ? $last_seen : $step_id ); } $wpdb->update( Migrations::table( Migrations::TABLE_SUBMISSIONS ), $fields, [ 'id' => (int) $row['id'], ] ); } private function maybe_complete( int $row_id, int $funnel_id, array $settings, int $elapsed_hint = 0 ) : void { global $wpdb; $table = Migrations::table( Migrations::TABLE_SUBMISSIONS ); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $row_id ), // phpcs:ignore ARRAY_A ); if ( !$row || (int) $row['completed'] === 1 ) { return; } $elapsed = max( $elapsed_hint, time() - (int) strtotime( (string) $row['created_at'] . ' UTC' ) ); $minimum = (int) ($settings['spam']['min_completion_seconds'] ?? 3); if ( $elapsed < $minimum ) { return; } $wpdb->update( $table, [ 'completed' => 1, 'completion_time' => $elapsed, 'updated_at' => current_time( 'mysql', true ), ], [ 'id' => $row_id, ] ); do_action( 'funnelnode_submission_completing', $row_id, (string) $row['step_data'] ); Review::remember_first_lead(); self::dispatch( Jobs::HOOK_SEND_EMAIL, [$row_id, $funnel_id] ); do_action( 'funnelnode_lead_event', $row_id, $funnel_id, 'completed' ); do_action( 'funnelnode_submission_completed', $row_id, $funnel_id ); } public function handle_send_email( int $row_id, int $funnel_id ) : void { global $wpdb; $table = Migrations::table( Migrations::TABLE_SUBMISSIONS ); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $row_id ), // phpcs:ignore ARRAY_A ); if ( !$row ) { return; } $settings = $this->funnel_settings( $funnel_id ); $email_cfg = (array) ($settings['email'] ?? []); $dict = $this->placeholder_dict( $funnel_id, (string) $row['step_data'], (string) $row['created_at'] ); $this->send_admin_mail( $row, $funnel_id, $email_cfg, $dict ); } private function send_admin_mail( array $row, int $funnel_id, array $email_cfg, array $dict ) : void { if ( array_key_exists( 'notify_admin', $email_cfg ) && !$email_cfg['notify_admin'] ) { return; } $to = $this->parse_recipients( (string) ($email_cfg['admin_email'] ?? '') ); if ( !$to ) { $to = $this->parse_recipients( (string) (Settings::all()['email']['default_recipients'] ?? '') ); } if ( !$to ) { $to = [(string) get_option( 'admin_email' )]; } $template = (string) ($email_cfg['subject_admin'] ?? ''); if ( '' === $template ) { /* translators: %s: funnel title */ $template = sprintf( __( 'New lead: %s', 'funnelnode' ), '{funnel_title}' ); } $subject = $this->resolve_template( $template, $dict ); $row_id = (int) $row['id']; $content = Mailer::answers_table( $this->answer_rows( $funnel_id, (string) $row['step_data'] ) ); foreach ( $this->lead_sections( $funnel_id, (string) $row['step_data'] ) as $section ) { $content .= '
' . '
' . esc_html( $section['title'] ) . '
' . Mailer::answers_table( $section['rows'] ) . '
'; } $content = (string) apply_filters( 'funnelnode_admin_mail_content', $content, $row_id, $funnel_id ); $meta = [[ 'label' => __( 'Funnel', 'funnelnode' ), 'value' => (string) $dict['funnel_title'], ], [ 'label' => __( 'Lead', 'funnelnode' ), 'value' => '#' . $row_id, ], [ 'label' => __( 'Submitted at', 'funnelnode' ), 'value' => get_date_from_gmt( (string) $row['updated_at'], 'Y-m-d H:i' ), ]]; $content .= '
' . Mailer::answers_table( $meta ) . '
'; Mailer::send( $to, $subject, Mailer::wrap_template( $content, $subject ), [ 'funnel_id' => $funnel_id, 'submission_id' => $row_id, 'html' => true, ] ); } public function placeholder_dict( int $funnel_id, string $step_data_json, string $created_at_gmt = '' ) : array { $dict = [ 'funnel_title' => wp_specialchars_decode( (string) get_the_title( $funnel_id ), ENT_QUOTES ), ]; if ( '' !== $created_at_gmt ) { $timestamp = strtotime( $created_at_gmt . ' +00:00' ); if ( false !== $timestamp ) { $dict['date'] = wp_date( (string) get_option( 'date_format' ), $timestamp ); $dict['time'] = wp_date( (string) get_option( 'time_format' ), $timestamp ); } } $data = json_decode( $step_data_json, true ); if ( !is_array( $data ) ) { return $dict; } $dict = array_map( 'strval', (array) apply_filters( 'funnelnode_placeholder_dict', $dict, $data, $funnel_id ) ); $graph = json_decode( (string) get_post_meta( $funnel_id, FunnelCpt::META_GRAPH, true ), true ); $fields = []; $nodes = []; foreach ( (array) ($graph['nodes'] ?? []) as $node ) { if ( isset( $node['id'] ) ) { $nodes[(string) $node['id']] = $node; } foreach ( (array) ($node['data']['config']['fields'] ?? []) as $field ) { $fields[(string) $field['id']] = $field; } } foreach ( $data as $step_id => $answers ) { if ( !is_array( $answers ) || str_starts_with( (string) $step_id, '_' ) ) { continue; } $node_type = (string) ($nodes[(string) $step_id]['type'] ?? ''); if ( 'input' === $node_type && isset( $answers['value'] ) && is_scalar( $answers['value'] ) ) { $dict[(string) $step_id] = (string) $answers['value']; continue; } if ( 'choice' === $node_type && isset( $answers['selected'] ) ) { $options = []; foreach ( (array) ($nodes[(string) $step_id]['data']['config']['options'] ?? []) as $opt ) { $options[(string) $opt['id']] = (string) ($opt['label'] ?? $opt['id']); } $labels = array_map( static fn( $id ) => $options[(string) $id] ?? (string) $id, (array) $answers['selected'] ); $dict[(string) $step_id] = implode( ', ', $labels ); continue; } foreach ( $answers as $key => $value ) { if ( !is_scalar( $value ) ) { continue; } $dict[(string) $key] = (string) $value; if ( '' === (string) $value ) { continue; } $field = $fields[(string) $key] ?? null; $type = (string) ($field['type'] ?? ''); $alias_types = ['email']; if ( in_array( $type, $alias_types, true ) && !isset( $dict[$type] ) ) { $dict[$type] = (string) $value; } if ( 'text' === $type && !isset( $dict['name'] ) && str_contains( strtolower( (string) ($field['label'] ?? '') ), 'name' ) ) { $dict['name'] = (string) $value; } } } return $dict; } private function resolve_template( string $template, array $dict ) : string { return self::resolve_placeholders( $template, $dict, static fn( string $v ): string => $v ); } private static function resolve_placeholders( string $template, array $dict, callable $transform ) : string { return (string) preg_replace_callback( '/(\\s*)([,;:–—-]?)(\\s*)\\{([\\w.-]+)(?:\\|([^}]*))?\\}(\\s*)/u', static function ( array $m ) use($dict, $transform, $template) : string { $lead = $m[1][0]; $separator = $m[2][0]; $mid = $m[3][0]; $key = $m[4][0]; $fallback = ( isset( $m[5] ) && -1 !== $m[5][1] ? $m[5][0] : '' ); $trail = ( isset( $m[6] ) && -1 !== $m[6][1] ? $m[6][0] : '' ); $resolved = (string) ($dict[$key] ?? ''); $value = ( '' !== $resolved ? $resolved : (string) $fallback ); if ( '' !== $value ) { return $lead . $separator . $mid . $transform( $value ) . $trail; } $after = substr( $template, $m[0][1] + strlen( $m[0][0] ) ); $before = '' !== $lead || '' !== $separator || '' !== $mid; $continues = '' !== $trail && '' !== $after && !preg_match( '/^[\\s.,;:!?)\\]}–—-]/u', $after ); return ( $before && $continues ? ' ' : '' ); }, $template, -1, $count, PREG_OFFSET_CAPTURE ); } private function parse_recipients( string $raw ) : array { return array_values( array_filter( array_map( static fn( string $address ): string => sanitize_email( trim( $address ) ), explode( ',', $raw ) ) ) ); } public function answer_rows( int $funnel_id, string $step_data_json ) : array { $data = json_decode( $step_data_json, true ); if ( !is_array( $data ) ) { return []; } $graph = json_decode( (string) get_post_meta( $funnel_id, FunnelCpt::META_GRAPH, true ), true ); $nodes = []; foreach ( (array) ($graph['nodes'] ?? []) as $node ) { if ( isset( $node['id'] ) ) { $nodes[$node['id']] = $node; } } $rows = []; foreach ( $data as $step_id => $answers ) { if ( !is_array( $answers ) || str_starts_with( (string) $step_id, '_' ) ) { continue; } $node = $nodes[$step_id] ?? null; $config = (array) ($node['data']['config'] ?? []); $type = (string) ($node['type'] ?? ''); $step_label = $this->node_label( $node, (string) $step_id ); if ( 'choice' === $type && isset( $answers['selected'] ) ) { $options = []; foreach ( (array) ($config['options'] ?? []) as $opt ) { $options[(string) $opt['id']] = (string) ($opt['label'] ?? $opt['id']); } $labels = array_map( static fn( $id ) => $options[(string) $id] ?? (string) $id, (array) $answers['selected'] ); $rows[] = [ 'step_id' => (string) $step_id, 'field_id' => null, 'step' => $step_label, 'label' => $step_label, 'value' => implode( ', ', $labels ), ]; continue; } if ( 'input' === $type && array_key_exists( 'value', $answers ) ) { $rows[] = [ 'step_id' => (string) $step_id, 'field_id' => null, 'step' => $step_label, 'label' => $step_label, 'value' => $this->stringify( $answers['value'] ), ]; continue; } $fields = []; foreach ( (array) ($config['fields'] ?? []) as $field ) { $fields[(string) $field['id']] = (string) ($field['label'] ?? $field['id']); } foreach ( $answers as $field_id => $value ) { $rows[] = [ 'step_id' => (string) $step_id, 'field_id' => (string) $field_id, 'step' => $step_label, 'label' => $fields[(string) $field_id] ?? (string) $field_id, 'value' => $this->stringify( $value ), ]; } } return $rows; } public function lead_sections( int $funnel_id, string $step_data_json ) : array { $sections = []; foreach ( (array) apply_filters( 'funnelnode_lead_sections', [], $funnel_id, $step_data_json ) as $section ) { $rows = []; foreach ( (array) ($section['rows'] ?? []) as $row ) { $rows[] = [ 'label' => (string) ($row['label'] ?? ''), 'value' => (string) ($row['value'] ?? ''), ]; } if ( $rows ) { $sections[] = [ 'title' => (string) ($section['title'] ?? ''), 'rows' => $rows, ]; } } return $sections; } public function step_label( int $funnel_id, string $step_id ) : string { $graph = json_decode( (string) get_post_meta( $funnel_id, FunnelCpt::META_GRAPH, true ), true ); foreach ( (array) ($graph['nodes'] ?? []) as $node ) { if ( ($node['id'] ?? '') === $step_id ) { return $this->node_label( $node, $step_id ); } } return $step_id; } private function node_label( ?array $node, string $fallback ) : string { $label = (string) ($node['data']['label'] ?? ''); return ( '' !== $label ? $label : $fallback ); } private function stringify( mixed $value ) : string { if ( is_bool( $value ) ) { return ( $value ? __( 'yes', 'funnelnode' ) : __( 'no', 'funnelnode' ) ); } if ( is_array( $value ) ) { if ( isset( $value['file_name'] ) ) { return (string) $value['file_name']; } return implode( ', ', array_map( [$this, 'stringify'], $value ) ); } return (string) $value; } private function sanitize_earlier( mixed $raw ) : array { $steps = []; foreach ( array_slice( ( is_array( $raw ) ? $raw : [] ), 0, 100 ) as $item ) { if ( !is_array( $item ) ) { continue; } $id = sanitize_text_field( (string) ($item['step_id'] ?? '') ); if ( preg_match( self::STEP_RE, $id ) ) { $steps[] = [$id, $this->sanitize_answers( $item['step_data'] ?? [] )]; } } return $steps; } private function sanitize_answers( mixed $raw ) : array { if ( !is_array( $raw ) ) { return []; } $clean = []; $count = 0; foreach ( $raw as $key => $value ) { if ( ++$count > self::MAX_FIELDS_PER_STEP ) { break; } $key = sanitize_text_field( (string) $key ); if ( '' === $key || strlen( $key ) > 64 ) { continue; } $clean[$key] = $this->sanitize_value( $value, 0 ); } return $clean; } private function sanitize_value( mixed $value, int $depth ) : mixed { if ( $depth > 2 ) { return ''; } if ( is_bool( $value ) ) { return $value; } if ( is_int( $value ) || is_float( $value ) ) { return $value; } if ( is_array( $value ) ) { return array_map( fn( $v ) => $this->sanitize_value( $v, $depth + 1 ), array_slice( $value, 0, 50 ) ); } return substr( sanitize_textarea_field( (string) $value ), 0, self::MAX_VALUE_LEN ); } private function sanitize_extra( mixed $raw ) : array { $clean = []; foreach ( (array) $raw as $key => $value ) { $key = (string) $key; if ( !preg_match( '/^_[a-z][a-z0-9_]{0,30}$/', $key ) ) { continue; } if ( is_scalar( $value ) ) { $clean[$key] = substr( sanitize_text_field( (string) $value ), 0, 200 ); continue; } if ( !is_array( $value ) ) { continue; } $map = []; $count = 0; foreach ( $value as $k => $v ) { if ( ++$count > 30 || !is_scalar( $v ) ) { continue; } $k = sanitize_text_field( (string) $k ); if ( '' === $k || strlen( $k ) > 64 ) { continue; } $map[$k] = substr( sanitize_text_field( (string) $v ), 0, 200 ); } if ( $map ) { $clean[$key] = $map; } } return $clean; } public static function row_token( int $funnel_id, string $session_id ) : string { return hash_hmac( 'sha256', 'submission|' . $funnel_id . '|' . $session_id, (string) FUNNELNODE_HASH_SALT ); } private function owns_row( int $funnel_id, string $session_id, string $token ) : bool { $owns = '' !== $token && hash_equals( self::row_token( $funnel_id, $session_id ), $token ); return $owns; } public static function is_valid_session_id( string $session_id ) : bool { $valid = 1 === preg_match( self::SESSION_RE, $session_id ); return $valid; } private function is_rate_limited() : bool { $ip = $this->client_ip(); if ( '' === $ip ) { return false; } $key = 'funnelnode_rl_' . md5( $ip ); $count = (int) get_transient( $key ); if ( $count >= 120 ) { return true; } set_transient( $key, $count + 1, MINUTE_IN_SECONDS ); return false; } private function client_ip() : string { return sanitize_text_field( wp_unslash( (string) ($_SERVER['REMOTE_ADDR'] ?? '') ) ); } private function anonymize_ip( string $ip ) : string { if ( str_contains( $ip, ':' ) ) { $packed = @inet_pton( $ip ); if ( false === $packed ) { return ''; } $masked = substr( $packed, 0, 8 ) . str_repeat( "\x00", 8 ); return (string) inet_ntop( $masked ); } $parts = explode( '.', $ip ); if ( 4 === count( $parts ) ) { $parts[3] = '0'; return implode( '.', $parts ); } return ''; } private function funnel_settings( int $funnel_id ) : array { $raw = (string) get_post_meta( $funnel_id, FunnelCpt::META_SETTINGS, true ); $decoded = json_decode( $raw, true ); $funnel = ( is_array( $decoded ) ? $decoded : [] ); $global = Settings::all(); $funnel['privacy'] = array_merge( $global['privacy'], (array) ($funnel['privacy'] ?? []) ); $funnel['spam'] = array_merge( $global['spam'], (array) ($funnel['spam'] ?? []) ); return $funnel; } }