value|values ], * options [ value => label ] (select), source + depends (AJAX options), multiple (select), * remote [ [ key, label, required, auto ] ] or source (map), custom (map: allow own keys), * key_label / value_label (kv), secret (kv: mask values), rows (textarea), html (textarea keeps HTML). * * Types: text, textarea, number, select, toggle, value (form field or smartcode template), * field (one form field key), fields (several form field keys), map (remote key => value), * kv (rows of key => value), secret (masked per-feed secret), notice (help text / HTML). * * Values are smartcode templates: picking a form field stores {inputs.key}; "Custom" stores any * text with smartcodes. A default of 'auto:email' (auto:name, auto:first_name, auto:last_name, * auto:phone, auto:message) resolves to the first matching field of the form. * * @package FWREN */ namespace FWREN\Integrations; use FWREN\Fields; use FWREN\Logs; use FWREN\Schema; use FWREN\Settings; use FWREN\Smartcodes; defined( 'ABSPATH' ) || exit; abstract class Integration { /** Placeholder sent to the browser instead of a stored secret. */ const MASK = '__fwren_secret__'; /** @var array Run context: form_id, entry, values, feed. */ protected $ctx = array(); /** @var string[] Secret values to scrub from logs during a run. */ protected $secrets = array(); /* ------------------------------------------------------------------ * * Identity * ------------------------------------------------------------------ */ /** @return string Slug (feed `integration`). */ abstract public function slug(); /** @return string Title. */ abstract public function title(); /** @return string crm | email | chat | automation | sheets | other. */ public function category() { return 'other'; } /** @return string Inline SVG, or an icon name from \FWREN\Icons. */ public function logo() { return 'admin-plugins'; } /** @return string One-line description. */ public function description() { return ''; } /** @return string Help shown under the credential fields (may contain links/HTML). */ public function help() { return ''; } /** * Requirement that is not met (e.g. a plugin that must be active), or '' when available. * * @return string */ public function requirement() { return ''; } /** @return bool Whether "Verify connection" applies. */ public function can_verify() { return (bool) $this->credential_fields(); } /** @return string Label of the verify button. */ public function verify_label() { return __( 'Verify connection', 'fieldwren' ); } /** * Process a feed. * * @param array $feed Feed (settings in $feed['settings']). * @param array $entry Entry row. * @param array $values Values. * @return true|string|\WP_Error */ abstract public function process( array $feed, array $entry, array $values ); /* ------------------------------------------------------------------ * * Credentials * ------------------------------------------------------------------ */ /** * Global credential fields: key => [ label, type text|password|url|select|textarea, desc, * placeholder, options, required, default ]. type password = secret (masked, never logged). * * @return array */ public function credential_fields() { return array(); } /** @return bool Whether the integration needs credentials before feeds run. */ public function needs_credentials() { foreach ( $this->credential_fields() as $f ) { if ( ! empty( $f['required'] ) ) { return true; } } return false; } /** @return array Stored credentials (+ enabled, verified). */ public function creds() { return Settings::credentials( 'integrations', $this->slug() ); } /** @return string One credential. */ protected function cred( $key ) { $c = $this->creds(); return isset( $c[ $key ] ) && is_scalar( $c[ $key ] ) ? trim( (string) $c[ $key ] ) : ''; } /** @return bool Enabled in the global Integrations tab. */ public function is_enabled() { $c = $this->creds(); return isset( $c['enabled'] ) ? ! empty( $c['enabled'] ) : ! $this->needs_credentials(); } /** @return bool Required credentials are filled. */ public function is_configured() { $c = $this->creds(); foreach ( $this->credential_fields() as $k => $f ) { if ( ! empty( $f['required'] ) && '' === trim( (string) ( $c[ $k ] ?? '' ) ) ) { return false; } } return true; } /** * Check credentials against the API. * * @param array $creds Credentials. * @return true|string|\WP_Error */ public function verify( array $creds ) { return true; } /** * Hook after credentials are sanitized, before they are stored (exchange a grant code…). * * @param array $creds New credentials. * @param array $old Previous credentials. * @return array|\WP_Error */ public function before_save_credentials( array $creds, array $old ) { return $creds; } /** * Sanitize posted credentials; an empty secret keeps the stored one. * * @param array $input Raw input (unslashed). * @param array $old Stored credentials. * @return array */ public function sanitize_credentials( array $input, array $old ) { $out = array( 'enabled' => ! empty( $input['enabled'] ) ); foreach ( $this->credential_fields() as $k => $f ) { $type = $f['type'] ?? 'text'; $raw = isset( $input[ $k ] ) && is_scalar( $input[ $k ] ) ? trim( (string) $input[ $k ] ) : ''; if ( ! empty( $f['raw'] ) ) { // Keys such as a service-account JSON: kept verbatim (validated by the integration). $raw = isset( $input[ $k ] ) && is_scalar( $input[ $k ] ) ? trim( wp_check_invalid_utf8( (string) $input[ $k ] ) ) : ''; $out[ $k ] = ( '' === $raw || self::MASK === $raw ) && self::is_secret( $f ) ? (string) ( $old[ $k ] ?? '' ) : $raw; } elseif ( self::is_secret( $f ) ) { $out[ $k ] = ( '' === $raw || self::MASK === $raw ) ? (string) ( $old[ $k ] ?? '' ) : ( 'textarea' === $type ? sanitize_textarea_field( $raw ) : sanitize_text_field( $raw ) ); } elseif ( 'url' === $type ) { $out[ $k ] = esc_url_raw( $raw ); } elseif ( 'textarea' === $type ) { $out[ $k ] = sanitize_textarea_field( $raw ); } elseif ( 'select' === $type ) { $out[ $k ] = isset( $f['options'][ $raw ] ) ? $raw : (string) ( $f['default'] ?? '' ); } else { $out[ $k ] = sanitize_text_field( $raw ); } } foreach ( array( 'verified', 'verified_at', 'account', 'api_domain' ) as $keep ) { if ( isset( $old[ $keep ] ) ) { $out[ $keep ] = $old[ $keep ]; } } // Changed credentials need a fresh verification. foreach ( $this->credential_fields() as $k => $f ) { if ( (string) ( $old[ $k ] ?? '' ) !== (string) $out[ $k ] ) { unset( $out['verified'], $out['verified_at'], $out['account'] ); break; } } return $out; } /** @return array Credentials for the browser: secrets replaced by a masked hint. */ public function public_credentials() { $c = $this->creds(); $out = array(); foreach ( $this->credential_fields() as $k => $f ) { $v = (string) ( $c[ $k ] ?? '' ); if ( self::is_secret( $f ) ) { $out[ $k ] = '' === $v ? '' : self::mask_hint( $v ); } else { $out[ $k ] = '' === $v ? (string) ( $f['default'] ?? '' ) : $v; } } return $out; } /** @return bool Whether a credential field holds a secret (masked, never logged). */ public static function is_secret( array $f ) { return 'password' === ( $f['type'] ?? 'text' ) || ! empty( $f['secret'] ); } /** @return string •••• + last 4 characters. */ public static function mask_hint( $v ) { $v = (string) $v; return strlen( $v ) > 8 ? str_repeat( '•', 8 ) . substr( $v, -4 ) : str_repeat( '•', 8 ); } /** @return string[] Secret credential values (for log scrubbing). */ protected function secret_values( array $creds = null ) { $creds = null === $creds ? $this->creds() : $creds; $out = array(); foreach ( $this->credential_fields() as $k => $f ) { if ( self::is_secret( $f ) && ! empty( $creds[ $k ] ) && strlen( (string) $creds[ $k ] ) > 3 ) { $out[] = (string) $creds[ $k ]; // JSON keys: also scrub their inner secrets (private key, client secret…). $json = json_decode( (string) $creds[ $k ], true ); if ( is_array( $json ) ) { foreach ( array( 'private_key', 'private_key_id', 'client_secret', 'refresh_token' ) as $inner ) { if ( ! empty( $json[ $inner ] ) && is_string( $json[ $inner ] ) ) { $out[] = $json[ $inner ]; } } } } } return $out; } /* ------------------------------------------------------------------ * * Feed fields and remote options * ------------------------------------------------------------------ */ /** * Fields of a feed. * * @param int $form_id Form id. * @return array */ public function feed_fields( $form_id ) { return array(); } /** * Remote options for an AJAX source (lists, fields…). * * @param string $source Source id. * @param array $settings Current feed settings (dependencies). * @return array|\WP_Error Select: [ value => label ]; map: [ [ key, label, required, auto ] ]. */ public function options( $source, array $settings ) { return new \WP_Error( 'fwren_no_source', __( 'Unknown option source.', 'fieldwren' ) ); } /** * Cached remote options. * * @param string $source Source. * @param array $settings Feed settings. * @param bool $refresh Skip the cache. * @return array|\WP_Error */ public function cached_options( $source, array $settings, $refresh = false ) { $deps = array(); foreach ( $this->feed_fields( 0 ) as $f ) { if ( ( $f['source'] ?? '' ) === $source ) { foreach ( (array) ( $f['depends'] ?? array() ) as $d ) { $deps[ $d ] = $settings[ $d ] ?? ''; } } } $key = 'fwren_int_' . md5( $this->slug() . '|' . $source . '|' . wp_json_encode( $deps ) . '|' . md5( wp_json_encode( $this->creds() ) ) ); if ( ! $refresh ) { $hit = get_transient( $key ); if ( is_array( $hit ) ) { return $hit; } } $this->secrets = $this->secret_values(); $res = $this->options( $source, $settings ); if ( ! is_wp_error( $res ) ) { set_transient( $key, $res, 10 * MINUTE_IN_SECONDS ); } return $res; } /** @return array Feed defaults from the field defaults (auto:* resolved for the form). */ public function feed_defaults( $form_id ) { $auto = self::auto_values( $form_id ); $out = array(); foreach ( $this->feed_fields( $form_id ) as $f ) { if ( empty( $f['key'] ) || 'notice' === $f['type'] ) { continue; } $d = $f['default'] ?? self::empty_value( $f['type'], ! empty( $f['multiple'] ) ); if ( is_string( $d ) && 0 === strpos( $d, 'auto:' ) ) { $d = $auto[ substr( $d, 5 ) ] ?? ''; } if ( 'map' === $f['type'] && ! empty( $f['remote'] ) && ! $d ) { $d = array(); foreach ( $f['remote'] as $r ) { if ( ! empty( $r['auto'] ) && ! empty( $auto[ $r['auto'] ] ) ) { $d[ $r['key'] ] = $auto[ $r['auto'] ]; } } } $out[ $f['key'] ] = $d; } return $out; } /** @return mixed Empty value of a field type. */ protected static function empty_value( $type, $multiple = false ) { switch ( $type ) { case 'toggle': return false; case 'map': return array(); case 'kv': case 'fields': return array(); case 'select': return $multiple ? array() : ''; } return ''; } /** * Standard contact fields (email, first, last, phone) prefilled from the form. * * @param array $which Keys to include. * @return array */ protected function contact_fields( array $which = array( 'email', 'first_name', 'last_name', 'phone' ) ) { $all = array( 'email' => array( 'key' => 'email', 'type' => 'value', 'label' => __( 'Email', 'fieldwren' ), 'default' => 'auto:email', 'required' => true ), 'name' => array( 'key' => 'name', 'type' => 'value', 'label' => __( 'Full name', 'fieldwren' ), 'default' => 'auto:name' ), 'first_name' => array( 'key' => 'first_name', 'type' => 'value', 'label' => __( 'First name', 'fieldwren' ), 'default' => 'auto:first_name' ), 'last_name' => array( 'key' => 'last_name', 'type' => 'value', 'label' => __( 'Last name', 'fieldwren' ), 'default' => 'auto:last_name' ), 'phone' => array( 'key' => 'phone', 'type' => 'value', 'label' => __( 'Phone', 'fieldwren' ), 'default' => 'auto:phone' ), ); $out = array(); foreach ( $which as $k ) { if ( isset( $all[ $k ] ) ) { $out[] = $all[ $k ]; } } return $out; } /** * First field of each kind as a smartcode template. * * @param int $form_id Form id. * @return array email, name, first_name, last_name, phone, message, company. */ public static function auto_values( $form_id ) { $out = array( 'email' => '', 'name' => '', 'first_name' => '', 'last_name' => '', 'phone' => '', 'message' => '', 'company' => '', 'url' => '' ); if ( ! $form_id ) { return $out; } foreach ( Schema::fields( $form_id ) as $k => $f ) { switch ( $f['type'] ) { case 'email': $out['email'] = $out['email'] ? $out['email'] : '{inputs.' . $k . '}'; break; case 'name': if ( ! $out['name'] ) { $out['name'] = '{inputs.' . $k . '}'; $parts = (array) ( $f['parts'] ?? array() ); if ( in_array( 'first', $parts, true ) ) { $out['first_name'] = '{inputs.' . $k . '.first}'; $out['last_name'] = in_array( 'last', $parts, true ) ? '{inputs.' . $k . '.last}' : ''; } else { $out['first_name'] = '{inputs.' . $k . '}'; } } break; case 'phone': $out['phone'] = $out['phone'] ? $out['phone'] : '{inputs.' . $k . '}'; break; case 'textarea': $out['message'] = $out['message'] ? $out['message'] : '{inputs.' . $k . '}'; break; case 'url': $out['url'] = $out['url'] ? $out['url'] : '{inputs.' . $k . '}'; break; case 'text': if ( ! $out['company'] && preg_match( '/compan|organi[sz]ation|business/i', $k . ' ' . $f['label'] ) ) { $out['company'] = '{inputs.' . $k . '}'; } break; } } return $out; } /* ------------------------------------------------------------------ * * Running a feed * ------------------------------------------------------------------ */ /** * `fwren/feed/{slug}` callback. * * @param mixed $result Previous result. * @param array $feed Feed. * @param array $entry Entry. * @param array $values Values. * @return mixed */ public function handle( $result, $feed, $entry, $values ) { if ( null !== $result ) { return $result; } $feed = (array) $feed; $entry = (array) $entry; if ( '' !== $this->requirement() ) { return new \WP_Error( 'fwren_unavailable', $this->requirement() ); } if ( ! $this->is_enabled() ) { Logs::add( (int) ( $entry['form_id'] ?? 0 ), (int) ( $entry['id'] ?? 0 ), $this->slug(), 'skipped', $feed['name'] ?? $this->title(), __( 'The integration is turned off in Settings → Integrations.', 'fieldwren' ) ); return null; } if ( ! $this->is_configured() ) { return new \WP_Error( 'fwren_not_connected', sprintf( /* translators: %s integration */ __( '%s is not connected. Add the credentials in Settings → Integrations.', 'fieldwren' ), $this->title() ) ); } $feed['settings'] = array_merge( $this->feed_defaults( 0 ), (array) ( $feed['settings'] ?? array() ) ); $this->ctx = array( 'form_id' => (int) ( $entry['form_id'] ?? 0 ), 'entry' => $entry, 'values' => (array) $values, 'feed' => $feed, ); $this->secrets = $this->secret_values(); try { $res = $this->process( $feed, $entry, (array) $values ); } catch ( \Throwable $e ) { $res = new \WP_Error( 'fwren_feed_exception', $e->getMessage() ); } if ( is_wp_error( $res ) ) { $res = new \WP_Error( $res->get_error_code(), $this->scrub( $res->get_error_message() ) ); } $this->ctx = array(); return $res; } /** @return array Settings of the running feed. */ protected function settings() { return (array) ( $this->ctx['feed']['settings'] ?? array() ); } /** @return mixed One setting of the running feed. */ protected function setting( $key, $default = '' ) { $s = $this->settings(); return array_key_exists( $key, $s ) ? $s[ $key ] : $default; } /** * Resolve a template (smartcodes) against the running entry, as plain text. * * @param string $template Template. * @return string */ protected function val( $template ) { $template = is_scalar( $template ) ? (string) $template : ''; if ( '' === $template ) { return ''; } $out = Smartcodes::parse( $template, array( 'form_id' => $this->ctx['form_id'] ?? 0, 'values' => $this->ctx['values'] ?? array(), 'entry' => $this->ctx['entry'] ?? array(), ), 'text' ); return trim( html_entity_decode( wp_strip_all_tags( (string) $out, false ), ENT_QUOTES, 'UTF-8' ) ); } /** @return string A setting resolved as a template. */ protected function sval( $key ) { return $this->val( $this->setting( $key, '' ) ); } /** @return mixed Raw submitted value of a form field (key or key.sub). */ protected function raw( $key ) { $parts = explode( '.', (string) $key, 2 ); $v = $this->ctx['values'][ $parts[0] ] ?? ''; if ( isset( $parts[1] ) ) { $v = is_array( $v ) ? ( $v[ $parts[1] ] ?? '' ) : ''; } return $v; } /** @return bool Whether a field value counts as "yes" (consent, checkbox). */ protected function truthy( $v ) { if ( is_array( $v ) ) { return (bool) array_filter( array_map( 'strval', $v ), 'strlen' ); } $v = strtolower( trim( (string) $v ) ); return '' !== $v && ! in_array( $v, array( '0', 'no', 'false', 'off', 'not accepted', 'n' ), true ); } /** * Resolved map: remote key => value, empty values dropped. * * @param string $key Setting key of the map. * @return array */ protected function mapped( $key = 'map' ) { $out = array(); foreach ( (array) $this->setting( $key, array() ) as $remote => $tpl ) { if ( '' === (string) $remote || ! is_scalar( $tpl ) ) { continue; } $v = $this->val( $tpl ); if ( '' !== $v ) { $out[ (string) $remote ] = $v; } } return $out; } /** * Resolved key-value rows. * * @param string $key Setting key. * @return array key => value. */ protected function kv( $key ) { $out = array(); foreach ( (array) $this->setting( $key, array() ) as $row ) { if ( ! is_array( $row ) || '' === trim( (string) ( $row['key'] ?? '' ) ) ) { continue; } $out[ trim( (string) $row['key'] ) ] = $this->val( $row['value'] ?? '' ); } return $out; } /** * Contact of the running entry: email, name, first_name, last_name, phone. Unmapped values * fall back to the first email / name / phone field of the form. * * @return array */ protected function contact() { $auto = self::auto_values( $this->ctx['form_id'] ?? 0 ); $out = array(); foreach ( array( 'email', 'name', 'first_name', 'last_name', 'phone' ) as $k ) { $tpl = (string) $this->setting( $k, '' ); $out[ $k ] = $this->val( '' !== $tpl ? $tpl : $auto[ $k ] ); } $out['email'] = sanitize_email( $out['email'] ); if ( '' === $out['name'] ) { $out['name'] = trim( $out['first_name'] . ' ' . $out['last_name'] ); } if ( '' === $out['first_name'] && '' === $out['last_name'] && '' !== $out['name'] ) { $bits = preg_split( '/\s+/', $out['name'], 2 ); $out['first_name'] = $bits[0]; $out['last_name'] = $bits[1] ?? ''; } elseif ( $out['first_name'] && ! $out['last_name'] && false !== strpos( $out['first_name'], ' ' ) && ! $this->setting( 'last_name', '' ) ) { $bits = preg_split( '/\s+/', $out['first_name'], 2 ); $out['first_name'] = $bits[0]; $out['last_name'] = $bits[1] ?? ''; } return $out; } /** @return \WP_Error|null Error when the contact has no valid email. */ protected function require_email( array $c ) { return is_email( $c['email'] ) ? null : new \WP_Error( 'fwren_no_email', __( 'No valid email address in this entry; nothing was sent.', 'fieldwren' ) ); } /** @return string[] Comma list (template) resolved and split. */ protected function list_of( $template ) { $v = $this->val( $template ); return array_values( array_unique( array_filter( array_map( 'trim', preg_split( '/[,\n]+/', $v ) ), 'strlen' ) ) ); } /** * Every visible, non-empty value: [ key => [ label, value ] ] (text). With $only, those fields. * * @param array $only Field keys (empty = all). * @return array */ protected function data_rows( array $only = array() ) { $form_id = (int) ( $this->ctx['form_id'] ?? 0 ); $schema = Schema::get( $form_id ); $values = (array) ( $this->ctx['values'] ?? array() ); $rows = array(); foreach ( $schema['order'] as $key ) { $f = $schema['fields'][ $key ] ?? null; if ( ! $f || ! array_key_exists( $key, $values ) || ! empty( $f['sensitive'] ) || ( $only && ! in_array( $key, $only, true ) ) ) { continue; } $type = Fields::get( $f['type'] ); if ( ! $type || $type->is_empty( $values[ $key ] ) ) { continue; } $rows[ $key ] = array( Schema::label( $f ), html_entity_decode( wp_strip_all_tags( (string) $type->format( $values[ $key ], $f, 'text' ) ), ENT_QUOTES, 'UTF-8' ) ); } return $rows; } /** @return array Entry meta for payloads. */ protected function entry_meta() { $e = (array) ( $this->ctx['entry'] ?? array() ); $form_id = (int) ( $this->ctx['form_id'] ?? 0 ); return array( 'form_id' => $form_id, 'form_title' => get_the_title( $form_id ), 'entry_id' => (int) ( $e['id'] ?? 0 ), 'serial' => (int) ( $e['serial'] ?? 0 ), 'status' => (string) ( $e['status'] ?? '' ), 'created_at' => isset( $e['created_at'] ) ? gmdate( 'c', strtotime( $e['created_at'] . ' UTC' ) ) : gmdate( 'c' ), 'source_url' => (string) ( $e['source_url'] ?? '' ), 'entry_url' => ! empty( $e['id'] ) ? admin_url( 'admin.php?page=fwren-entries&entry=' . (int) $e['id'] ) : '', ); } /** @return string Title of a message: "New submission: Form". */ protected function default_title() { /* translators: %s form title */ return sprintf( __( 'New submission: %s', 'fieldwren' ), get_the_title( (int) ( $this->ctx['form_id'] ?? 0 ) ) ); } /** * Feed fields of a chat message (title, which data, custom text, entry link). * * @return array */ protected function message_fields() { return array( array( 'key' => 'title', 'type' => 'text', 'label' => __( 'Title', 'fieldwren' ), 'default' => __( 'New submission: {form_title}', 'fieldwren' ) ), array( 'key' => 'content', 'type' => 'select', 'label' => __( 'Content', 'fieldwren' ), 'default' => 'all', 'no_empty' => true, 'options' => array( 'all' => __( 'All submitted data', 'fieldwren' ), 'selected' => __( 'Selected fields', 'fieldwren' ), 'message' => __( 'Custom message only', 'fieldwren' ), ), ), array( 'key' => 'fields', 'type' => 'fields', 'label' => __( 'Fields', 'fieldwren' ), 'show_if' => array( 'content' => 'selected' ) ), array( 'key' => 'message', 'type' => 'textarea', 'label' => __( 'Message', 'fieldwren' ), 'rows' => 3, 'desc' => __( 'Optional text above the data (or the whole message with "Custom message only").', 'fieldwren' ) ), array( 'key' => 'link', 'type' => 'toggle', 'label' => __( 'Entry link', 'fieldwren' ), 'text' => __( 'Add a link to the entry in WordPress', 'fieldwren' ), 'default' => true ), ); } /** @return array [ label, value ] rows the message should show. */ protected function message_rows() { $s = $this->settings(); if ( 'message' === ( $s['content'] ?? 'all' ) ) { return array(); } return array_values( $this->data_rows( 'selected' === ( $s['content'] ?? '' ) ? (array) ( $s['fields'] ?? array() ) : array() ) ); } /** @return string Shortened text. */ protected static function cut( $s, $max ) { $s = (string) $s; if ( function_exists( 'mb_strlen' ) ) { return mb_strlen( $s ) > $max ? mb_substr( $s, 0, $max - 1 ) . '…' : $s; } return strlen( $s ) > $max ? substr( $s, 0, $max - 3 ) . '...' : $s; } /** * Uploaded files (and signatures) of the running entry. * * @param string[] $only Field keys (empty = every upload field). * @return array[] [ name, abs, size, type, field ] — only files that exist inside the upload folder. */ protected function entry_files( array $only = array() ) { $form_id = (int) ( $this->ctx['form_id'] ?? 0 ); $schema = Schema::get( $form_id ); $base = realpath( \FWREN\Install::upload_dir() ); $out = array(); if ( ! $base ) { return $out; } $base = trailingslashit( wp_normalize_path( $base ) ); foreach ( (array) ( $this->ctx['values'] ?? array() ) as $key => $v ) { $f = $schema['fields'][ $key ] ?? null; if ( ! $f || ( empty( $f['is_upload'] ) && empty( $f['signature'] ) ) || ( $only && ! in_array( $key, $only, true ) ) ) { continue; } $list = is_array( $v ) && isset( $v['path'] ) ? array( $v ) : (array) $v; foreach ( $list as $file ) { if ( ! is_array( $file ) || empty( $file['path'] ) || false !== strpos( (string) $file['path'], '..' ) ) { continue; } $abs = realpath( $base . ltrim( (string) $file['path'], '/' ) ); if ( ! $abs || 0 !== strpos( wp_normalize_path( $abs ), $base ) || ! is_file( $abs ) ) { continue; } $name = sanitize_file_name( (string) ( $file['name'] ?? basename( $abs ) ) ); $out[] = array( 'name' => '' !== $name ? $name : basename( $abs ), 'abs' => $abs, 'size' => (int) filesize( $abs ), 'type' => ! empty( $file['type'] ) ? (string) $file['type'] : 'application/octet-stream', 'field' => (string) $key, ); } } return $out; } /** * Name of an uploaded file from a template: {file.name}, {file.base}, {file.ext}, {file.field}, * {file.index} plus any smartcode. The original extension is kept. * * @param string $template Template. * @param array $file entry_files() row. * @param int $index 1-based index. * @return string */ protected function file_name( $template, array $file, $index ) { $ext = (string) pathinfo( $file['name'], PATHINFO_EXTENSION ); $name = strtr( '' !== trim( (string) $template ) ? (string) $template : '{file.name}', array( '{file.name}' => $file['name'], '{file.base}' => (string) pathinfo( $file['name'], PATHINFO_FILENAME ), '{file.ext}' => $ext, '{file.field}' => $file['field'], '{file.index}' => (string) $index, ) ); $name = self::clean_name( $this->val( $name ) ); if ( '' === $name ) { $name = $file['name']; } if ( '' !== $ext && strtolower( (string) pathinfo( $name, PATHINFO_EXTENSION ) ) !== strtolower( $ext ) ) { $name .= '.' . $ext; } return $name; } /** @return string File or folder name without path separators or reserved characters. */ protected static function clean_name( $s ) { $s = preg_replace( '#[\\\\/:*?"<>|\x00-\x1f]+#', '-', (string) $s ); return trim( self::cut( $s, 200 ), " .-\t" ); } /** * The entry as a file: JSON (key → label/value plus _meta) or CSV (header row + value row). * * @param string $format json | csv. * @return array [ content, mime, ext ]. */ protected function entry_export( $format ) { $rows = $this->data_rows(); if ( 'csv' === $format ) { $fh = fopen( 'php://temp', 'r+' ); // phpcs:ignore WordPress.WP.AlternativeFunctions $h = array( 'Entry ID', 'Date' ); $v = array( (string) ( $this->ctx['entry']['id'] ?? '' ), gmdate( 'Y-m-d H:i:s' ) ); foreach ( $rows as $r ) { $h[] = $r[0]; $v[] = ( '' !== $r[1] && in_array( $r[1][0], array( '=', '+', '-', '@' ), true ) && ! is_numeric( $r[1] ) ) ? "'" . $r[1] : $r[1]; } fputcsv( $fh, $h ); fputcsv( $fh, $v ); rewind( $fh ); $csv = "\xEF\xBB\xBF" . stream_get_contents( $fh ); fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions return array( $csv, 'text/csv', 'csv' ); } $data = array(); foreach ( $rows as $k => $r ) { $data[ $k ] = array( 'label' => $r[0], 'value' => $r[1] ); } return array( (string) wp_json_encode( array( 'fields' => $data, '_meta' => $this->entry_meta() ), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ), 'application/json', 'json' ); } /** @return array Feed fields shared by the file-storage integrations. */ protected function storage_fields() { return array( array( 'key' => 'fields', 'type' => 'fields', 'label' => __( 'Upload fields', 'fieldwren' ), 'desc' => __( 'None ticked = every file upload and signature field.', 'fieldwren' ) ), array( 'key' => 'file_name', 'type' => 'text', 'label' => __( 'File name', 'fieldwren' ), 'default' => '{file.name}', 'desc' => __( 'Placeholders: {file.name}, {file.base}, {file.ext}, {file.field}, {file.index}, plus smartcodes such as {entry.id}. The extension is kept.', 'fieldwren' ) ), array( 'key' => 'export', 'type' => 'select', 'label' => __( 'Entry file', 'fieldwren' ), 'default' => '', 'no_empty' => true, 'options' => array( '' => __( 'None', 'fieldwren' ), 'json' => __( 'Also upload the entry as JSON', 'fieldwren' ), 'csv' => __( 'Also upload the entry as CSV', 'fieldwren' ) ) ), array( 'key' => 'export_name', 'type' => 'text', 'label' => __( 'Entry file name', 'fieldwren' ), 'default' => 'entry-{entry.id}', 'show_if' => array( 'export' => array( 'json', 'csv' ) ) ), ); } /** * Files a storage feed should upload: [ name, mime, content callback|string, size ]. * * @param array $s Feed settings. * @return array[] */ protected function storage_items( array $s ) { $items = array(); foreach ( $this->entry_files( (array) ( $s['fields'] ?? array() ) ) as $i => $f ) { $items[] = array( 'name' => $this->file_name( $s['file_name'] ?? '', $f, $i + 1 ), 'mime' => $f['type'], 'abs' => $f['abs'], 'size' => $f['size'] ); } if ( in_array( $s['export'] ?? '', array( 'json', 'csv' ), true ) ) { list( $content, $mime, $ext ) = $this->entry_export( $s['export'] ); $base = self::clean_name( $this->val( $s['export_name'] ?? '' ) ); $items[] = array( 'name' => ( '' !== $base ? $base : 'entry' ) . '.' . $ext, 'mime' => $mime, 'content' => $content, 'size' => strlen( $content ) ); } return $items; } /** @return string|\WP_Error Content of a storage item. */ protected static function item_content( array $item ) { if ( isset( $item['content'] ) ) { return $item['content']; } $c = file_get_contents( $item['abs'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions return false === $c ? new \WP_Error( 'fwren_read', sprintf( /* translators: %s file */ __( 'Could not read %s.', 'fieldwren' ), $item['name'] ) ) : $c; } /** * Resolve a template in HTML mode ({all_data} as a table), kept to safe HTML. * * @param string $template Template. * @return string */ protected function html_val( $template ) { $out = (string) Smartcodes::parse( (string) $template, array( 'form_id' => $this->ctx['form_id'] ?? 0, 'values' => $this->ctx['values'] ?? array(), 'entry' => $this->ctx['entry'] ?? array(), ), 'html' ); $out = false === strpos( $out, '<' ) ? nl2br( $out ) : $out; return trim( wp_kses_post( $out ) ); } /** @return string Entry IP (when stored). */ protected function ip() { return (string) ( $this->ctx['entry']['ip'] ?? '' ); } /* ------------------------------------------------------------------ * * HTTP * ------------------------------------------------------------------ */ /** * HTTP request with logging (no secrets) and error extraction. * * @param string $method GET | POST | PUT | PATCH | DELETE. * @param string $url URL. * @param array $args headers, body (array|string), json (bool), form (bool), query (array), * auth ([ user, pass ] Basic), timeout, redirection, ok ( int[] extra OK codes ). * @return array|\WP_Error [ code, body (decoded JSON or string), headers, raw ]. */ protected function http( $method, $url, array $args = array() ) { $method = strtoupper( $method ); $headers = (array) ( $args['headers'] ?? array() ); if ( ! empty( $args['query'] ) ) { $url = add_query_arg( array_map( 'rawurlencode', (array) $args['query'] ), $url ); } $body = $args['body'] ?? null; if ( is_array( $body ) || is_object( $body ) ) { if ( ! empty( $args['form'] ) ) { $body = http_build_query( (array) $body, '', '&' ); $headers['Content-Type'] = $headers['Content-Type'] ?? 'application/x-www-form-urlencoded'; } else { $body = wp_json_encode( $body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); $headers['Content-Type'] = $headers['Content-Type'] ?? 'application/json'; } } if ( ! empty( $args['auth'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( $args['auth'][0] . ':' . ( $args['auth'][1] ?? '' ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions } $headers['Accept'] = $headers['Accept'] ?? 'application/json'; foreach ( $headers as $h => $v ) { if ( preg_match( '/authorization|token|key|secret|signature/i', $h ) && is_string( $v ) && strlen( $v ) > 6 ) { $this->secrets[] = $v; $this->secrets[] = preg_replace( '/^\S+\s+/', '', $v ); } } $req = array( 'method' => $method, 'headers' => $headers, 'timeout' => (int) ( $args['timeout'] ?? 20 ), 'redirection' => (int) ( $args['redirection'] ?? 3 ), 'user-agent' => 'Fieldwren/' . ( defined( 'FWREN_VERSION' ) ? FWREN_VERSION : '1' ) . '; ' . home_url( '/' ), ); if ( null !== $body && 'GET' !== $method ) { $req['body'] = $body; } $req = apply_filters( 'fwren/integration/request', $req, $url, $this->slug() ); $start = microtime( true ); $res = wp_remote_request( $url, $req ); $ms = (int) round( ( microtime( true ) - $start ) * 1000 ); if ( is_wp_error( $res ) ) { $this->log( $method, $url, 0, ! empty( $args['binary'] ) ? null : $body, $res->get_error_message(), $ms, is_string( $body ) ? strlen( $body ) : 0 ); return $res; } $code = (int) wp_remote_retrieve_response_code( $res ); $raw = (string) wp_remote_retrieve_body( $res ); $json = json_decode( $raw, true ); $data = null === $json && 'null' !== trim( $raw ) ? $raw : $json; $this->log( $method, $url, $code, ! empty( $args['binary'] ) ? null : $body, $raw, $ms, is_string( $body ) ? strlen( $body ) : 0 ); $out = array( 'code' => $code, 'body' => $data, 'headers' => wp_remote_retrieve_headers( $res ), 'raw' => $raw, ); if ( $code >= 400 && ! in_array( $code, (array) ( $args['ok'] ?? array() ), true ) ) { $msg = $this->error_message( $data, $code ); return new \WP_Error( 'fwren_http_' . $code, $this->scrub( sprintf( '%s (HTTP %d)', $msg ? $msg : __( 'Request failed', 'fieldwren' ), $code ) ), $out ); } return $out; } /** * Error text out of an API response. * * @param mixed $body Decoded body. * @param int $code Status. * @return string */ protected function error_message( $body, $code ) { if ( is_string( $body ) ) { return substr( trim( wp_strip_all_tags( $body ) ), 0, 300 ); } if ( ! is_array( $body ) ) { return ''; } foreach ( array( 'detail', 'message', 'error_description', 'title', 'msg', 'Message', 'error', 'errors' ) as $k ) { if ( empty( $body[ $k ] ) ) { continue; } $v = $body[ $k ]; if ( is_string( $v ) ) { $extra = ( 'title' === $k && ! empty( $body['detail'] ) ) ? ': ' . $body['detail'] : ''; return substr( $v . $extra, 0, 400 ); } if ( is_array( $v ) ) { $first = isset( $v[0] ) ? $v[0] : reset( $v ); if ( is_string( $first ) ) { return substr( $first, 0, 400 ); } if ( is_array( $first ) ) { foreach ( array( 'message', 'detail', 'title', 'msg' ) as $kk ) { if ( ! empty( $first[ $kk ] ) && is_string( $first[ $kk ] ) ) { return substr( $first[ $kk ], 0, 400 ); } } } foreach ( array( 'message', 'detail' ) as $kk ) { if ( ! empty( $v[ $kk ] ) && is_string( $v[ $kk ] ) ) { return substr( $v[ $kk ], 0, 400 ); } } } } return ''; } /** Replace known secrets in a string. */ protected function scrub( $s ) { $s = (string) $s; foreach ( array_unique( array_filter( $this->secrets, 'strlen' ) ) as $secret ) { if ( strlen( $secret ) > 3 ) { $s = str_replace( $secret, '***', $s ); } } // Query secrets. $s = preg_replace( '/([?&](?:api_?key|apikey|api_token|token|key|secret|access_token|refresh_token|client_secret|password|auth)=)[^&\s"\']+/i', '$1***', $s ); return $s; } /** Log one request (only while a feed runs, when request logging is on). */ protected function log( $method, $url, $code, $request_body, $response, $ms, $bytes = 0 ) { if ( empty( $this->ctx['form_id'] ) || ! Manager::setting( 'log_requests', true ) ) { return; } $p = wp_parse_url( $url ); $path = ( $p['host'] ?? '' ) . ( $p['path'] ?? '' ); $req = ''; if ( is_string( $request_body ) && '' !== $request_body ) { $dec = json_decode( $request_body, true ); if ( ! is_array( $dec ) ) { parse_str( $request_body, $dec ); } $req = is_array( $dec ) && $dec ? 'keys: ' . implode( ', ', array_slice( array_map( 'strval', array_keys( $dec ) ), 0, 25 ) ) . ' · ' : ''; $req .= strlen( $request_body ) . ' bytes'; } elseif ( null === $request_body && $bytes ) { $req = $bytes . ' bytes (file upload)'; } $resp = substr( preg_replace( '/\s+/', ' ', wp_strip_all_tags( (string) $response ) ), 0, 400 ); Logs::add( (int) $this->ctx['form_id'], (int) ( $this->ctx['entry']['id'] ?? 0 ), $this->slug(), 'info', $this->scrub( sprintf( '%s %s → %s (%d ms)', $method, $path, $code ? $code : 'error', $ms ) ), $this->scrub( trim( ( $req ? __( 'Request', 'fieldwren' ) . ': ' . $req . "\n" : '' ) . __( 'Response', 'fieldwren' ) . ': ' . $resp ) ) ); } /** @return array Body of a successful http() result or the error. */ protected static function body( $res ) { return is_wp_error( $res ) ? $res : ( is_array( $res['body'] ) ? $res['body'] : array() ); } /** * Build options [ value => label ] from a list of rows. * * @param array $rows Rows. * @param string $id Id key. * @param string $label Label key (dot path allowed). * @return array */ protected static function pluck( $rows, $id, $label ) { $out = array(); foreach ( (array) $rows as $r ) { $r = (array) $r; $v = self::dig( $r, $id ); if ( null === $v || '' === (string) $v ) { continue; } $l = self::dig( $r, $label ); $out[ (string) $v ] = is_scalar( $l ) && '' !== (string) $l ? (string) $l : (string) $v; } return $out; } /** @return mixed Nested value by dot path. */ protected static function dig( $arr, $path ) { foreach ( explode( '.', $path ) as $k ) { if ( ! is_array( $arr ) || ! array_key_exists( $k, $arr ) ) { return null; } $arr = $arr[ $k ]; } return $arr; } /** @return string Generic SVG wrapper: a coloured tile with a short monogram. */ protected static function tile( $color, $text, $fg = '#fff' ) { return ''; } }