slug() ] = $obj;
}
}
return self::$items;
}
/** @return Integration|null */
public static function get( $slug ) {
$all = self::all();
return $all[ $slug ] ?? null;
}
/** @return array Category labels. */
public static function categories() {
return array(
'crm' => __( 'CRM', 'fieldwren' ),
'email' => __( 'Email marketing', 'fieldwren' ),
'chat' => __( 'Chat & SMS', 'fieldwren' ),
'automation' => __( 'Automation', 'fieldwren' ),
'sheets' => __( 'Sheets & databases', 'fieldwren' ),
'other' => __( 'Productivity & other', 'fieldwren' ),
);
}
/** Each integration answers its own feeds. */
public static function register_feed_hooks() {
foreach ( self::all() as $slug => $int ) {
add_filter( 'fwren/feed/' . $slug, array( $int, 'handle' ), 10, 4 );
}
}
/** @return mixed Module setting (integrations.general). */
public static function setting( $key, $default = null ) {
$g = Settings::credentials( 'integrations', 'general' );
return array_key_exists( $key, $g ) ? $g[ $key ] : $default;
}
/** @return string Capability of every integrations screen and action. */
private static function cap() {
return apply_filters( 'fwren/integrations/capability', 'fwren_manage_settings' );
}
/* ------------------------------------------------------------------ *
* Resend
* ------------------------------------------------------------------ */
/**
* Send an entry to its form's integration feeds again (conditions still apply).
*
* @param int $entry_id Entry id.
* @param string $feed_id One feed (runs even when the feed is paused); empty = every enabled feed.
* @return array|\WP_Error feed id => true|string|WP_Error|'skipped'.
*/
public static function resend( $entry_id, $feed_id = '' ) {
$entry = Entries::get( (int) $entry_id );
if ( ! $entry ) {
return new \WP_Error( 'fwren_no_entry', __( 'Entry not found.', 'fieldwren' ) );
}
$values = (array) $entry['response'];
$out = array();
foreach ( self::form_feeds( (int) $entry['form_id'] ) as $feed ) {
if ( $feed_id ? (string) $feed['id'] !== (string) $feed_id : empty( $feed['enabled'] ) ) {
continue;
}
if ( ! empty( $feed['conditions']['enabled'] ) && ! Conditions::passes( $feed['conditions'], $values ) ) {
$out[ $feed['id'] ] = 'skipped';
continue;
}
$slug = sanitize_key( $feed['integration'] );
try {
$res = apply_filters( 'fwren/feed/' . $slug, null, $feed, $entry, $values );
} catch ( \Throwable $e ) {
$res = new \WP_Error( 'fwren_feed_exception', $e->getMessage() );
}
if ( null === $res ) {
$out[ $feed['id'] ] = 'skipped';
continue;
}
$ok = ! is_wp_error( $res );
/* translators: %s feed name */
Logs::add( (int) $entry['form_id'], (int) $entry['id'], $slug, $ok ? 'success' : 'failed', sprintf( __( '%s (resent)', 'fieldwren' ), $feed['name'] ?? $slug ), $ok ? ( is_string( $res ) ? $res : __( 'Sent.', 'fieldwren' ) ) : $res->get_error_message() );
if ( ! $ok ) {
do_action( 'fwren/feed_failed', $feed, $entry, $res );
}
$out[ $feed['id'] ] = $res;
}
return $out;
}
/**
* Resend several entries.
*
* @param int[] $entry_ids Ids.
* @return array [ sent, failed, skipped ].
*/
public static function bulk_resend( array $entry_ids ) {
$c = array( 'sent' => 0, 'failed' => 0, 'skipped' => 0 );
foreach ( array_filter( array_map( 'absint', $entry_ids ) ) as $id ) {
$r = self::resend( $id );
foreach ( is_wp_error( $r ) ? array( $r ) : $r as $res ) {
if ( is_wp_error( $res ) ) {
$c['failed']++;
} elseif ( 'skipped' === $res ) {
$c['skipped']++;
} else {
$c['sent']++;
}
}
}
return $c;
}
/** @return array Feeds of a form that belong to this module. */
public static function form_feeds( $form_id ) {
$all = self::all();
return array_values(
array_filter(
Form::feeds( (int) $form_id ),
static function ( $f ) use ( $all ) {
return is_array( $f ) && ! empty( $f['id'] ) && isset( $all[ $f['integration'] ?? '' ] );
}
)
);
}
/** Bulk action label (if the entries screen offers the filter). */
public static function bulk_actions( $actions ) {
$actions = (array) $actions;
$actions['fwren_resend_integrations'] = __( 'Resend to integrations', 'fieldwren' );
return $actions;
}
/** Bulk action handler (if the entries screen fires it). */
public static function handle_bulk_action( $action, $ids ) {
if ( 'fwren_resend_integrations' === $action && current_user_can( self::cap() ) ) {
self::bulk_resend( (array) $ids );
}
}
/** "Integrations" box on the entry screen with per-feed resend buttons. */
public static function entry_box( $entry ) {
$entry = (array) $entry;
if ( empty( $entry['id'] ) || ! current_user_can( self::cap() ) ) {
return;
}
$feeds = self::form_feeds( (int) $entry['form_id'] );
if ( ! $feeds ) {
return;
}
echo '
' . esc_html__( 'Integrations', 'fieldwren' ) . ' ';
foreach ( $feeds as $f ) {
$int = self::get( $f['integration'] );
echo '' . esc_html( $f['name'] ?: $int->title() ) . ' (' . esc_html( $int->title() ) . ') ' . esc_html__( 'Resend', 'fieldwren' ) . ' ';
}
echo ' ' . esc_html__( 'Resend to all integrations', 'fieldwren' ) . '
';
echo '
';
}
/* ------------------------------------------------------------------ *
* Failed-integration email
* ------------------------------------------------------------------ */
/**
* Email the admin when a feed fails (one email per feed per 10 minutes).
*
* @param array $feed Feed.
* @param array $entry Entry.
* @param \WP_Error $error Error.
*/
public static function feed_failed( $feed, $entry, $error ) {
if ( ! self::setting( 'failed_email', false ) ) {
return;
}
$feed = (array) $feed;
$entry = (array) $entry;
$int = self::get( $feed['integration'] ?? '' );
if ( ! $int ) {
return;
}
$lock = 'fwren_int_fail_' . md5( ( $entry['form_id'] ?? 0 ) . '|' . ( $feed['id'] ?? '' ) );
if ( get_transient( $lock ) ) {
return;
}
set_transient( $lock, 1, (int) apply_filters( 'fwren/integrations/failed_email_throttle', 10 * MINUTE_IN_SECONDS ) );
$to = \FWREN\Notifications::emails( (string) self::setting( 'failed_email_to', get_option( 'admin_email' ) ) );
if ( ! $to ) {
$to = array( get_option( 'admin_email' ) );
}
$form_id = (int) ( $entry['form_id'] ?? 0 );
$msg = is_wp_error( $error ) ? $error->get_error_message() : (string) $error;
/* translators: 1: integration, 2: form */
$subject = sprintf( __( '[%1$s] Integration failed: %2$s', 'fieldwren' ), wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), $int->title() . ' – ' . get_the_title( $form_id ) );
$rows = array(
__( 'Form', 'fieldwren' ) => get_the_title( $form_id ) . ' (#' . $form_id . ')',
__( 'Feed', 'fieldwren' ) => ( $feed['name'] ?? '' ) . ' (' . $int->title() . ')',
__( 'Entry', 'fieldwren' ) => ! empty( $entry['id'] ) ? '#' . (int) $entry['id'] : '—',
__( 'Error', 'fieldwren' ) => $msg,
__( 'Time', 'fieldwren' ) => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ),
);
$body = '' . esc_html__( 'An integration feed could not send a form entry.', 'fieldwren' ) . '
';
foreach ( $rows as $k => $v ) {
$body .= '' . esc_html( $k ) . ' ' . esc_html( $v ) . ' ';
}
$body .= '
';
if ( ! empty( $entry['id'] ) ) {
$body .= '' . esc_html__( 'Open the entry', 'fieldwren' ) . ' · ' . esc_html__( 'Fix the cause, then use "Resend to integrations" on the entry.', 'fieldwren' ) . '
';
}
$body .= '' . esc_html__( 'Further failures of this feed within 10 minutes are not emailed. Turn these emails off in Settings → Integrations.', 'fieldwren' ) . '
';
$html = class_exists( '\FWREN\Notifications' ) ? \FWREN\Notifications::wrap( $body, $subject, $form_id ) : $body;
wp_mail( $to, $subject, $html, array( 'Content-Type: text/html; charset=UTF-8' ) );
}
/* ------------------------------------------------------------------ *
* Assets
* ------------------------------------------------------------------ */
/** Enqueue on the settings screens only. */
public static function enqueue() {
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
if ( ! in_array( $page, array( 'fwren-form-settings', 'fwren-settings', 'fwren-entries' ), true ) ) {
return;
}
$url = plugins_url( 'assets/', __FILE__ );
$ver = defined( 'FWREN_VERSION' ) ? FWREN_VERSION : '1.0.0';
wp_enqueue_style( 'fwren-integrations', $url . 'integrations.css', array(), $ver );
wp_enqueue_script( 'fwren-integrations', $url . 'integrations.js', array(), $ver, true );
wp_localize_script(
'fwren-integrations',
'FWRENIntL10n',
array(
'ajax' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( self::NONCE ),
'i18n' => self::i18n(),
)
);
}
/** @return array UI strings. */
private static function i18n() {
return array(
'addFeed' => __( 'Add integration feed', 'fieldwren' ),
'noFeeds' => __( 'No integration feeds yet. Add one to send entries of this form to another service.', 'fieldwren' ),
'name' => __( 'Feed name', 'fieldwren' ),
'integration' => __( 'Integration', 'fieldwren' ),
'status' => __( 'Status', 'fieldwren' ),
'actions' => __( 'Actions', 'fieldwren' ),
'edit' => __( 'Edit', 'fieldwren' ),
'duplicate' => __( 'Duplicate', 'fieldwren' ),
'delete' => __( 'Delete', 'fieldwren' ),
'confirmDel' => __( 'Delete this feed?', 'fieldwren' ),
'done' => __( 'Done', 'fieldwren' ),
'cancel' => __( 'Cancel', 'fieldwren' ),
'back' => __( '← All feeds', 'fieldwren' ),
'choose' => __( 'Choose an integration', 'fieldwren' ),
'notEnabled' => __( 'Turned off or not connected – set it up in Settings → Integrations.', 'fieldwren' ),
'openSettings' => __( 'Open settings', 'fieldwren' ),
'unsaved' => __( 'Feed changes are not saved yet – click Save.', 'fieldwren' ),
'none' => __( '— None —', 'fieldwren' ),
'custom' => __( 'Custom value / smartcodes…', 'fieldwren' ),
'smartcodes' => __( 'Insert smartcode', 'fieldwren' ),
'loading' => __( 'Loading…', 'fieldwren' ),
'refresh' => __( 'Refresh', 'fieldwren' ),
'pickFirst' => __( 'Choose the setting above first.', 'fieldwren' ),
'addRow' => __( 'Add row', 'fieldwren' ),
'addField' => __( 'Add field', 'fieldwren' ),
'remove' => __( 'Remove', 'fieldwren' ),
'key' => __( 'Key', 'fieldwren' ),
'value' => __( 'Value', 'fieldwren' ),
'remoteField' => __( 'Remote field', 'fieldwren' ),
'formField' => __( 'Form field / value', 'fieldwren' ),
'conditions' => __( 'Conditional logic', 'fieldwren' ),
'condEnable' => __( 'Run this feed only when conditions match', 'fieldwren' ),
'matchAll' => __( 'All rules match', 'fieldwren' ),
'matchAny' => __( 'Any rule matches', 'fieldwren' ),
'addRule' => __( 'Add rule', 'fieldwren' ),
'enabled' => __( 'Enabled', 'fieldwren' ),
'paused' => __( 'Paused', 'fieldwren' ),
'newFeed' => __( 'New feed', 'fieldwren' ),
'copy' => __( '(copy)', 'fieldwren' ),
'saving' => __( 'Saving…', 'fieldwren' ),
'saved' => __( 'Saved.', 'fieldwren' ),
'verifying' => __( 'Checking…', 'fieldwren' ),
'confirmDisc' => __( 'Remove the stored credentials of this integration?', 'fieldwren' ),
'error' => __( 'Something went wrong.', 'fieldwren' ),
'secretKeep' => __( 'Saved – leave as is to keep', 'fieldwren' ),
'required' => __( 'Required', 'fieldwren' ),
'copied' => __( 'Copied.', 'fieldwren' ),
'sending' => __( 'Sending…', 'fieldwren' ),
'sent' => __( 'Done – see the log.', 'fieldwren' ),
'search' => __( 'Search integrations…', 'fieldwren' ),
'all' => __( 'All', 'fieldwren' ),
'badges' => self::badge_labels(),
);
}
/** @return array Connection status labels. */
private static function badge_labels() {
return array(
'ready' => __( 'No setup needed', 'fieldwren' ),
'verified' => __( 'Connected', 'fieldwren' ),
'saved' => __( 'Not verified', 'fieldwren' ),
'missing' => __( 'Not connected', 'fieldwren' ),
'unavailable' => __( 'Plugin not active', 'fieldwren' ),
);
}
/* ------------------------------------------------------------------ *
* Global tab
* ------------------------------------------------------------------ */
/** Add the Integrations tab to global settings. */
public static function global_tabs( $tabs ) {
$tabs = (array) $tabs;
$tabs['integrations'] = __( 'Integrations', 'fieldwren' );
return $tabs;
}
/** @return string Logo markup (inline SVG). */
public static function logo_html( Integration $int ) {
$logo = $int->logo();
if ( 0 !== strpos( ltrim( (string) $logo ), '' . \FWREN\Icons::svg( $logo, 22 ) . '';
}
return '' . self::kses_svg( $logo ) . ' ';
}
/** @return string SVG through a small allow-list. */
private static function kses_svg( $svg ) {
$attrs = array( 'viewbox' => true, 'xmlns' => true, 'width' => true, 'height' => true, 'fill' => true, 'd' => true, 'x' => true, 'y' => true, 'rx' => true, 'ry' => true, 'cx' => true, 'cy' => true, 'r' => true, 'stroke' => true, 'stroke-width' => true, 'stroke-linecap' => true, 'stroke-linejoin' => true, 'transform' => true, 'role' => true, 'aria-hidden' => true, 'text-anchor' => true, 'font-family' => true, 'font-size' => true, 'font-weight' => true, 'points' => true, 'opacity' => true, 'fill-rule' => true, 'clip-rule' => true );
return wp_kses(
$svg,
array(
'svg' => $attrs,
'g' => $attrs,
'path' => $attrs,
'rect' => $attrs,
'circle' => $attrs,
'ellipse' => $attrs,
'polygon' => $attrs,
'text' => $attrs,
)
);
}
/** Render the global Integrations tab. */
public static function render_global_tab() {
if ( ! current_user_can( self::cap() ) ) {
return;
}
$cats = self::categories();
echo '';
wp_nonce_field( self::NONCE, '_fwreni_nonce', false );
// Module settings.
$to = (string) self::setting( 'failed_email_to', get_option( 'admin_email' ) );
echo '
';
// Toolbar.
echo '
';
echo '
';
foreach ( self::all() as $slug => $int ) {
self::render_card( $int, $cats );
}
echo '
';
echo '';
echo '
';
}
/** One integration card. */
private static function render_card( Integration $int, array $cats ) {
$slug = $int->slug();
$fields = $int->credential_fields();
$creds = $int->creds();
$pub = $int->public_credentials();
$on = $int->is_enabled();
$ok = $int->is_configured();
$status = ! $fields ? 'ready' : ( ! empty( $creds['verified'] ) ? 'verified' : ( $ok ? 'saved' : 'missing' ) );
$need = $int->requirement();
$status = '' !== $need ? 'unavailable' : $status;
$labels = self::badge_labels();
$name ='fwreni[' . $slug . ']';
echo '';
echo '
' . self::logo_html( $int ); // phpcs:ignore WordPress.Security.EscapeOutput -- escaped in logo_html().
echo '
' . esc_html( $int->title() ) . ' ' . esc_html( $cats[ $int->category() ] ?? '' ) . '
';
echo '
' . esc_html__( 'Enable', 'fieldwren' ) . ' ' . esc_html( $int->title() ) . ' ';
echo '
';
echo '
' . esc_html( $int->description() ) . '
';
if ( '' !== $need ) {
echo '
' . esc_html( $need ) . '
';
}
echo '';
if ( $fields ) {
echo '
';
foreach ( $fields as $k => $f ) {
$type = $f['type'] ?? 'text';
$id = 'fwreni-' . $slug . '-' . $k;
$val = (string) ( $pub[ $k ] ?? '' );
echo '
' . esc_html( $f['label'] ) . ( ! empty( $f['required'] ) ? ' * ' : '' ) . ' ';
if ( 'select' === $type ) {
echo '
';
foreach ( (array) $f['options'] as $ov => $ol ) {
echo '' . esc_html( $ol ) . ' ';
}
echo ' ';
} elseif ( 'textarea' === $type && Integration::is_secret( $f ) ) {
echo '
';
} elseif ( 'textarea' === $type ) {
echo '
';
} elseif ( 'password' === $type ) {
echo '
';
} else {
echo '
';
}
if ( ! empty( $f['desc'] ) ) {
echo '
' . wp_kses_post( $f['desc'] ) . '
';
}
echo '
';
}
if ( $int->help() ) {
echo '
' . wp_kses_post( $int->help() ) . '
';
}
echo '
' . esc_html__( 'Save', 'fieldwren' ) . ' ';
if ( $int->can_verify() ) {
echo ' ' . esc_html( $int->verify_label() ) . ' ';
}
echo ' ' . esc_html__( 'Disconnect', 'fieldwren' ) . '
';
echo '
';
echo '
';
} elseif ( $int->help() ) {
echo '
' . esc_html__( 'How it works', 'fieldwren' ) . ' ' . wp_kses_post( $int->help() ) . '';
}
echo '
';
}
/** Whole-form POST of the global tab (the page's own Save button). */
public static function save_global_post() {
if ( empty( $_POST['_fwreni_nonce'] ) || ! current_user_can( self::cap() ) ) {
return;
}
if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_fwreni_nonce'] ) ), self::NONCE ) ) {
return;
}
$posted = isset( $_POST['fwreni'] ) && is_array( $_POST['fwreni'] ) ? wp_unslash( $_POST['fwreni'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- sanitized per field.
foreach ( self::all() as $slug => $int ) {
$input = isset( $posted[ $slug ] ) && is_array( $posted[ $slug ] ) ? $posted[ $slug ] : array();
self::store_credentials( $int, $input );
}
$g = isset( $_POST['fwreni_general'] ) && is_array( $_POST['fwreni_general'] ) ? wp_unslash( $_POST['fwreni_general'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
self::store_general( $g );
}
/**
* Sanitize and store credentials of one integration.
*
* @return array|\WP_Error Stored credentials.
*/
private static function store_credentials( Integration $int, array $input ) {
$old = $int->creds();
$creds = $int->sanitize_credentials( $input, $old );
$creds = $int->before_save_credentials( $creds, $old );
if ( is_wp_error( $creds ) ) {
return $creds;
}
if ( $old !== $creds ) {
Settings::save_credentials( 'integrations', $int->slug(), $creds );
}
return $creds;
}
/** Store module settings. */
private static function store_general( array $g ) {
$to = implode( ', ', \FWREN\Notifications::emails( (string) ( $g['failed_email_to'] ?? '' ) ) );
Settings::save_credentials(
'integrations',
'general',
array(
'failed_email' => ! empty( $g['failed_email'] ),
'failed_email_to' => $to ? $to : (string) get_option( 'admin_email' ),
'log_requests' => ! empty( $g['log_requests'] ),
)
);
}
/* ------------------------------------------------------------------ *
* AJAX
* ------------------------------------------------------------------ */
/** Nonce + capability. */
private static function guard() {
if ( ! check_ajax_referer( self::NONCE, 'nonce', false ) ) {
wp_send_json_error( array( 'message' => __( 'Your session expired. Reload the page.', 'fieldwren' ) ), 403 );
}
if ( ! current_user_can( self::cap() ) ) {
wp_send_json_error( array( 'message' => __( 'You are not allowed to do this.', 'fieldwren' ) ), 403 );
}
}
/** @return Integration Integration from the request (or exits). */
private static function req_integration() {
$slug = isset( $_POST['slug'] ) ? sanitize_key( wp_unslash( $_POST['slug'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification -- guard() ran.
$int = self::get( $slug );
if ( ! $int ) {
wp_send_json_error( array( 'message' => __( 'Unknown integration.', 'fieldwren' ) ), 400 );
}
return $int;
}
/** Save one card (and optionally verify). */
public static function ajax_save() {
self::guard();
$int = self::req_integration();
$input = isset( $_POST['creds'] ) && is_array( $_POST['creds'] ) ? wp_unslash( $_POST['creds'] ) : array(); // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput -- guard() ran; sanitized per field.
$creds = self::store_credentials( $int, $input );
if ( is_wp_error( $creds ) ) {
wp_send_json_error( array( 'message' => $creds->get_error_message() ) );
}
$out = array(
'message' => __( 'Saved.', 'fieldwren' ),
'enabled' => $int->is_enabled(),
'configured' => $int->is_configured(),
'creds' => $int->public_credentials(),
'status' => '' !== $int->requirement() ? 'unavailable' : ( ! $int->credential_fields() ? 'ready' : ( ! empty( $creds['verified'] ) ? 'verified' : ( $int->is_configured() ? 'saved' : 'missing' ) ) ),
);
if ( ! empty( $_POST['verify'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
if ( ! $int->is_configured() ) {
wp_send_json_error( array_merge( $out, array( 'message' => __( 'Fill in the required fields first.', 'fieldwren' ) ) ) );
}
$res = $int->verify( $int->creds() );
$c = $int->creds();
if ( is_wp_error( $res ) ) {
unset( $c['verified'], $c['verified_at'], $c['account'] );
Settings::save_credentials( 'integrations', $int->slug(), $c );
wp_send_json_error( array_merge( $out, array( 'status' => 'saved', 'message' => $res->get_error_message() ) ) );
}
$c['verified'] = true;
$c['verified_at'] = time();
$c['account'] = is_string( $res ) ? sanitize_text_field( $res ) : '';
Settings::save_credentials( 'integrations', $int->slug(), $c );
$out['status'] = 'verified';
$out['account'] = $c['account'];
/* translators: %s account */
$out['message'] = $c['account'] ? sprintf( __( 'Connected: %s', 'fieldwren' ), $c['account'] ) : __( 'Connected.', 'fieldwren' );
}
wp_send_json_success( $out );
}
/** Remove stored credentials (keeps the enabled flag). */
public static function ajax_disconnect() {
self::guard();
$int = self::req_integration();
Settings::save_credentials( 'integrations', $int->slug(), array( 'enabled' => $int->is_enabled() ) );
wp_send_json_success( array( 'message' => __( 'Credentials removed.', 'fieldwren' ), 'status' => $int->credential_fields() ? 'missing' : 'ready' ) );
}
/** Save module settings. */
public static function ajax_general() {
self::guard();
$g = isset( $_POST['general'] ) && is_array( $_POST['general'] ) ? wp_unslash( $_POST['general'] ) : array(); // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput
self::store_general( $g );
wp_send_json_success( array( 'message' => __( 'Saved.', 'fieldwren' ) ) );
}
/** Remote options for the feed editor. */
public static function ajax_options() {
self::guard();
$int = self::req_integration();
$source = isset( $_POST['source'] ) ? sanitize_key( wp_unslash( $_POST['source'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
$settings = isset( $_POST['settings'] ) ? json_decode( wp_unslash( (string) $_POST['settings'] ), true ) : array(); // phpcs:ignore WordPress.Security.NonceVerification,WordPress.Security.ValidatedSanitizedInput -- decoded JSON, only read as scalar lookups.
$settings = is_array( $settings ) ? array_map( static function ( $v ) {
return is_scalar( $v ) ? sanitize_text_field( (string) $v ) : $v;
}, $settings ) : array();
if ( '' !== $int->requirement() ) {
wp_send_json_error( array( 'message' => $int->requirement() ) );
}
if ( ! $int->is_configured() ) {
wp_send_json_error( array( 'message' => __( 'Connect this integration in Settings → Integrations first.', 'fieldwren' ) ) );
}
$res = $int->cached_options( $source, $settings, ! empty( $_POST['refresh'] ) ); // phpcs:ignore WordPress.Security.NonceVerification
if ( is_wp_error( $res ) ) {
wp_send_json_error( array( 'message' => $res->get_error_message() ) );
}
// Keep order in JSON: send a list.
$list = array();
foreach ( $res as $k => $v ) {
$list[] = is_array( $v ) ? $v : array( 'value' => (string) $k, 'label' => (string) $v );
}
wp_send_json_success( array( 'options' => $list ) );
}
/** Resend an entry (entry screen). */
public static function ajax_resend() {
self::guard();
$entry_id = isset( $_POST['entry'] ) ? absint( $_POST['entry'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification
$feed_id = isset( $_POST['feed'] ) ? sanitize_key( wp_unslash( $_POST['feed'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
$res = self::resend( $entry_id, $feed_id );
if ( is_wp_error( $res ) ) {
wp_send_json_error( array( 'message' => $res->get_error_message() ) );
}
$msgs = array();
$fail = false;
foreach ( $res as $id => $r ) {
if ( is_wp_error( $r ) ) {
$fail = true;
$msgs[] = $r->get_error_message();
} elseif ( 'skipped' === $r ) {
$msgs[] = __( 'Skipped (conditions or integration off).', 'fieldwren' );
} else {
$msgs[] = is_string( $r ) ? $r : __( 'Sent.', 'fieldwren' );
}
}
if ( ! $msgs ) {
$msgs[] = __( 'No feeds to run.', 'fieldwren' );
}
$payload = array( 'message' => implode( ' · ', $msgs ) );
$fail ? wp_send_json_error( $payload ) : wp_send_json_success( $payload );
}
/* ------------------------------------------------------------------ *
* Form tab
* ------------------------------------------------------------------ */
/** Add the Integrations tab to the form settings. */
public static function form_tabs( $tabs, $form_id = 0 ) {
$tabs = (array) $tabs;
$tabs['integrations'] = __( 'Integrations', 'fieldwren' );
return $tabs;
}
/** Render the feed editor of a form. */
public static function render_form_tab( $form_id, $settings = array() ) {
$form_id = (int) $form_id;
if ( ! current_user_can( self::cap() ) || ! $form_id ) {
return;
}
$feeds = array_map( array( __CLASS__, 'mask_feed' ), self::form_feeds( $form_id ) );
echo '';
}
/** @return array Editor config of a form. */
private static function form_config( $form_id ) {
$ints = array();
$cats = self::categories();
foreach ( self::all() as $slug => $int ) {
$ints[ $slug ] = array(
'title' => $int->title(),
'category' => $int->category(),
'catLabel' => $cats[ $int->category() ] ?? '',
'description' => $int->description(),
'logo' => self::logo_html( $int ),
'available' => '' === $int->requirement() && $int->is_enabled() && $int->is_configured(),
'requirement' => $int->requirement(),
'fields' => array_values( $int->feed_fields( $form_id ) ),
'defaults' => (object) $int->feed_defaults( $form_id ),
);
}
$sources = array();
$schema = Schema::get( $form_id );
foreach ( $schema['order'] as $key ) {
$f = $schema['fields'][ $key ];
if ( ! empty( $f['sensitive'] ) ) {
continue;
}
$label = Schema::label( $f );
$sources[] = array( 'value' => '{inputs.' . $key . '}', 'label' => $label . ' (' . $key . ')' );
if ( ! empty( $f['parts'] ) && count( (array) $f['parts'] ) > 1 ) {
foreach ( (array) $f['parts'] as $p ) {
$sources[] = array( 'value' => '{inputs.' . $key . '.' . $p . '}', 'label' => '— ' . $label . ' › ' . ucfirst( str_replace( '_', ' ', $p ) ) );
}
}
}
return array(
'formId' => $form_id,
'integrations' => $ints,
'sources' => $sources,
'fields' => (object) Schema::field_choices( $form_id ),
'smartcodes' => Smartcodes::catalog( $form_id ),
'operators' => Conditions::operators(),
'categories' => $cats,
'settingsUrl' => admin_url( 'admin.php?page=fwren-settings&tab=integrations' ),
'mask' => Integration::MASK,
'auto' => Integration::auto_values( $form_id ),
);
}
/** @return array Feed with per-feed secrets replaced by the mask. */
public static function mask_feed( array $feed ) {
$int = self::get( $feed['integration'] ?? '' );
if ( ! $int ) {
return $feed;
}
$s = (array) ( $feed['settings'] ?? array() );
foreach ( $int->feed_fields( 0 ) as $f ) {
$k = $f['key'] ?? '';
if ( ! $k || ! isset( $s[ $k ] ) ) {
continue;
}
if ( 'secret' === $f['type'] && '' !== (string) $s[ $k ] ) {
$s[ $k ] = Integration::MASK;
} elseif ( 'kv' === $f['type'] && ! empty( $f['secret'] ) && is_array( $s[ $k ] ) ) {
foreach ( $s[ $k ] as $i => $row ) {
if ( is_array( $row ) && '' !== (string) ( $row['value'] ?? '' ) ) {
$s[ $k ][ $i ]['value'] = Integration::MASK;
}
}
}
}
$feed['settings'] = (object) $s;
return $feed;
}
/**
* Save the form tab: our feeds from the hidden JSON input; other modules' feeds are kept.
*
* @param int $form_id Form id.
* @param array $post $_POST.
*/
public static function save_form_tab( $form_id, $post = array() ) {
$form_id = (int) $form_id;
if ( ! $form_id || ! current_user_can( self::cap() ) || ! isset( $post['fwren_int_feeds_json'] ) ) {
return;
}
$raw = json_decode( wp_unslash( (string) $post['fwren_int_feeds_json'] ), true );
if ( ! is_array( $raw ) ) {
return;
}
$old_all = Form::feeds( $form_id );
$old = array();
$keep = array();
foreach ( $old_all as $f ) {
if ( is_array( $f ) && self::get( $f['integration'] ?? '' ) ) {
$old[ (string) ( $f['id'] ?? '' ) ] = $f;
} else {
$keep[] = $f;
}
}
$new = array();
$ids = array();
foreach ( $raw as $feed ) {
$clean = is_array( $feed ) ? self::sanitize_feed( $feed, $old, $form_id ) : null;
if ( $clean && ! isset( $ids[ $clean['id'] ] ) ) {
$ids[ $clean['id'] ] = true;
$new[] = $clean;
}
}
Form::save_feeds( $form_id, array_merge( $keep, $new ) );
}
/**
* Sanitize one feed against its integration's field definitions.
*
* @param array $feed Posted feed.
* @param array $old Stored feeds of this module by id (secret restore).
* @param int $form_id Form id.
* @return array|null
*/
private static function sanitize_feed( array $feed, array $old, $form_id ) {
$int = self::get( sanitize_key( $feed['integration'] ?? '' ) );
if ( ! $int ) {
return null;
}
$id = sanitize_key( (string) ( $feed['id'] ?? '' ) );
if ( '' === $id ) {
$id = 'f' . strtolower( wp_generate_password( 10, false ) );
}
$src = sanitize_key( (string) ( $feed['_src'] ?? '' ) );
$prev = $old[ $id ] ?? ( $src && isset( $old[ $src ] ) ? $old[ $src ] : array() );
$prev_s = (array) ( $prev['settings'] ?? array() );
$in = is_array( $feed['settings'] ?? null ) ? $feed['settings'] : array();
$settings = array();
foreach ( $int->feed_fields( $form_id ) as $f ) {
$k = $f['key'] ?? '';
if ( ! $k || 'notice' === $f['type'] ) {
continue;
}
$settings[ $k ] = self::sanitize_value( $f, $in[ $k ] ?? null, $prev_s[ $k ] ?? null );
}
$ops = Conditions::operators();
$rules = array();
foreach ( (array) ( $feed['conditions']['rules'] ?? array() ) as $r ) {
if ( ! is_array( $r ) || empty( $r['field'] ) ) {
continue;
}
$op = (string) ( $r['operator'] ?? '=' );
$rules[] = array(
'field' => preg_replace( '/[^a-z0-9_.\-]/', '', strtolower( (string) $r['field'] ) ),
'operator' => isset( $ops[ $op ] ) ? $op : '=',
'value' => sanitize_text_field( is_scalar( $r['value'] ?? '' ) ? (string) $r['value'] : '' ),
);
}
return array(
'id' => $id,
'integration' => $int->slug(),
'name' => sanitize_text_field( (string) ( $feed['name'] ?? '' ) ) ?: $int->title(),
'enabled' => ! empty( $feed['enabled'] ),
'conditions' => array(
'enabled' => ! empty( $feed['conditions']['enabled'] ) && $rules,
'match' => 'any' === ( $feed['conditions']['match'] ?? 'all' ) ? 'any' : 'all',
'rules' => $rules,
),
'settings' => $settings,
);
}
/** @return string A URL that may hold smartcodes and %-escapes (no tags, no whitespace). */
private static function url_text( $v ) {
return is_scalar( $v ) ? preg_replace( '/[\s<>"\'\\\\]+/', '',wp_strip_all_tags( (string) $v ) ) : '';
}
/**
* Sanitize one feed setting.
*
* @param array $f Field definition.
* @param mixed $v Posted value.
* @param mixed $prev Stored value (secret restore).
* @return mixed
*/
private static function sanitize_value( array $f, $v, $prev ) {
$text = static function ( $s ) {
return is_scalar( $s ) ? sanitize_text_field( (string) $s ) : '';
};
switch ( $f['type'] ) {
case 'toggle':
return ! empty( $v ) && 'false' !== $v;
case 'number':
return is_numeric( $v ) ? $v + 0 : '';
case 'textarea':
if ( ! is_scalar( $v ) ) {
return '';
}
return ! empty( $f['html'] ) ? wp_kses_post( (string) $v ) : sanitize_textarea_field( (string) $v );
case 'secret':
if ( Integration::MASK === $v ) {
return is_scalar( $prev ) ? (string) $prev : '';
}
return ! empty( $f['url'] ) ? self::url_text( $v ) : $text( $v );
case 'select':
if ( ! empty( $f['multiple'] ) ) {
return array_values( array_filter( array_map( $text, (array) $v ), 'strlen' ) );
}
$v = $text( $v );
if ( ! empty( $f['options'] ) && empty( $f['source'] ) && '' !== $v && ! isset( $f['options'][ $v ] ) ) {
return (string) ( $f['default'] ?? '' );
}
return $v;
case 'field':
return preg_replace( '/[^a-z0-9_.\-]/', '', strtolower( $text( $v ) ) );
case 'fields':
return array_values( array_filter( array_map( 'sanitize_key', (array) $v ), 'strlen' ) );
case 'map':
$out = array();
foreach ( is_array( $v ) ? $v : array() as $rk => $tpl ) {
$rk = $text( $rk );
if ( '' !== $rk && is_scalar( $tpl ) && '' !== trim( (string) $tpl ) ) {
$out[ $rk ] = sanitize_textarea_field( (string) $tpl );
}
}
return $out;
case 'kv':
$out = array();
$prev = is_array( $prev ) ? $prev : array();
foreach ( is_array( $v ) ? $v : array() as $row ) {
if ( ! is_array( $row ) ) {
continue;
}
$k = $text( $row['key'] ?? '' );
$val = is_scalar( $row['value'] ?? '' ) ? (string) ( $row['value'] ?? '' ) : '';
if ( '' === $k ) {
continue;
}
if ( ! empty( $f['secret'] ) && Integration::MASK === $val ) {
$val = '';
foreach ( $prev as $p ) {
if ( is_array( $p ) && ( $p['key'] ?? '' ) === $k ) {
$val = (string) ( $p['value'] ?? '' );
break;
}
}
}
$out[] = array( 'key' => $k, 'value' => sanitize_textarea_field( $val ) );
}
return $out;
case 'value':
case 'text':
default:
if ( ! empty( $f['url'] ) ) {
return self::url_text( $v );
}
return is_scalar( $v ) ? sanitize_textarea_field( (string) $v ) : '';
}
}
}