Plugin Directory

Changeset 3845360


Ignore:
Timestamp:
12/05/2026 12:17:30 AM (less than one hour ago)
Author:
vitalconsulting
Message:

MyVitalAssistant 1.6.10

Location:
myvitalassistant/trunk
Files:
2 added
3 edited

Legend:

Unmodified
Added
Removed
  • myvitalassistant/trunk/myvitalassistant.php

    r3666161 r3845360  
    33 * Plugin Name:       MyVitalAssistant
    44 * Description:       Serves MyVitalAssistant's ad-attribution tracking from your own domain, so Safari stops deleting your visitors' attribution after seven days. Captures form submissions from Contact Form 7, WPForms, Gravity Forms, Fluent Forms, Ninja Forms, Formidable, Elementor, and Keap's own Opt-in Forms plugin so attribution reaches your CRM without any field wiring.
    5  * Version:           1.6.1
     5 * Version:           1.6.10
    66 * Plugin URI:        https://help.myvitalassistant.com/cookie-lifetime
    77 * Requires at least: 6.3
    … …  
    4747}
    4848
    49 const MYVITA_VERSION        = '1.6.1';
     49const MYVITA_VERSION        = '1.6.10';
    5050const MYVITA_PREFIX         = '/vt';
    5151const MYVITA_DEFAULT_ORIGIN = 'https://t.myvitalassistant.com';
    … …  
    5959 */
    6060const MYVITA_COOKIE         = '_vt';
    61 
    62 /** Endpoints we are willing to forward. Anything else 404s here. */
    63 const MYVITA_ROUTES = ['/e', '/c', '/s.js', '/call'];
     61/**
     62 * The settings page's slug, the one name every link to it is built from.
     63 *
     64 * Until 1.6.2 the page registered as myvita-tracking while the forms list's
     65 * "Refresh this list" link and the editor block's "Set up forms" button were
     66 * built by hand as page=myvitalassistant, a page that does not exist, so both
     67 * answered "Sorry, you are not allowed to access this page." Found on a
     68 * WordPress 7.1.1 install on 2026-10-07. The slug itself is kept, because it
     69 * is the address anybody who bookmarked the page already has.
     70 */
     71const MYVITA_SETTINGS_PAGE  = 'myvita-tracking';
     72
     73/**
     74 * Endpoints we are willing to forward. Anything else 404s here.
     75 *
     76 * /fm.js and /fm since 1.6.3: on an account with Tracking Forms switched on,
     77 * the tracking script loads a small reader once per page per visitor per day
     78 * that reports the shape of the forms on the page (questions, never answers),
     79 * so the account can recreate one. Relayed like the beacon so the browser
     80 * never sees a second host.
     81 */
     82const MYVITA_ROUTES = ['/e', '/c', '/s.js', '/call', '/fm', '/fm.js'];
    6483
    6584/**
    … …  
    495514    echo '</tbody></table>';
    496515    $url = wp_nonce_url(
    497         admin_url('options-general.php?page=myvitalassistant&myvita_refresh_forms=1'),
     516        admin_url('admin.php?page=' . MYVITA_SETTINGS_PAGE . '&myvita_refresh_forms=1'),
    498517        'myvita_refresh_forms'
    499518    );
    … …  
    537556        wp_localize_script('myvita-form-block', 'myvitaForms', [
    538557            'forms' => myvita_forms(),
    539             'build' => admin_url('options-general.php?page=myvitalassistant'),
     558            'build' => admin_url('admin.php?page=' . MYVITA_SETTINGS_PAGE),
    540559        ]);
    541560    }
    … …  
    588607
    589608/* -------------------------------------------------------------------------
     609 * InfusedWoo settings export
     610 *
     611 * A site moving off InfusedWoo needs its mapping read out of the database:
     612 * which Keap product, tags, trial and fee each WooCommerce product carries,
     613 * and the plugin's own options. This builds that as ONE file the site admin
     614 * downloads. Nothing is sent anywhere: it is created here and handed to the
     615 * browser, so there is nothing to disclose as an external call.
     616 *
     617 * Read only: it changes nothing on the site. Customers and orders are never
     618 * included (an order is only COUNTED), and any value whose name says it is a
     619 * password, key, token, licence or signature is blanked, as is any long
     620 * token-shaped string, before it goes into the file.
     621 * ---------------------------------------------------------------------- */
     622
     623/** True when a setting's NAME says its value is a credential. */
     624function myvita_iw_secret_key(string $key): bool
     625{
     626    return (bool) preg_match(
     627        '/(password|passwd|secret|token|api[_\- ]?key|app[_\- ]?key|licen[sc]e|private|signature|auth(?!or)|share[_\- ]?(url|link)|webhook[_\- ]?url|(^|[_\-\s])key($|[_\-\s])|[a-z]key$)/i',
     628        $key
     629    );
     630}
     631
     632/**
     633 * A copy of a value that is safe to hand over: credentials blanked by NAME,
     634 * token-shaped strings blanked by SHAPE, query-string secrets blanked inside
     635 * addresses, and anything very long cut. Objects become arrays; nothing is
     636 * ever unserialised into a class.
     637 */
     638function myvita_iw_redact($value, string $key = '', int $depth = 0)
     639{
     640    if ($key !== '' && myvita_iw_secret_key($key)) {
     641        return (is_string($value) && $value === '') ? '' : '[redacted]';
     642    }
     643    if (is_object($value)) {
     644        $value = (array) $value;
     645    }
     646    if (is_array($value)) {
     647        if ($depth >= 8) {
     648            return '[too deep]';
     649        }
     650        $out = [];
     651        foreach ($value as $k => $v) {
     652            $out[$k] = myvita_iw_redact($v, (string) $k, $depth + 1);
     653        }
     654        return $out;
     655    }
     656    if (is_string($value)) {
     657        if (preg_match('/^[A-Za-z0-9_\-]{32,}$/', $value)) {
     658            return '[redacted: long token-like value]';
     659        }
     660        $value = preg_replace('/([?&](?:key|token|api_?key|secret|password|sig|signature)=)[^&\s"\']+/i', '$1[redacted]', $value);
     661        if (strlen($value) > 4000) {
     662            $value = substr($value, 0, 4000) . '... [cut at 4000 characters]';
     663        }
     664        return $value;
     665    }
     666    return $value;
     667}
     668
     669/** A stored value as data: serialised text is read without creating any object. */
     670function myvita_iw_stored($raw)
     671{
     672    if (is_string($raw) && is_serialized($raw)) {
     673        $data = @unserialize($raw, ['allowed_classes' => false]);
     674        return $data === false && $raw !== 'b:0;' ? $raw : $data;
     675    }
     676    return $raw;
     677}
     678
     679/** Whether InfusedWoo is installed and active on this site. */
     680function myvita_iw_present(): bool
     681{
     682    $active = (array) get_option('active_plugins', []);
     683    if (is_multisite()) {
     684        $active = array_merge($active, array_keys((array) get_site_option('active_sitewide_plugins', [])));
     685    }
     686    foreach ($active as $file) {
     687        if (stripos((string) $file, 'infusedwoo') !== false) {
     688            return true;
     689        }
     690    }
     691    return false;
     692}
     693
     694/** The whole export as an array. Reads only. */
     695function myvita_iw_collect(): array
     696{
     697    global $wpdb;
     698
     699    if (!function_exists('get_plugins')) {
     700        require_once ABSPATH . 'wp-admin/includes/plugin.php';
     701    }
     702    $found = [];
     703    $names = [];
     704    foreach (get_plugins() as $file => $data) {
     705        $active = is_plugin_active($file);
     706        if ($active) {
     707            $names[] = $data['Name'] . ' ' . $data['Version'];
     708        }
     709        if (stripos($file . $data['Name'], 'infusedwoo') !== false) {
     710            $found[] = ['name' => $data['Name'], 'version' => $data['Version'], 'file' => $file, 'active' => $active];
     711        }
     712    }
     713
     714    $out = [
     715        'about' => [
     716            'made_by'     => 'MyVitalAssistant plugin ' . MYVITA_VERSION . ' on ' . home_url(),
     717            'made_at'     => gmdate('c'),
     718            'note'        => 'Read only. Credentials are blanked by name and by shape; customers and orders are not included. Look it over before you send it.',
     719            'wordpress'   => get_bloginfo('version'),
     720            'woocommerce' => defined('WC_VERSION') ? WC_VERSION : null,
     721            'infusedwoo'  => $found,
     722            'active_plugins' => $names,
     723        ],
     724        'options' => [],
     725        'products' => [],
     726        'orders' => [],
     727        'posts' => [],
     728        'tables' => [],
     729    ];
     730
     731    // 1. The plugin's own options, by the prefixes it is known to use.
     732    $likes = [];
     733    foreach (['infusedwoo', 'iw_', 'infusionsoft', 'woocommerce_infusionsoft', 'wc_infusionsoft'] as $prefix) {
     734        $likes[] = $wpdb->esc_like($prefix) . '%';
     735    }
     736    $where = implode(' OR ', array_fill(0, count($likes), 'option_name LIKE %s'));
     737    $rows = $wpdb->get_results($wpdb->prepare("SELECT option_name, option_value FROM {$wpdb->options} WHERE {$where} ORDER BY option_name LIMIT 600", $likes));
     738    foreach ((array) $rows as $row) {
     739        $out['options'][$row->option_name] = myvita_iw_redact(myvita_iw_stored($row->option_value), $row->option_name);
     740    }
     741
     742    // 2. What each product and variation carries: the Keap product, plan, tags,
     743    //    trial, fee and the rest of the product tab, all plain post meta.
     744    $meta = $wpdb->get_results($wpdb->prepare(
     745        "SELECT pm.post_id, pm.meta_key, pm.meta_value FROM {$wpdb->postmeta} pm
     746         INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
     747         WHERE p.post_type IN ('product','product_variation')
     748           AND (pm.meta_key LIKE %s OR pm.meta_key LIKE %s)
     749         ORDER BY pm.post_id, pm.meta_key LIMIT 8000",
     750        $wpdb->esc_like('infusionsoft_') . '%',
     751        $wpdb->esc_like('iw_') . '%'
     752    ));
     753    $byPost = [];
     754    foreach ((array) $meta as $row) {
     755        $byPost[(int) $row->post_id][$row->meta_key] = myvita_iw_redact(myvita_iw_stored($row->meta_value), $row->meta_key);
     756    }
     757    foreach ($byPost as $id => $keys) {
     758        $post = get_post($id);
     759        $out['products'][] = [
     760            'id'     => $id,
     761            'type'   => $post ? $post->post_type : null,
     762            'parent' => $post ? (int) $post->post_parent : null,
     763            'name'   => $post ? $post->post_title : null,
     764            'status' => $post ? $post->post_status : null,
     765            'sku'    => (string) get_post_meta($id, '_sku', true),
     766            'keap'   => $keys,
     767        ];
     768    }
     769
     770    // 3. Orders are only COUNTED, never read: how many carry Keap ids already.
     771    $out['orders'] = [
     772        'with_keap_meta' => (int) $wpdb->get_var($wpdb->prepare(
     773            "SELECT COUNT(DISTINCT pm.post_id) FROM {$wpdb->postmeta} pm
     774             INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
     775             WHERE p.post_type LIKE %s AND pm.meta_key LIKE %s",
     776            $wpdb->esc_like('shop_order') . '%',
     777            $wpdb->esc_like('infusionsoft_') . '%'
     778        )),
     779    ];
     780
     781    // 4. Records of the plugin's own post types (recipes and the like). Found
     782    //    in the posts table itself, because a type InfusedWoo registers only
     783    //    on its own admin screens is not in get_post_types() when this runs,
     784    //    which is how a store's active recipes were missed from the first export.
     785    $types = array_merge(
     786        array_values(get_post_types([], 'names')),
     787        (array) $wpdb->get_col($wpdb->prepare(
     788            "SELECT DISTINCT post_type FROM {$wpdb->posts} WHERE post_type LIKE %s OR post_type LIKE %s OR post_type LIKE %s",
     789            '%' . $wpdb->esc_like('recipe') . '%',
     790            $wpdb->esc_like('iw') . '%',
     791            $wpdb->esc_like('infusedwoo') . '%'
     792        ))
     793    );
     794    foreach (array_values(array_unique($types)) as $type) {
     795        if (!preg_match('/^(iw|infusedwoo|infusionsoft)/i', $type) && stripos($type, 'recipe') === false) {
     796            continue;
     797        }
     798        $items = get_posts(['post_type' => $type, 'post_status' => 'any', 'numberposts' => 300, 'suppress_filters' => true]);
     799        foreach ($items as $item) {
     800            $fields = [];
     801            foreach ((array) get_post_meta($item->ID) as $k => $vals) {
     802                $fields[$k] = myvita_iw_redact(array_map('myvita_iw_stored', (array) $vals), (string) $k);
     803            }
     804            $out['posts'][] = [
     805                'type'     => $type,
     806                'id'       => $item->ID,
     807                'title'    => $item->post_title,
     808                'status'   => $item->post_status,
     809                'modified' => $item->post_modified_gmt,
     810                'content'  => myvita_iw_redact(myvita_iw_stored($item->post_content)),
     811                'meta'     => $fields,
     812            ];
     813        }
     814    }
     815
     816    // 5. The plugin's own tables: names, columns and row counts. Rows are not
     817    //    read, since a log or queue table holds customers.
     818    foreach (['iw', 'infusedwoo'] as $prefix) {
     819        $tables = $wpdb->get_col($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($wpdb->prefix . $prefix) . '%'));
     820        foreach ((array) $tables as $table) {
     821            $quoted = '`' . str_replace('`', '``', $table) . '`';
     822            $columns = $wpdb->get_col("SHOW COLUMNS FROM {$quoted}", 0);
     823            $out['tables'][$table] = [
     824                'rows'    => (int) $wpdb->get_var("SELECT COUNT(*) FROM {$quoted}"),
     825                'columns' => (array) $columns,
     826            ];
     827        }
     828    }
     829
     830    return $out;
     831}
     832
     833add_action('admin_post_myvita_iw_export', function (): void {
     834    if (!current_user_can('manage_options')) {
     835        wp_die('You need to be an administrator to do this.', '', ['response' => 403]);
     836    }
     837    check_admin_referer('myvita_iw_export');
     838    $json = wp_json_encode(myvita_iw_collect(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR);
     839    $host = sanitize_file_name((string) wp_parse_url(home_url(), PHP_URL_HOST));
     840    nocache_headers();
     841    header('Content-Type: application/json; charset=utf-8');
     842    header('Content-Disposition: attachment; filename="myvitalassistant-infusedwoo-' . $host . '-' . gmdate('Y-m-d') . '.json"');
     843    echo $json; // phpcs:ignore WordPress.Security.EscapeOutput -- a JSON download, not a page
     844    exit;
     845});
     846
     847/**
     848 * Migration read-outs are for a site MyVitalAssistant support is setting up, never for a
     849 * store owner browsing settings. Support turns them on with
     850 * define('MYVITA_SUPPORT_TOOLS', true); in wp-config.php.
     851 */
     852function myvita_support_tools(): bool
     853{
     854    return defined('MYVITA_SUPPORT_TOOLS') && MYVITA_SUPPORT_TOOLS;
     855}
     856
     857/** The card on the settings page, shown only where InfusedWoo is active. */
     858function myvita_iw_card(): void
     859{
     860    if (!current_user_can('manage_options') || !myvita_iw_present()) {
     861        return;
     862    }
     863    ?>
     864    <h2>InfusedWoo settings</h2>
     865    <p class="description" style="max-width:640px">
     866        Moving off InfusedWoo? This downloads one file with the Keap setup InfusedWoo keeps on your products and in its own settings, so it can be rebuilt without retyping. It is made on this site and handed to your browser: nothing is sent anywhere, nothing is changed, and customers and orders are not in it. Passwords, keys, tokens and licence keys are blanked. Look it over before you send it to anyone.
     867    </p>
     868    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
     869        <input type="hidden" name="action" value="myvita_iw_export" />
     870        <?php wp_nonce_field('myvita_iw_export'); ?>
     871        <?php submit_button('Download InfusedWoo settings', 'secondary', 'submit', false); ?>
     872    </form>
     873    <?php
     874}
     875
     876/* -------------------------------------------------------------------------
     877 * SUMO Payment Plans read-out
     878 *
     879 * A store moving its deposits and instalments into MyVitalAssistant needs to
     880 * know how SUMO really stores a booking: its settings, its own records and how
     881 * a deposit order relates to the balance orders. This builds that as ONE file
     882 * the site admin downloads, the same way as the InfusedWoo export above:
     883 * created here, handed to the browser, nothing sent anywhere and nothing
     884 * changed.
     885 *
     886 * It reads a handful of example bookings and never a customer: no name,
     887 * address, phone, email or user id is included, anything that looks like an
     888 * email address is blanked, and credentials are blanked by name and shape.
     889 * ---------------------------------------------------------------------- */
     890
     891/** Whether SUMO Payment Plans is installed and active on this site. */
     892function myvita_sumo_present(): bool
     893{
     894    $active = (array) get_option('active_plugins', []);
     895    if (is_multisite()) {
     896        $active = array_merge($active, array_keys((array) get_site_option('active_sitewide_plugins', [])));
     897    }
     898    foreach ($active as $file) {
     899        if (stripos((string) $file, 'sumo') !== false && stripos((string) $file, 'payment') !== false) {
     900            return true;
     901        }
     902    }
     903    return false;
     904}
     905
     906/** The same redaction as the InfusedWoo export, plus any email address and any user or customer id. */
     907function myvita_sumo_clean($value, string $key = '')
     908{
     909    if ($key !== '' && preg_match('/(email|e_mail|phone|address|first_?name|last_?name|billing|shipping|user_?id|customer_?id|buyer|ip_?address)/i', $key)) {
     910        return '[left out]';
     911    }
     912    $value = myvita_iw_redact($value, $key);
     913    if (is_array($value)) {
     914        $out = [];
     915        foreach ($value as $k => $v) {
     916            $out[$k] = myvita_sumo_clean($v, (string) $k);
     917        }
     918        return $out;
     919    }
     920    if (is_string($value)) {
     921        $value = preg_replace('/[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/', '[email]', $value);
     922    }
     923    return $value;
     924}
     925
     926/** Everything SUMO keeps under a post's meta, cleaned. */
     927function myvita_sumo_meta(int $post_id): array
     928{
     929    $fields = [];
     930    foreach ((array) get_post_meta($post_id) as $k => $vals) {
     931        $fields[$k] = myvita_sumo_clean(array_map('myvita_iw_stored', (array) $vals), (string) $k);
     932    }
     933    return $fields;
     934}
     935
     936/** One order as a booking sample: amounts, lines and SUMO's own fields, never the buyer. */
     937function myvita_sumo_order($order): array
     938{
     939    $lines = [];
     940    foreach ($order->get_items() as $item) {
     941        $lines[] = [
     942            'name'     => $item->get_name(),
     943            'sku'      => method_exists($item, 'get_product') && $item->get_product() ? $item->get_product()->get_sku() : '',
     944            'quantity' => $item->get_quantity(),
     945            'subtotal' => $item->get_subtotal(),
     946            'total'    => $item->get_total(),
     947        ];
     948    }
     949    $fees = [];
     950    foreach ($order->get_fees() as $fee) {
     951        $fees[] = ['name' => $fee->get_name(), 'total' => $fee->get_total()];
     952    }
     953    $meta = [];
     954    foreach ($order->get_meta_data() as $entry) {
     955        $data = $entry->get_data();
     956        $name = (string) $data['key'];
     957        if (stripos($name, 'sumo') !== false || stripos($name, 'payment_plan') !== false) {
     958            $meta[$name] = myvita_sumo_clean(myvita_iw_stored($data['value']), $name);
     959        }
     960    }
     961    $created = $order->get_date_created();
     962    $paid    = $order->get_date_paid();
     963    return [
     964        'id'             => $order->get_id(),
     965        'parent_id'      => $order->get_parent_id(),
     966        'status'         => $order->get_status(),
     967        'total'          => $order->get_total(),
     968        'currency'       => $order->get_currency(),
     969        'created'        => $created ? $created->date('c') : null,
     970        'paid'           => $paid ? $paid->date('c') : null,
     971        'gateway'        => $order->get_payment_method(),
     972        'lines'          => $lines,
     973        'fees'           => $fees,
     974        'sumo_order_meta' => $meta,
     975    ];
     976}
     977
     978/** The whole read-out as an array. Reads only. */
     979/**
     980 * SUMO's per-product plan settings: for each product and variation that holds
     981 * any `_sumo_pp_` post meta, those keys only (deposit rule, balance due date,
     982 * plan choice, whatever SUMO stored), cleaned like every other value here. A
     983 * product's title is a trip name, not a person. Capped: the count is always
     984 * the whole, the rows the first 150 by id. Read only.
     985 */
     986function myvita_sumo_products(): array
     987{
     988    global $wpdb;
     989
     990    $rows = $wpdb->get_results($wpdb->prepare(
     991        "SELECT p.ID, p.post_parent, p.post_type, p.post_title, m.meta_key, m.meta_value
     992           FROM {$wpdb->posts} p
     993           JOIN {$wpdb->postmeta} m ON m.post_id = p.ID
     994          WHERE p.post_type IN ('product', 'product_variation')
     995            AND p.post_status <> 'trash'
     996            AND m.meta_key LIKE %s
     997          ORDER BY p.ID ASC
     998          LIMIT 6000",
     999        $wpdb->esc_like('_sumo_pp_') . '%'
     1000    ));
     1001
     1002    $byId = [];
     1003    foreach ((array) $rows as $r) {
     1004        $id = (int) $r->ID;
     1005        if (!isset($byId[$id])) {
     1006            $byId[$id] = [
     1007                'id'     => $id,
     1008                'parent' => (int) $r->post_parent,
     1009                'type'   => $r->post_type,
     1010                'title'  => myvita_sumo_clean($r->post_title),
     1011                'meta'   => [],
     1012            ];
     1013        }
     1014        $byId[$id]['meta'][$r->meta_key] = myvita_sumo_clean(myvita_iw_stored(maybe_unserialize($r->meta_value)), (string) $r->meta_key);
     1015    }
     1016
     1017    return ['count' => count($byId), 'rows' => array_slice(array_values($byId), 0, 150)];
     1018}
     1019
     1020function myvita_sumo_collect(): array
     1021{
     1022    global $wpdb;
     1023
     1024    if (!function_exists('get_plugins')) {
     1025        require_once ABSPATH . 'wp-admin/includes/plugin.php';
     1026    }
     1027    $found = [];
     1028    foreach (get_plugins() as $file => $data) {
     1029        if (stripos($file . $data['Name'], 'sumo') !== false) {
     1030            $found[] = ['name' => $data['Name'], 'version' => $data['Version'], 'active' => is_plugin_active($file)];
     1031        }
     1032    }
     1033    $out = [
     1034        'about' => [
     1035            'made_by'     => 'MyVitalAssistant plugin ' . MYVITA_VERSION . ' on ' . home_url(),
     1036            'made_at'     => gmdate('c'),
     1037            'note'        => 'Read only. A few example bookings, SUMO\'s own settings and records, and each product\'s own plan settings. No customer name, contact detail or user id is included; look it over before you send it.',
     1038            'woocommerce' => defined('WC_VERSION') ? WC_VERSION : null,
     1039        ],
     1040        'plugins'     => $found,
     1041        'options'     => [],
     1042        'post_types'  => [],
     1043        'tables'      => [],
     1044        'products'    => [],
     1045        'bookings'    => [],
     1046    ];
     1047
     1048    // 1. SUMO's options, by name. Values are cleaned; long lists are cut.
     1049    $names = $wpdb->get_col($wpdb->prepare(
     1050        "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s ORDER BY option_name LIMIT 400",
     1051        $wpdb->esc_like('sumo') . '%',
     1052        $wpdb->esc_like('_sumo') . '%'
     1053    ));
     1054    foreach ((array) $names as $name) {
     1055        $out['options'][$name] = myvita_sumo_clean(myvita_iw_stored(get_option($name)), (string) $name);
     1056    }
     1057
     1058    // 2. SUMO's own post types: how many, and three whole examples of each.
     1059    $types = $wpdb->get_col($wpdb->prepare(
     1060        "SELECT DISTINCT post_type FROM {$wpdb->posts} WHERE post_type LIKE %s",
     1061        '%' . $wpdb->esc_like('sumo') . '%'
     1062    ));
     1063    foreach ((array) $types as $type) {
     1064        $count = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s", $type));
     1065        $items = [];
     1066        foreach (get_posts(['post_type' => $type, 'post_status' => 'any', 'numberposts' => 3, 'orderby' => 'ID', 'order' => 'DESC', 'suppress_filters' => true]) as $item) {
     1067            $items[] = [
     1068                'id'       => $item->ID,
     1069                'status'   => $item->post_status,
     1070                'parent'   => $item->post_parent,
     1071                'title'    => myvita_sumo_clean($item->post_title),
     1072                'modified' => $item->post_modified_gmt,
     1073                'meta'     => myvita_sumo_meta($item->ID),
     1074            ];
     1075        }
     1076        $out['post_types'][$type] = ['count' => $count, 'examples' => $items];
     1077    }
     1078
     1079    // 3. SUMO's own tables: names, columns, row counts. Rows are not read.
     1080    $tables = $wpdb->get_col($wpdb->prepare('SHOW TABLES LIKE %s', '%' . $wpdb->esc_like('sumo') . '%'));
     1081    foreach ((array) $tables as $table) {
     1082        $quoted = '`' . str_replace('`', '``', $table) . '`';
     1083        $out['tables'][$table] = [
     1084            'rows'    => (int) $wpdb->get_var("SELECT COUNT(*) FROM {$quoted}"),
     1085            'columns' => (array) $wpdb->get_col("SHOW COLUMNS FROM {$quoted}", 0),
     1086        ];
     1087    }
     1088
     1089    // 3b. Each product's own plan settings (deposit rule, balance due date).
     1090    $out['products'] = myvita_sumo_products();
     1091
     1092    // 4. Example bookings: recent orders SUMO flagged, each with the orders
     1093    //    that name it as their parent. Up to four that have children, then up
     1094    //    to two that stand alone.
     1095    if (function_exists('wc_get_orders')) {
     1096        $flagged = wc_get_orders([
     1097            'limit'      => 40,
     1098            'orderby'    => 'date',
     1099            'order'      => 'DESC',
     1100            'meta_query' => [['key' => 'is_sumo_pp_order', 'compare' => 'EXISTS']],
     1101        ]);
     1102        $with = [];
     1103        $alone = [];
     1104        foreach ((array) $flagged as $order) {
     1105            $children = wc_get_orders(['parent' => $order->get_id(), 'limit' => 12, 'orderby' => 'date', 'order' => 'ASC']);
     1106            $row = ['booking' => myvita_sumo_order($order), 'children' => []];
     1107            foreach ((array) $children as $child) {
     1108                $row['children'][] = myvita_sumo_order($child);
     1109            }
     1110            if ($row['children'] && count($with) < 4) {
     1111                $with[] = $row;
     1112            } elseif (!$row['children'] && count($alone) < 2) {
     1113                $alone[] = $row;
     1114            }
     1115        }
     1116        $out['bookings'] = array_merge($with, $alone);
     1117    }
     1118
     1119    return $out;
     1120}
     1121
     1122add_action('admin_post_myvita_sumo_export', function (): void {
     1123    if (!current_user_can('manage_options')) {
     1124        wp_die('You need to be an administrator to do this.', '', ['response' => 403]);
     1125    }
     1126    check_admin_referer('myvita_sumo_export');
     1127    $json = wp_json_encode(myvita_sumo_collect(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR);
     1128    $host = sanitize_file_name((string) wp_parse_url(home_url(), PHP_URL_HOST));
     1129    nocache_headers();
     1130    header('Content-Type: application/json; charset=utf-8');
     1131    header('Content-Disposition: attachment; filename="myvitalassistant-sumo-' . $host . '-' . gmdate('Y-m-d') . '.json"');
     1132    echo $json; // phpcs:ignore WordPress.Security.EscapeOutput -- a JSON download, not a page
     1133    exit;
     1134});
     1135
     1136/** The card on the settings page, shown only where SUMO Payment Plans is active. */
     1137function myvita_sumo_card(): void
     1138{
     1139    if (!current_user_can('manage_options') || !myvita_sumo_present()) {
     1140        return;
     1141    }
     1142    ?>
     1143    <h2>Payment plan details</h2>
     1144    <p class="description" style="max-width:640px">
     1145        Planning to take deposits and instalments through MyVitalAssistant instead? This downloads one file showing how your payment plans plugin stores a booking: its settings, its own records and a few example bookings with their deposit and balance orders. It is made on this site and handed to your browser: nothing is sent anywhere and nothing is changed. No customer name, contact detail or user id is included. Look it over before you send it to anyone.
     1146    </p>
     1147    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
     1148        <input type="hidden" name="action" value="myvita_sumo_export" />
     1149        <?php wp_nonce_field('myvita_sumo_export'); ?>
     1150        <?php submit_button('Download payment plan details', 'secondary', 'submit', false); ?>
     1151    </form>
     1152    <?php
     1153}
     1154
     1155/* -------------------------------------------------------------------------
    5901156 * Settings
    5911157 * ---------------------------------------------------------------------- */
    5921158
    5931159add_action('admin_menu', function (): void {
    594     add_options_page('MyVitalAssistant', 'MyVitalAssistant', 'manage_options', 'myvita-tracking', 'myvita_settings_page');
     1160    // A menu item of its own, wearing the MyVitalAssistant mark. The mark is a
     1161    // full colour image shipped inside the plugin and drawn as a background of
     1162    // fixed size (see the style below): WordPress recolours an SVG data URI to
     1163    // grey, and an <img> icon is resized by themes and other plugins.
     1164    add_menu_page('MyVitalAssistant', 'MyVitalAssistant', 'manage_options', MYVITA_SETTINGS_PAGE, 'myvita_settings_page', 'none', 59);
     1165});
     1166
     1167add_action('admin_enqueue_scripts', function (): void {
     1168    wp_register_style('myvita-menu', false, [], MYVITA_VERSION);
     1169    wp_enqueue_style('myvita-menu');
     1170    $url = esc_url_raw(plugins_url('assets/menu-icon.png', __FILE__));
     1171    wp_add_inline_style(
     1172        'myvita-menu',
     1173        '#adminmenu .toplevel_page_' . MYVITA_SETTINGS_PAGE . ' div.wp-menu-image{background:url("' . $url . '") no-repeat center center;background-size:20px 20px;}'
     1174        . '#adminmenu .toplevel_page_' . MYVITA_SETTINGS_PAGE . ' div.wp-menu-image:before{content:"";}'
     1175    );
     1176});
     1177
     1178
     1179// A Settings link on the plugin's own row of the Plugins screen, so the page is
     1180// found where people look for it as well as under Settings.
     1181add_filter('plugin_action_links_' . plugin_basename(__FILE__), function (array $links): array {
     1182    if (!current_user_can('manage_options')) {
     1183        return $links;
     1184    }
     1185    $url = admin_url('admin.php?page=' . MYVITA_SETTINGS_PAGE);
     1186    array_unshift($links, '<a href="' . esc_url($url) . '">' . 'Settings' . '</a>');
     1187    return $links;
    5951188});
    5961189
    … …  
    8701463    // whatever args each event carries, which clear_scheduled_hook cannot.
    8711464    wp_unschedule_hook('myvita_retry_order');
     1465    wp_unschedule_hook('myvita_resend_check');
     1466    wp_unschedule_hook('myvita_trips_push');
     1467    wp_unschedule_hook('myvita_trips_hourly');
     1468    wp_unschedule_hook('myvita_backfill_tick');
    8721469});
    8731470
    … …  
    8831480    <div class="wrap">
    8841481        <h1>MyVitalAssistant</h1>
     1482        <?php settings_errors('myvita_tracking'); ?>
    8851483        <p>Serves tracking from <code><?php echo esc_html(home_url(MYVITA_PREFIX . '/')); ?></code> instead of a separate subdomain, so Safari keeps your visitors' attribution for 400 days instead of 7.</p>
    8861484        <?php if ($ready) : ?>
    … …  
    9701568            <?php submit_button(); ?>
    9711569        </form>
     1570        <?php if (myvita_support_tools()) { myvita_iw_card(); myvita_sumo_card(); } ?>
    9721571        <?php myvita_render_log(); ?>
    9731572    </div>
    … …  
    11061705}
    11071706
     1707/**
     1708 * The checkout meta keys a person mapped on the Worker's settings page, which
     1709 * are the ONLY extra order meta whose values may leave this site.
     1710 *
     1711 * Asked of the collector (`GET /order/field-keys`, same token as an order) and
     1712 * kept for ten minutes. Nothing is sent when the answer is missing, late or
     1713 * malformed: a failed lookup means no extra values, never a guess.
     1714 */
     1715function myvita_checkout_keys(): array
     1716{
     1717    $cached = get_transient('myvita_field_keys');
     1718    if (is_array($cached)) {
     1719        return $cached;
     1720    }
     1721    $options = myvita_options();
     1722    if ($options['account'] === '' || $options['ingest'] === '') {
     1723        return [];
     1724    }
     1725    $res = wp_remote_get(
     1726        $options['origin'] . '/order/field-keys?a=' . rawurlencode($options['account']),
     1727        [
     1728            'headers' => ['Authorization' => 'Bearer ' . $options['ingest']],
     1729            'timeout' => 2,
     1730        ]
     1731    );
     1732    if (is_wp_error($res) || (int) wp_remote_retrieve_response_code($res) !== 200) {
     1733        return [];
     1734    }
     1735    $body = json_decode((string) wp_remote_retrieve_body($res), true);
     1736    $keys = [];
     1737    if (is_array($body) && isset($body['resend'])) {
     1738        myvita_note_resend($body['resend']);
     1739    }
     1740    if (is_array($body) && isset($body['keys']) && is_array($body['keys'])) {
     1741        foreach ($body['keys'] as $k) {
     1742            if (is_string($k) && preg_match('/^[A-Za-z0-9_\-. ]{1,100}$/', $k)) {
     1743                $keys[] = $k;
     1744            }
     1745        }
     1746    }
     1747    set_transient('myvita_field_keys', $keys, 10 * MINUTE_IN_SECONDS);
     1748    return $keys;
     1749}
     1750
     1751/**
     1752 * PAST ORDERS, SENT AGAIN WHEN THE ACCOUNT ASKS.
     1753 *
     1754 * Orders sent before a checkout field was mapped carried none of its values,
     1755 * which still sit in this store's database. The collector's answer to the
     1756 * lookup above can carry `resend`, a moment (set when a mapping is saved with
     1757 * automatic resend on, or when the owner presses the button there). When it
     1758 * differs from the one this site last acted on, the history walk below runs
     1759 * again from the first order. A redelivery overwrites by key, so nothing is
     1760 * duplicated. The lookup also runs hourly on its own, so a site with no new
     1761 * orders still notices.
     1762 */
     1763const MYVITA_RESEND_SEEN = 'myvita_resend_seen';
     1764
     1765function myvita_note_resend($stamp): void
     1766{
     1767    if (!is_string($stamp) || !preg_match('/^\d{4}-\d{2}-\d{2}T[0-9:.]{8,14}Z$/', $stamp)) {
     1768        return;
     1769    }
     1770    if (get_option(MYVITA_RESEND_SEEN, '') === $stamp) {
     1771        return;
     1772    }
     1773    update_option(MYVITA_RESEND_SEEN, $stamp, false);
     1774    $options = myvita_options();
     1775    if ($options['account'] === '' || $options['ingest'] === '' || !myvita_sync_enabled('sync_orders') || !function_exists('wc_get_orders')) {
     1776        return;
     1777    }
     1778    update_option(MYVITA_BACKFILL_OPTION, ['started' => time(), 'offset' => 0, 'sent' => 0, 'done' => 0], false);
     1779    if (!wp_next_scheduled('myvita_backfill_tick')) {
     1780        wp_schedule_single_event(time() + 30, 'myvita_backfill_tick');
     1781    }
     1782}
     1783
     1784function myvita_resend_check(): void
     1785{
     1786    delete_transient('myvita_field_keys');
     1787    myvita_checkout_keys();
     1788}
     1789add_action('myvita_resend_check', 'myvita_resend_check');
     1790add_action('init', function (): void {
     1791    if (!wp_next_scheduled('myvita_resend_check')) {
     1792        wp_schedule_event(time() + 600, 'hourly', 'myvita_resend_check');
     1793    }
     1794});
     1795
     1796/**
     1797 * THE TRIPS THIS STORE HAS ON SALE, TOLD TO THE ACCOUNT.
     1798 *
     1799 * A form on the MyVitalAssistant side can ask "which trip are you interested
     1800 * in" and offer the products that are for sale right now. For that the
     1801 * account needs the store's product categories and its published products:
     1802 * each product's title, its stock status and the ids of its categories. No
     1803 * price, no description, no customer, nothing about an order. Only with the
     1804 * order sync key, like the checkout field names. Sent when a product or a
     1805 * category is added, changed, unpublished or removed (coalesced into one send
     1806 * a minute later) and once an hour as a backstop; an unchanged list is not
     1807 * sent again for a day. A failed send is simply tried at the next change or
     1808 * the next hour.
     1809 */
     1810const MYVITA_TRIPS_HASH = 'myvita_trips_hash';
     1811
     1812function myvita_trips_payload(): array
     1813{
     1814    $categories = [];
     1815    $terms = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false, 'number' => 300]);
     1816    if (is_array($terms)) {
     1817        foreach ($terms as $term) {
     1818            $categories[] = [
     1819                'id'     => (int) $term->term_id,
     1820                'name'   => (string) $term->name,
     1821                'parent' => (int) $term->parent,
     1822                'count'  => (int) $term->count,
     1823            ];
     1824        }
     1825    }
     1826    $trips = [];
     1827    $ids = get_posts([
     1828        'post_type'        => 'product',
     1829        'post_status'      => 'publish',
     1830        'numberposts'      => 500,
     1831        'fields'           => 'ids',
     1832        'orderby'          => 'title',
     1833        'order'            => 'ASC',
     1834        'suppress_filters' => true,
     1835    ]);
     1836    foreach ((array) $ids as $id) {
     1837        $product = wc_get_product($id);
     1838        if (!$product || $product->get_catalog_visibility() === 'hidden') {
     1839            continue;
     1840        }
     1841        $trips[] = [
     1842            'id'    => (int) $id,
     1843            'title' => wp_strip_all_tags((string) $product->get_name()),
     1844            'stock' => (string) $product->get_stock_status(),
     1845            'cats'  => array_map('intval', (array) $product->get_category_ids()),
     1846        ];
     1847    }
     1848    return ['categories' => $categories, 'trips' => $trips];
     1849}
     1850
     1851function myvita_push_trips(): void
     1852{
     1853    $options = myvita_options();
     1854    if ($options['account'] === '' || $options['ingest'] === '' || !function_exists('wc_get_product')) {
     1855        return;
     1856    }
     1857    $body = wp_json_encode(myvita_trips_payload());
     1858    if (!is_string($body)) {
     1859        return;
     1860    }
     1861    $hash = md5($body);
     1862    $last = get_option(MYVITA_TRIPS_HASH, []);
     1863    if (is_array($last) && ($last['hash'] ?? '') === $hash && (int) ($last['at'] ?? 0) > time() - DAY_IN_SECONDS) {
     1864        return;
     1865    }
     1866    $res = wp_remote_post(
     1867        $options['origin'] . '/order/trips?a=' . rawurlencode($options['account']),
     1868        [
     1869            'headers' => ['Authorization' => 'Bearer ' . $options['ingest'], 'Content-Type' => 'application/json'],
     1870            'body'    => $body,
     1871            'timeout' => 8,
     1872        ]
     1873    );
     1874    if (!is_wp_error($res) && (int) wp_remote_retrieve_response_code($res) === 200) {
     1875        update_option(MYVITA_TRIPS_HASH, ['hash' => $hash, 'at' => time()], false);
     1876    }
     1877}
     1878add_action('myvita_trips_push', 'myvita_push_trips');
     1879
     1880/** One send a minute after the last change, however many changes there were. */
     1881function myvita_queue_trips_push(): void
     1882{
     1883    if (!wp_next_scheduled('myvita_trips_push')) {
     1884        wp_schedule_single_event(time() + 60, 'myvita_trips_push');
     1885    }
     1886}
     1887add_action('woocommerce_update_product', 'myvita_queue_trips_push');
     1888add_action('woocommerce_new_product', 'myvita_queue_trips_push');
     1889add_action('woocommerce_product_set_stock_status', 'myvita_queue_trips_push');
     1890add_action('woocommerce_delete_product', 'myvita_queue_trips_push');
     1891add_action('woocommerce_trash_product', 'myvita_queue_trips_push');
     1892add_action('woocommerce_untrash_product', 'myvita_queue_trips_push');
     1893add_action('created_product_cat', 'myvita_queue_trips_push');
     1894add_action('edited_product_cat', 'myvita_queue_trips_push');
     1895add_action('delete_product_cat', 'myvita_queue_trips_push');
     1896add_action('transition_post_status', function ($new, $old, $post): void {
     1897    if ($new !== $old && is_object($post) && $post->post_type === 'product') {
     1898        myvita_queue_trips_push();
     1899    }
     1900}, 10, 3);
     1901add_action('myvita_trips_hourly', 'myvita_push_trips');
     1902add_action('init', function (): void {
     1903    if (!wp_next_scheduled('myvita_trips_hourly')) {
     1904        wp_schedule_event(time() + 900, 'hourly', 'myvita_trips_hourly');
     1905    }
     1906});
     1907
     1908/**
     1909 * The NAMES of the meta on an order (never the values), so the settings page
     1910 * can list them instead of asking for each to be typed. Internal and
     1911 * attribution keys are left out; at most 150 are sent.
     1912 */
     1913function myvita_order_meta_names(\WC_Order $order): array
     1914{
     1915    $names = [];
     1916    foreach ($order->get_meta_data() as $m) {
     1917        $k = (string) $m->key;
     1918        if ($k === '' || strpos($k, '_wc_order_attribution_') === 0 || strpos($k, '_edit_') === 0) {
     1919            continue;
     1920        }
     1921        if (preg_match('/^[A-Za-z0-9_\-. ]{1,100}$/', $k)) {
     1922            $names[$k] = true;
     1923        }
     1924        if (count($names) >= 150) {
     1925            break;
     1926        }
     1927    }
     1928    return array_keys($names);
     1929}
     1930
    11081931function myvita_order_payload(\WC_Order $order): array
    11091932{
    … …  
    11111934    foreach ($order->get_items() as $item_id => $item) {
    11121935        $product = method_exists($item, 'get_product') ? $item->get_product() : null;
    1113         $lines[] = [
     1936        $line = [
    11141937            'id'           => (int) $item_id,
    11151938            'name'         => (string) $item->get_name(),
    … …  
    11191942            'subtotal_tax' => (string) $item->get_subtotal_tax(),
    11201943        ];
     1944        // The CRM product and tags chosen on the product's MyVitalAssistant
     1945        // tab (or InfusedWoo's, which are read and never written).
     1946        $crm = myvita_line_crm($product);
     1947        if ($crm !== null) {
     1948            $line['crm'] = $crm;
     1949        }
     1950        $lines[] = $line;
    11211951    }
    11221952
    … …  
    11591989
    11601990    $meta = [];
    1161     foreach (myvita_order_meta_allowlist() as $key) {
     1991    // The allowlist plus the keys a person mapped on the settings page. Nothing
     1992    // else crosses the wire: a passport number stays here unless mapped.
     1993    foreach (array_values(array_unique(array_merge(myvita_order_meta_allowlist(), myvita_checkout_keys()))) as $key) {
    11621994        $value = $order->get_meta($key, true);
    11631995        if ($value !== '' && $value !== null && !is_array($value)) {
    … …  
    11902022            'company'    => (string) $order->get_billing_company(),
    11912023        ],
     2024        'meta_keys'     => myvita_order_meta_names($order),
    11922025        'line_items'    => $lines,
    11932026        'shipping_lines' => $shipping,
    … …  
    11982031    ];
    11992032}
     2033
     2034/* -------------------------------------------------------------------------
     2035 * The MyVitalAssistant tab on a WooCommerce product and variation
     2036 *
     2037 * Which CRM product (or subscription plan) a sale of this product is, and
     2038 * which tags the buyer gets once it is paid. The same two choices InfusedWoo's
     2039 * own product tab holds, read from MyVitalAssistant's list of the CRM's
     2040 * products, plans and tags rather than from the CRM itself, so this site never
     2041 * holds a CRM credential.
     2042 *
     2043 * Order of use, the order InfusedWoo itself uses: a choice made here first,
     2044 * then the fields InfusedWoo saved on the same product, then the SKU. A
     2045 * variation's own choice wins over its product's for the CRM product, and the
     2046 * tags are the product's plus the variation's.
     2047 * ---------------------------------------------------------------------- */
     2048
     2049const MYVITA_META_TYPE    = '_myvita_crm_type';
     2050const MYVITA_META_PRODUCT = '_myvita_crm_product';
     2051const MYVITA_META_PLAN    = '_myvita_crm_plan';
     2052const MYVITA_META_TAGS    = '_myvita_crm_tags';
     2053
     2054/** Digits only: a CRM id is a number, and anything else is not one. */
     2055function myvita_crm_id($value): string
     2056{
     2057    if (!is_scalar($value)) {
     2058        return '';
     2059    }
     2060    $text = trim((string) $value);
     2061    return preg_match('/^[0-9]{1,12}$/', $text) === 1 ? $text : '';
     2062}
     2063
     2064/** A list of CRM ids, digits only, no blanks, no repeats, at most twenty. */
     2065function myvita_crm_ids($value): array
     2066{
     2067    if (is_string($value) && $value !== '') {
     2068        $value = [$value];
     2069    }
     2070    if (!is_array($value)) {
     2071        return [];
     2072    }
     2073    $out = [];
     2074    foreach ($value as $one) {
     2075        $id = myvita_crm_id($one);
     2076        if ($id !== '' && !in_array($id, $out, true)) {
     2077            $out[] = $id;
     2078        }
     2079    }
     2080    return array_slice($out, 0, 20);
     2081}
     2082
     2083/**
     2084 * Whether the tab is offered: WooCommerce is here and this site is linked to an
     2085 * account. The order sync key is NOT required: choices are saved on the site
     2086 * and nothing leaves it until orders are switched on, and without the key the
     2087 * pickers simply cannot look up names.
     2088 */
     2089function myvita_crm_tab_enabled(): bool
     2090{
     2091    if (!class_exists('WooCommerce') || !current_user_can('edit_products')) {
     2092        return false;
     2093    }
     2094    $options = myvita_options();
     2095    return $options['account'] !== '';
     2096}
     2097
     2098/** What this plugin saved on a product or variation. */
     2099function myvita_crm_saved(int $post_id): array
     2100{
     2101    return [
     2102        'type'    => get_post_meta($post_id, MYVITA_META_TYPE, true) === 'subscription' ? 'subscription' : 'product',
     2103        'product' => myvita_crm_id(get_post_meta($post_id, MYVITA_META_PRODUCT, true)),
     2104        'plan'    => myvita_crm_id(get_post_meta($post_id, MYVITA_META_PLAN, true)),
     2105        'tags'    => myvita_crm_ids(get_post_meta($post_id, MYVITA_META_TAGS, true)),
     2106    ];
     2107}
     2108
     2109/** What InfusedWoo saved on the same product, read and never written. */
     2110function myvita_crm_infusedwoo(int $post_id): array
     2111{
     2112    $type = get_post_meta($post_id, 'infusionsoft_type', true);
     2113    return [
     2114        'type'    => $type === 'Subscription' ? 'subscription' : 'product',
     2115        'product' => myvita_crm_id(get_post_meta($post_id, 'infusionsoft_product', true)),
     2116        'plan'    => myvita_crm_id(get_post_meta($post_id, 'infusionsoft_sub', true)),
     2117        'tags'    => myvita_crm_ids(get_post_meta($post_id, 'infusionsoft_tag', true)),
     2118    ];
     2119}
     2120
     2121/**
     2122 * The choice for one product or variation: ours when it has anything, else
     2123 * InfusedWoo's, and where each came from.
     2124 */
     2125function myvita_crm_choice(int $post_id): array
     2126{
     2127    $mine = myvita_crm_saved($post_id);
     2128    if ($mine['product'] !== '' || $mine['plan'] !== '' || $mine['tags']) {
     2129        return $mine + ['from' => 'mva'];
     2130    }
     2131    $theirs = myvita_crm_infusedwoo($post_id);
     2132    if ($theirs['product'] !== '' || $theirs['plan'] !== '' || $theirs['tags']) {
     2133        return $theirs + ['from' => 'infusedwoo'];
     2134    }
     2135    return $mine + ['from' => ''];
     2136}
     2137
     2138/**
     2139 * What an order line tells the collector about its CRM product, or null when
     2140 * nothing was chosen anywhere and the SKU has to do.
     2141 */
     2142function myvita_line_crm($product): ?array
     2143{
     2144    if (!is_object($product) || !method_exists($product, 'get_id')) {
     2145        return null;
     2146    }
     2147    $own    = myvita_crm_choice((int) $product->get_id());
     2148    $parent = method_exists($product, 'get_parent_id') ? (int) $product->get_parent_id() : 0;
     2149    $up     = $parent > 0 ? myvita_crm_choice($parent) : ['type' => 'product', 'product' => '', 'plan' => '', 'tags' => [], 'from' => ''];
     2150
     2151    $product_id = $own['product'] !== '' ? $own['product'] : $up['product'];
     2152    $plan_id    = $own['plan'] !== '' ? $own['plan'] : $up['plan'];
     2153    $tags       = myvita_crm_ids(array_merge($up['tags'], $own['tags']));
     2154    $from       = $own['from'] !== '' ? $own['from'] : $up['from'];
     2155    if ($product_id === '' && $plan_id === '' && !$tags) {
     2156        return null;
     2157    }
     2158    $out = [];
     2159    if ($product_id !== '') {
     2160        $out['product_id'] = $product_id;
     2161    }
     2162    if ($plan_id !== '') {
     2163        $out['plan_id'] = $plan_id;
     2164    }
     2165    if ($tags) {
     2166        $out['tag_ids'] = $tags;
     2167    }
     2168    if ($from !== '') {
     2169        $out['from'] = $from;
     2170    }
     2171    return $out;
     2172}
     2173
     2174/**
     2175 * Ask the collector for a page of the account's CRM products, plans or tags.
     2176 * Read only, and only the account id and the access token this site was given
     2177 * when it linked leave the site.
     2178 */
     2179function myvita_catalogue_fetch(array $query): array
     2180{
     2181    $options = myvita_options();
     2182    if ($options['account'] === '' || $options['token'] === '') {
     2183        return ['ok' => false];
     2184    }
     2185    $args = ['a' => $options['account'], 't' => $options['token']] + $query;
     2186    $res  = wp_remote_get(
     2187        $options['origin'] . '/wp/catalogue?' . http_build_query($args, '', '&'),
     2188        ['timeout' => 8]
     2189    );
     2190    if (is_wp_error($res) || wp_remote_retrieve_response_code($res) !== 200) {
     2191        return ['ok' => false];
     2192    }
     2193    $body = json_decode((string) wp_remote_retrieve_body($res), true);
     2194    return is_array($body) && !empty($body['ok']) ? $body : ['ok' => false];
     2195}
     2196
     2197/** The picker's data, shaped for selectWoo. */
     2198add_action('wp_ajax_myvita_catalogue', function (): void {
     2199    if (!current_user_can('edit_products')) {
     2200        wp_send_json_error(null, 403);
     2201    }
     2202    check_ajax_referer('myvita_catalogue', 'nonce');
     2203    $kind = isset($_GET['kind']) ? sanitize_key(wp_unslash($_GET['kind'])) : 'product';
     2204    $kind = in_array($kind, ['product', 'plan', 'tag'], true) ? $kind : 'product';
     2205    $query = ['kind' => $kind];
     2206    if (isset($_GET['q'])) {
     2207        $query['q'] = sanitize_text_field(wp_unslash($_GET['q']));
     2208    }
     2209    if (isset($_GET['page'])) {
     2210        $query['page'] = max(1, (int) $_GET['page']);
     2211    }
     2212    if (isset($_GET['ids'])) {
     2213        $query['ids'] = implode(',', myvita_crm_ids(explode(',', sanitize_text_field(wp_unslash($_GET['ids'])))));
     2214    }
     2215    if (isset($_GET['product'])) {
     2216        $query['product'] = myvita_crm_id(wp_unslash($_GET['product']));
     2217    }
     2218    $body = myvita_catalogue_fetch($query);
     2219    if (empty($body['ok'])) {
     2220        wp_send_json(['results' => [], 'pagination' => ['more' => false], 'crm' => '']);
     2221    }
     2222    $names = ['keap' => 'Keap', 'ghl' => 'HighLevel'];
     2223    $crm   = isset($body['crm'], $names[$body['crm']]) ? $names[$body['crm']] : '';
     2224    wp_send_json([
     2225        'results'    => isset($body['results']) && is_array($body['results']) ? $body['results'] : [],
     2226        'pagination' => ['more' => !empty($body['more'])],
     2227        'crm'        => $crm,
     2228    ]);
     2229});
     2230
     2231add_filter('woocommerce_product_data_tabs', function (array $tabs): array {
     2232    if (!myvita_crm_tab_enabled()) {
     2233        return $tabs;
     2234    }
     2235    $tabs['myvita_crm'] = [
     2236        'label'    => 'MyVitalAssistant',
     2237        'target'   => 'myvita_crm_data',
     2238        'class'    => ['show_if_simple', 'show_if_variable'],
     2239        'priority' => 85,
     2240    ];
     2241    return $tabs;
     2242});
     2243
     2244/**
     2245 * The pickers, the same for a product and for a variation. The saved choice is
     2246 * drawn as bare ids, and a script fills in their names once the page is up,
     2247 * so opening a product never waits on the collector.
     2248 */
     2249function myvita_crm_fields(array $choice, string $prefix, bool $variation): void
     2250{
     2251    $type = $choice['type'];
     2252    ?>
     2253    <div class="myvita-crm" data-variation="<?php echo $variation ? '1' : '0'; ?>">
     2254        <?php if (!$variation) : ?>
     2255            <p class="form-field">
     2256                <label for="<?php echo esc_attr($prefix); ?>_type">Product or subscription?</label>
     2257                <select id="<?php echo esc_attr($prefix); ?>_type" name="<?php echo esc_attr($prefix); ?>_type" class="myvita-type">
     2258                    <option value="product"<?php selected($type, 'product'); ?>>Product</option>
     2259                    <option value="subscription"<?php selected($type, 'subscription'); ?>>Subscription</option>
     2260                </select>
     2261            </p>
     2262        <?php endif; ?>
     2263        <p class="form-field">
     2264            <label for="<?php echo esc_attr($prefix); ?>_product">Product being sold</label>
     2265            <select id="<?php echo esc_attr($prefix); ?>_product" name="<?php echo esc_attr($prefix); ?>_product" class="myvita-pick" data-kind="product" data-placeholder="Leave empty to match by SKU" style="width:50%">
     2266                <?php if ($choice['product'] !== '') : ?>
     2267                    <option value="<?php echo esc_attr($choice['product']); ?>" selected="selected">#<?php echo esc_html($choice['product']); ?></option>
     2268                <?php endif; ?>
     2269            </select>
     2270        </p>
     2271        <?php if (!$variation) : ?>
     2272            <p class="form-field myvita-plan-row"<?php echo $type === 'subscription' ? '' : ' style="display:none"'; ?>>
     2273                <label for="<?php echo esc_attr($prefix); ?>_plan">Subscription plan</label>
     2274                <select id="<?php echo esc_attr($prefix); ?>_plan" name="<?php echo esc_attr($prefix); ?>_plan" class="myvita-pick" data-kind="plan" data-placeholder="Choose the product first, then its plan" style="width:50%">
     2275                    <?php if ($choice['plan'] !== '') : ?>
     2276                        <option value="<?php echo esc_attr($choice['plan']); ?>" selected="selected">#<?php echo esc_html($choice['plan']); ?></option>
     2277                    <?php endif; ?>
     2278                </select>
     2279            </p>
     2280        <?php endif; ?>
     2281        <p class="form-field">
     2282            <label for="<?php echo esc_attr($prefix); ?>_tags">Tags to apply upon successful purchase</label>
     2283            <select id="<?php echo esc_attr($prefix); ?>_tags" name="<?php echo esc_attr($prefix); ?>_tags[]" class="myvita-pick" data-kind="tag" multiple="multiple" data-placeholder="Search tags" style="width:50%">
     2284                <?php foreach ($choice['tags'] as $tag_id) : ?>
     2285                    <option value="<?php echo esc_attr($tag_id); ?>" selected="selected">#<?php echo esc_html($tag_id); ?></option>
     2286                <?php endforeach; ?>
     2287            </select>
     2288        </p>
     2289    </div>
     2290    <?php
     2291}
     2292
     2293add_action('woocommerce_product_data_panels', function (): void {
     2294    global $post;
     2295    if (!myvita_crm_tab_enabled() || !$post) {
     2296        return;
     2297    }
     2298    $choice = myvita_crm_choice((int) $post->ID);
     2299    ?>
     2300    <div id="myvita_crm_data" class="panel woocommerce_options_panel">
     2301        <div class="options_group">
     2302            <h4 style="padding:0 12px"><span class="myvita-crm-name">Your CRM</span></h4>
     2303            <p class="description" style="padding:0 12px">Which product in your CRM this sells, and the tags a buyer gets once they have paid. With no product chosen here, the SKU is used.</p>
     2304            <?php if ($choice['from'] === 'infusedwoo') : ?>
     2305                <p style="padding:0 12px"><strong>These are filled in from InfusedWoo.</strong> Saving this product keeps them here.</p>
     2306            <?php endif; ?>
     2307            <?php wp_nonce_field('myvita_crm_save', 'myvita_crm_nonce'); ?>
     2308            <?php myvita_crm_fields($choice, 'myvita_crm', false); ?>
     2309        </div>
     2310    </div>
     2311    <?php
     2312});
     2313
     2314add_action('woocommerce_process_product_meta', function ($post_id): void {
     2315    $post_id = (int) $post_id;
     2316    if (!isset($_POST['myvita_crm_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['myvita_crm_nonce'])), 'myvita_crm_save')) {
     2317        return;
     2318    }
     2319    if (!current_user_can('edit_post', $post_id)) {
     2320        return;
     2321    }
     2322    $type = isset($_POST['myvita_crm_type']) && sanitize_key(wp_unslash($_POST['myvita_crm_type'])) === 'subscription' ? 'subscription' : 'product';
     2323    update_post_meta($post_id, MYVITA_META_TYPE, $type);
     2324    update_post_meta($post_id, MYVITA_META_PRODUCT, isset($_POST['myvita_crm_product']) ? myvita_crm_id(wp_unslash($_POST['myvita_crm_product'])) : '');
     2325    update_post_meta($post_id, MYVITA_META_PLAN, $type === 'subscription' && isset($_POST['myvita_crm_plan']) ? myvita_crm_id(wp_unslash($_POST['myvita_crm_plan'])) : '');
     2326    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- every value is reduced to digits by myvita_crm_ids
     2327    $tags = isset($_POST['myvita_crm_tags']) ? myvita_crm_ids(wp_unslash($_POST['myvita_crm_tags'])) : [];
     2328    update_post_meta($post_id, MYVITA_META_TAGS, $tags);
     2329});
     2330
     2331/** A variation's own choices: its CRM product and any extra tags. */
     2332add_action('woocommerce_product_after_variable_attributes', function ($loop, $variation_data, $variation): void {
     2333    if (!myvita_crm_tab_enabled() || !is_object($variation)) {
     2334        return;
     2335    }
     2336    $choice = myvita_crm_choice((int) $variation->ID);
     2337    ?>
     2338    <div class="myvita-crm-variation">
     2339        <p><strong>MyVitalAssistant</strong><?php echo $choice['from'] === 'infusedwoo' ? ' (filled in from InfusedWoo; saving keeps it here)' : ''; ?></p>
     2340        <?php wp_nonce_field('myvita_crm_var_save', 'myvita_crm_var_nonce[' . (int) $loop . ']'); ?>
     2341        <?php myvita_crm_fields($choice, 'myvita_crm_var_' . (int) $loop, true); ?>
     2342    </div>
     2343    <?php
     2344}, 20, 3);
     2345
     2346add_action('woocommerce_save_product_variation', function ($variation_id, $i): void {
     2347    $variation_id = (int) $variation_id;
     2348    $i            = (int) $i;
     2349    $nonce        = isset($_POST['myvita_crm_var_nonce'][$i]) ? sanitize_text_field(wp_unslash($_POST['myvita_crm_var_nonce'][$i])) : '';
     2350    if ($nonce === '' || !wp_verify_nonce($nonce, 'myvita_crm_var_save')) {
     2351        return;
     2352    }
     2353    if (!current_user_can('edit_post', $variation_id)) {
     2354        return;
     2355    }
     2356    $key = 'myvita_crm_var_' . $i;
     2357    update_post_meta($variation_id, MYVITA_META_PRODUCT, isset($_POST[$key . '_product']) ? myvita_crm_id(wp_unslash($_POST[$key . '_product'])) : '');
     2358    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- every value is reduced to digits by myvita_crm_ids
     2359    update_post_meta($variation_id, MYVITA_META_TAGS, isset($_POST[$key . '_tags']) ? myvita_crm_ids(wp_unslash($_POST[$key . '_tags'])) : []);
     2360}, 10, 2);
     2361
     2362/** The pickers' script, only on the product editor. */
     2363add_action('admin_enqueue_scripts', function ($hook): void {
     2364    if (!in_array($hook, ['post.php', 'post-new.php'], true) || !myvita_crm_tab_enabled()) {
     2365        return;
     2366    }
     2367    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
     2368    if (!$screen || $screen->post_type !== 'product') {
     2369        return;
     2370    }
     2371    wp_enqueue_script('selectWoo');
     2372    $cfg = wp_json_encode([
     2373        'url'   => admin_url('admin-ajax.php'),
     2374        'nonce' => wp_create_nonce('myvita_catalogue'),
     2375    ]);
     2376    $js = <<<'JS'
     2377(function ($) {
     2378    var cfg = __CFG__;
     2379    function productOf($el) {
     2380        return $el.closest('.myvita-crm').find('select[data-kind="product"]').val() || '';
     2381    }
     2382    function showCrm(name) {
     2383        if (name) { $('.myvita-crm-name').text(name); }
     2384    }
     2385    function nameThem($el) {
     2386        var ids = $el.val();
     2387        if (!ids || !ids.length) { return; }
     2388        ids = $.isArray(ids) ? ids : [ids];
     2389        $.getJSON(cfg.url, {
     2390            action: 'myvita_catalogue', nonce: cfg.nonce, kind: $el.data('kind'),
     2391            ids: ids.join(','), product: productOf($el)
     2392        }, function (d) {
     2393            showCrm(d && d.crm);
     2394            $.each((d && d.results) || [], function (_, row) {
     2395                $el.find('option').filter(function () { return this.value === String(row.id); }).text(row.text);
     2396            });
     2397            $el.trigger('change.select2');
     2398        });
     2399    }
     2400    function start(scope) {
     2401        $(scope).find('select.myvita-pick').each(function () {
     2402            var $el = $(this);
     2403            if ($el.data('myvitaStarted')) { return; }
     2404            $el.data('myvitaStarted', 1);
     2405            $el.selectWoo({
     2406                allowClear: true,
     2407                width: '50%',
     2408                placeholder: $el.data('placeholder') || '',
     2409                tags: true,
     2410                createTag: function (p) {
     2411                    var t = $.trim(p.term);
     2412                    return /^[0-9]{1,12}$/.test(t) ? { id: t, text: t + ' (id)' } : null;
     2413                },
     2414                ajax: {
     2415                    url: cfg.url, dataType: 'json', delay: 250,
     2416                    data: function (p) {
     2417                        return { action: 'myvita_catalogue', nonce: cfg.nonce, kind: $el.data('kind'), q: p.term || '', page: p.page || 1, product: productOf($el) };
     2418                    },
     2419                    processResults: function (d) {
     2420                        showCrm(d && d.crm);
     2421                        return { results: (d && d.results) || [], pagination: { more: !!(d && d.pagination && d.pagination.more) } };
     2422                    }
     2423                }
     2424            });
     2425            nameThem($el);
     2426        });
     2427    }
     2428    $(function () {
     2429        start(document);
     2430        $('#woocommerce-product-data').on('change', '.myvita-type', function () {
     2431            $('.myvita-plan-row').toggle($(this).val() === 'subscription');
     2432        });
     2433    });
     2434    $(document.body).on('woocommerce_variations_loaded', function () { start(document); });
     2435})(jQuery);
     2436JS;
     2437    wp_add_inline_script('selectWoo', str_replace('__CFG__', (string) $cfg, $js));
     2438});
    12002439
    12012440/**
    … …  
    17082947    $log = get_option(MYVITA_LOG_OPTION, []);
    17092948    if (!is_array($log) || $log === []) {
    1710         echo '<h2>Form capture activity</h2><p>No captures yet. Submit any form on the site and it appears here.</p>';
    1711         return;
    1712     }
    1713     echo '<h2>Form capture activity</h2>';
     2949        echo '<details style="margin-top:1.5em"><summary><strong>Troubleshooting: form capture activity</strong></summary><p>No captures yet. Submit any form on the site and it appears here.</p></details>';
     2950        return;
     2951    }
     2952    echo '<details style="margin-top:1.5em"><summary><strong>Troubleshooting: form capture activity</strong></summary>';
    17142953    echo '<p>The last ' . (int) count($log) . ' form submissions this plugin captured and sent along with their attribution. Newest first.</p>';
    17152954    echo '<table class="widefat striped" style="max-width:760px"><thead><tr>';
    … …  
    17322971        );
    17332972    }
    1734     echo '</tbody></table>';
    1735 }
     2973    echo '</tbody></table></details>';
     2974}
  • myvitalassistant/trunk/readme.txt

    r3666161 r3845360  
    33Tags: attribution, analytics, keap, woocommerce, tracking
    44Requires at least: 6.3
    5 Tested up to: 7.0
     5Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.6.1
     7Stable tag: 1.6.10
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    3434
    3535* **Visitor tracking beacons.** When a page loads, the tracking script sends the page URL, referrer, any ad click ids and UTM parameters on the URL, and an anonymous visitor id, through your own /vt/ path to the collector. This runs on every public page view once the plugin is connected.
     36* **The shape of your page's forms.** Only if Tracking Forms is switched on in your MyVitalAssistant account: once per page per visitor per day, a few seconds after the page loads, the tracking script reads the forms on the page and sends their shape through your own /vt/ path to the collector: each question's label, type, name, placeholder and whether it is required, a dropdown's choices, the button's words, the heading above the form, and the page's address without its query string. Never what a visitor typed, never a hidden field and never a password box. It lets you recreate a form from your site in MyVitalAssistant.
    3637* **Form captures.** When one of the supported form plugins accepts a submission, the plugin sends the submitted email, name, and phone plus the visitor's attribution cookie to the collector, so the lead's contact in your connected CRM receives its attribution.
    37 * **WooCommerce orders.** Only if you paste the optional order sync key: order number, status, totals, line items, billing name, email, phone and company, coupon and refund details, and WooCommerce's own attribution meta are sent when payment completes, when status changes, and when a refund is recorded.
     38* **WooCommerce orders.** Only if you paste the optional order sync key: order number, status, totals, line items (with the CRM product and tags you chose on each product, if any), billing name, email, phone and company, coupon and refund details, and WooCommerce's own attribution meta, plus ONLY the checkout fields you chose in your MyVitalAssistant account, are sent when payment completes, when status changes, and when a refund is recorded.
     39* **Checkout field names.** Only with the order sync key: with each order, the names (never the values) of the order meta keys on that order, so your MyVitalAssistant account can list them for you to choose from, and, before an order is sent, a request (to /order/field-keys on your collector) asking your account which checkout fields you chose.
     40* **Your trips for sale.** Only with the order sync key: your store's product categories and its published products (each product's title, its stock status and the ids of its categories, never a price, a description or anything about a customer or an order), so a form in your MyVitalAssistant account can offer the trips you have on sale. Sent when you add, change or remove a product or category, and once an hour; an unchanged list is not sent again for a day.
    3841* **Account linking.** When you enter your MyVitalAssistant email on the settings page, the plugin sends that email and your site URL once to look up your account.
     42* **Your CRM's products, plans and tags.** When you edit a WooCommerce product, the MyVitalAssistant tab asks the collector for the products, subscription plans and tags in your connected CRM (the catalogue), sending only your account id and the access token the service issued when you linked, and the words you typed to search. Only names and ids come back. Nothing is sent when you are not editing a product.
    3943* **Your list of tracking forms.** On the settings page and in the block editor, the plugin asks the collector which forms your account has, sending only your account id and the access token the service issued when you linked. Only each form's name and its short code come back. The answer is cached for twelve hours.
    4044* **Placing a tracking form on a page.** If you place one of your MyVitalAssistant forms with the block or the shortcode, that page loads the form's script from the collector when a visitor views it, and what the visitor types is sent to the collector when they submit. The form itself is stored by the service rather than on this site. Pages with no form placed on them are unaffected.
     45* **A form that asks as a conversation.** If you set one of your forms to ask its questions as a conversation with an AI assistant (a setting in your MyVitalAssistant account, not on this site), each message the visitor sends goes to the collector as they send it, with the answers given so far. The collector passes it, with your business's name and the form's own questions, to Anthropic's Claude model, which suggests the next question; Anthropic's [commercial terms](https://www.anthropic.com/legal/commercial-terms) and [privacy policy](https://www.anthropic.com/legal/privacy) cover that processing. The service stores none of the conversation: the lead reaches your CRM as an ordinary form submission when the visitor presses Send. To cap how often the assistant can be asked, the visitor's IP address is counted for an hour. If the visitor presses the microphone, their own browser's speech recognition turns their speech into text, and some browsers run that on their maker's servers.
     46* **A form that sends visitors on with their answers.** If you set a form to send visitors to a web address of your choosing after they submit, and tick the box to add their answers, those answers travel in that address to the page you chose, where that page, its analytics and the visitor's browser history can read them. Off unless you tick it.
    4147* **A daily heartbeat.** Once a day the plugin pings the collector with your account id, your plugin version and your WordPress version, so your MyVitalAssistant dashboard can tell you the install is alive and warn you when something needs attention. On a site running WooCommerce it also sends your WooCommerce version, your store currency, and the name, folder and version number of your active commerce and CRM plugins, so the dashboard can warn you when one of those extensions changes what your order data means. That plugin list is sent only when WooCommerce is present, because that is the only situation the warning applies to. No other plugin list, no post content, no user accounts and no customer records are sent by the heartbeat. It also fetches your own home page from your server once a day to warn you if an old hand pasted tracking tag is still present and double counting.
    4248
    … …  
    6066= What data leaves my site? =
    6167
    62 See the External services section above for the complete list. In short: visitor tracking beacons, form submissions with their attribution, an optional WooCommerce order feed you switch on deliberately, and a daily heartbeat that reports your versions and, on a store, which commerce plugins are active. Nothing else. Order meta beyond an explicit allow list never leaves your server, and the tracking path forwards only its own attribution cookie, never the rest of your visitors' cookies.
     68See the External services section above for the complete list. In short: visitor tracking beacons, form submissions with their attribution (and, on a form you set to ask as a conversation, each message as the visitor sends it), an optional WooCommerce order feed you switch on deliberately, and a daily heartbeat that reports your versions and, on a store, which commerce plugins are active. Nothing else. (The optional InfusedWoo settings download is built on your site and handed to your browser; it is not sent to us.) Order meta beyond an explicit allow list never leaves your server, and the tracking path forwards only its own attribution cookie, never the rest of your visitors' cookies.
    6369
    6470= Does it slow my site down? =
    … …  
    6874= What about GDPR and visitor consent? =
    6975
    70 The plugin tracks visitors on behalf of your business, so the same obligations apply as with any analytics or attribution tool: disclose it in your privacy policy and gather whatever consent your jurisdiction requires. The visitor id is anonymous and the attribution cookie contains no personal information; form submissions carry the personal data your visitor typed, which is sent to your own MyVitalAssistant account.
     76The plugin tracks visitors on behalf of your business, so the same obligations apply as with any analytics or attribution tool: disclose it in your privacy policy and gather whatever consent your jurisdiction requires. The visitor id is anonymous and the attribution cookie contains no personal information; form submissions carry the personal data your visitor typed, which is sent to your own MyVitalAssistant account. A form you set to ask as a conversation also sends what the visitor says to Anthropic's AI model, as described under External services, so name that in your privacy policy too if you use one.
    7177
    7278= What happens when I deactivate or uninstall? =
    7379
    74 Deactivating stops everything immediately: no script tag, no proxy, no captures, no daily ping. Uninstalling also deletes the plugin's stored settings and its capture log. Nothing else was ever stored on your site.
     80Deactivating stops everything immediately: no script tag, no proxy, no captures, no daily ping. Uninstalling also deletes the plugin's stored settings, its capture log and the CRM choices saved on your products. Nothing else was ever stored on your site.
    7581
    7682= Can I use it without WooCommerce? =
    … …  
    7985
    8086== Changelog ==
     87
     88= 1.6.10 =
     89* Settings page: the form capture activity list is tucked under a Troubleshooting heading, and the migration read-out downloads (InfusedWoo and payment plans) now appear only when support turns them on for a site. Nothing about what the plugin sends has changed.
     90
     91= 1.6.9 =
     92* Checkout fields: you can choose, in your MyVitalAssistant account, which checkout details (order meta) are sent with an order so they can be written onto the order in your CRM. Only the fields you choose are sent. The plugin also tells your account the NAMES of the order meta keys it sees, never their values, so you can pick from a list. A passport number or any other checkout detail you do not choose never leaves your site.
     93* Past orders: when your account asks for it (automatically after you save a field choice, or when you press a button there), the plugin sends your past orders again so their checkout details can be written onto the matching CRM orders. It checks hourly. Orders are sent the same way as before, to the same place, and sending one twice never duplicates it.
     94* Trips for a form: with the order sync key, the plugin tells your account the products you have on sale (titles, stock status and categories only) so a form can offer them as a choice and keep the list current by itself.
     95* SUMO Payment Plans read-out: the download now also lists each product's own plan settings (deposit rule and balance date). It is read only, sends nothing, and holds no customer details.
     96
     97= 1.6.8 =
     98* The menu mark is drawn at a fixed size so a theme or another plugin cannot stretch it over the menu label.
     99
     100= 1.6.7 =
     101* The MyVitalAssistant menu item now shows the MyVitalAssistant mark instead of a generic icon.
     102
     103= 1.6.6 =
     104* A "Payment plan details" download on the settings page, shown only where a payment plans plugin is active. It is one file made on your site and handed to your browser, showing how deposits and instalments are stored and a few example bookings. Nothing is sent anywhere and nothing is changed; no customer name, contact detail or user id is included.
     105* The MyVitalAssistant product tab now shows without an order sync key, and accepts a typed numeric id.
     106
     107= 1.6.5 =
     108* A MyVitalAssistant tab on each WooCommerce product and variation, like the Keap tab InfusedWoo adds: choose which product in your CRM a sale of it is (or which subscription plan) and the tags a buyer gets once they have paid. The lists come from your MyVitalAssistant account, so this site never holds a CRM key. Where you have chosen nothing, the fields InfusedWoo saved on the same product are used, and the SKU after that.
     109* The InfusedWoo settings download now also includes InfusedWoo's automation recipes, which the first version missed.
     110
     111= 1.6.4 =
     112* On a site running InfusedWoo, the settings page offers a Download InfusedWoo settings button: one file of the Keap setup InfusedWoo keeps on your products and in its own settings, made on your site and handed to your browser. Nothing is sent anywhere, orders and customers are not included, and passwords, keys, tokens and licence keys are blanked.
     113* MyVitalAssistant is now a menu item of its own in the WordPress admin menu, with an icon, instead of a page under Settings, and the plugin's row of the Plugins screen links to it.
     114
     115= 1.6.3 =
     116* If you switch on Tracking Forms in your MyVitalAssistant account, the tracking script now reads the questions on the forms your pages show (their labels and choices, never what a visitor types) once per page per visitor per day, so you can recreate one in MyVitalAssistant, including forms that load by script. Your /vt/ path now relays that small reader and its report like the rest of the tracking.
     117
     118= 1.6.2 =
     119* The "Refresh this list" link under your tracking forms, and the editor block's "Set up forms" button, now open the plugin's settings page. Both pointed at an address WordPress refused with "Sorry, you are not allowed to access this page."
     120* Tested with WordPress 7.1.
     121* The External services section now describes forms you set to ask as a conversation with an AI assistant, and forms that send visitors on to a web address with their answers.
    81122
    82123= 1.6.1 =
  • myvitalassistant/trunk/uninstall.php

    r3666161 r3845360  
    44 * everything it stored, and this is that promise kept: the settings, the
    55 * stray-tag flag, the capture log, the burst-cap and cached form list
    6  * transients, and the daily schedule. There is nothing else; the plugin creates no tables.
     6 * transients, and the daily schedule. The CRM choices saved on products are removed too. There is nothing else; the plugin creates no tables.
    77 *
    88 * Both prefixes are cleaned on purpose: versions before 1.5.0 stored under
    … …  
    3030delete_transient('myvita_optin_burst');
    3131delete_transient('myvita_forms');
     32delete_transient('myvita_field_keys');
     33delete_option('myvita_resend_seen');
     34wp_unschedule_hook('myvita_resend_check');
     35delete_option('myvita_trips_hash');
     36wp_unschedule_hook('myvita_trips_push');
     37wp_unschedule_hook('myvita_trips_hourly');
     38
     39// The CRM product and tags chosen on products and variations.
     40foreach (['_myvita_crm_type', '_myvita_crm_product', '_myvita_crm_plan', '_myvita_crm_tags'] as $myvita_meta_key) {
     41    delete_post_meta_by_key($myvita_meta_key);
     42}
Note: See TracChangeset for help on using the changeset viewer.