Plugin Directory

Changeset 3834804


Ignore:
Timestamp:
11/30/2026 10:20:35 AM (less than one hour ago)
Author:
uptaingmbh
Message:

Release uptain-connect 2.4.2

Update WordPress and WooCommerce compatibility, add optional Usercentrics consent handling through the existing initial-blocking switch, and provide customer data when orders are created. Enable personal-data and net-sum defaults only on fresh installations; preserve existing shop settings.

Release source: tested Git main commit 3c63dfa7c297485cdebcb0bae9377d44b0f3b7d4.

Location:
uptain-connect
Files:
6 added
13 deleted
8 edited
2 copied
1 moved

Legend:

Unmodified
Added
Removed
  • uptain-connect/tags/2.4.2/readme.txt

    r3834731 r3834804  
    1 === Conversion Optimization with Exit-Intent Popups and Abandoned Shopping Cart Emails ===
    2 Stable tag: 2.4
    3 Donate link: www.uptain.de
    4 License: GPLv2
    5 License URI: http://www.gnu.org/licenses/gpl-2.0.html
     1=== uptain Conversion-Rate Optimierung ===
     2Contributors: uptaingmbh, webfoersterei
     3Tags: woocommerce, conversion, exit-intent, cart recovery, marketing
     4Requires at least: 5.8
     5Tested up to: 7.1
     6Requires PHP: 7.4
     7Stable tag: 2.4.2
     8License: GPL-2.0-or-later
     9License URI: https://www.gnu.org/licenses/gpl-2.0.html
    610
    7 We develop automated state-of-the-art solutions for regaining lost customers coupled with absolute customer orientation.
     11Connect WooCommerce with uptain for personalized exit-intent popups and abandoned-cart recovery.
    812
    913== Description ==
    1014
    11 uptain offers intelligent solutions for the recovery of shopping cart abandonments for online shops in real time and uses the strengths of state-of-the-art data processing, big data benchmarks and automated A/B tests.
     15uptain connects your WooCommerce shop to the uptain service. Enter your uptain ID to make shop, cart and order information available to uptain's conversion tools.
    1216
    13 The uptain plugin is integrated in the website and automatically detects shopping cart abandonments as well as the corresponding reasons for abandonment. The uptain® ALGORITHM generates an individual service message or a personalized dialog box for each abandoner based on the determined data in order to win him back as a customer. With the plugin, the integration of uptain is very quick and easy.
    14 About 70% of your customers abandon their shopping with a filled shopping cart. Use this revenue potential for your online shop.
     17* Exit-intent popups and abandoned-cart recovery through your uptain account.
     18* Cart value, currency, coupon and order information from WooCommerce.
     19* Configurable personal data for known visitors and customers who have placed an order, including guest checkouts, and a net order-value sum.
     20* Classic checkout, Cart and Checkout blocks, and WooCommerce High-Performance Order Storage (HPOS).
    1521
    16 == Solutions ==
     22The plugin is free. An uptain account and an uptain ID are required; the external uptain service is subject to its own commercial terms. See [uptain](https://uptain.de/) for the service and [your integrations page](https://customer.uptain.de/integrations) for your ID.
    1723
    18 **Activation-Popups**
     24= External service and data =
    1925
    20 * uptain recognizes the problem of each and every customer who abandon the shopping cart and provides Activation Popups to support your customers in closing the sale.
    21 * Depending on the website visitor and the reason for abandonment, a distinction is made between individual vouchers, telephone or e-mail service and other communication channels.
    22 * The Activation Popups adapt to your website in terms of colour, font and type of communication.
    23 * The Activation Popups from uptain work on all operating systems and browsers and are designed not to disturb your customers while browsing.
     26When configured and activated according to the consent settings, this plugin loads JavaScript from https://app.uptain.de/js/uptain.js. This connects the visitor's browser to uptain and makes cart value, currency, page type, coupons, order number and order success available to that script. The browser also sends connection metadata, such as its IP address, when contacting the service.
    2427
    25 **Abandonment-Mail**
     28"Include personal data?" and "Include total net sum?" are enabled by default on new installations. Upgrades and reactivation preserve existing choices. When personal data is enabled, an available email from the logged-in account or current WooCommerce checkout session is included before the uptain script starts, even without a previous order. Names and the WordPress customer ID are included as soon as an order is created, without waiting for payment. Unsubmitted checkout drafts do not qualify. Guests receive no account ID; their names and revenue are limited to their own orders recorded in the current WooCommerce session. An entered email alone never grants access to earlier orders. Unavailable fields, such as gender or title, are omitted.
    2629
    27 * based on visitor behaviour, uptain calculates what is the most likely reason for abandonment and automatically sends a suitable service e-mail to the shopping cart abandoner.
    28 * Depending on the website visitor and reason for abandonment, a distinction is made between individual vouchers and automated assistance.
    29 * Each individual Abandonment-Mail is optimized and individualized according to time, address, content, etc.
    30 * With uptain's Abandonment-Mails you can win back your shopping cart abandoners in accordance with the GDPR.
    31 * Our technologies consider the customer journey across the various devices of your end customers - also for guest and new customers.
     30The net-sum option includes product totals from created orders, including unpaid orders, after discounts and itemized refunds, excluding tax, shipping and fees. As in the original integration, payment status does not filter these orders; failed and cancelled orders remain included. This is order value, not confirmed paid revenue. Disabling personal data also disables email and revenue transmission. The plugin reads the visitor's current WooCommerce session through WordPress admin-ajax.php for on-page refreshes. A server-side PHP session keeps a newly placed order available for the confirmation page. Consent settings continue to control when the external script starts.
    3231
    33 **Payment Models**
     32No account, email address or shop URL is sent to the former agency's activation webhook. No external update server is used; updates use the existing WordPress.org entry.
    3433
    35 An uptain ID is required to use the plugin. You will receive this from the service team after you have decided on one of the models.
    36 uptain offers transparent and success-oriented payment models:
     34* [uptain service](https://uptain.de/)
     35* [Terms](https://uptain.de/agb/)
     36* [Privacy policy](https://uptain.de/datenschutz/)
    3737
    38 *Lead*
    39 
    40 * Pay for real contacts only
    41 
    42 *Provision*
    43 
    44 * Pay for additional revenue only
    45 
    46 *Flat-Fee*
    47 
    48 * Pay reliable in budget and planning
    49 
    50 No contract period. No fixed costs. Our most popular model is success-based invoicing via commission. Calculate your individual commission rate using our online calculator:
    51 https://uptain.de/en/pricing/
    52 
    53 You will then receive your personal uptain ID so that you can use the plugin.
    54 If you wish to use one of the other models, simply contact our experts:
    55 https://uptain.de/en/contact/
    56 
    57 == Why uptain? ==
    58 
    59 uptain uses real-time data processing to react quickly and effectively to shopping cart abandonments. This allows you to use the traffic on your website from the very first minute in order to perform better.
    60 
    61 **Conversion Optimization**
    62 
    63 * Increase your conversion rate without great effort by automatically recovering up to 30% of your shopping cart abandoners.
    64 
    65 **More customers- satisfied and sustainable**
    66 
    67 * Take advantage of the potential behind shopping cart abandonment and convert approximately 30% of your shopping cart abandoners into profitable conversions. With our individually customized service-oriented customer communication, you will achieve particularly high response rates and long-term customer loyalty.
    68 
    69 **Up to 10% more revenue**
    70 
    71 * With the help of our solutions you can increase your revenue sustainably by up to 10%.
    72 
    73 **Relief of IT**
    74 
    75 * Our solutions adapt effortlessly to your corporate design - without IT or design knowledge.
     38You are responsible for selecting the appropriate consent settings for your shop. Consent tools are installed and configured separately.
    7639
    7740== Installation ==
    7841
    79 For using uptain-connect an individual uptain-ID is required. Please visit the following website to sign up for a free uptain-ID:
     421. Back up the shop and test the update in staging.
     432. Install and activate WooCommerce, then install or update "uptain-connect". For a ZIP update, use Plugins > Add New > Upload Plugin and replace the existing version.
     443. Open Settings > uptain and enter your uptain ID. Existing IDs and settings are retained when updating.
     454. Configure the consent and personal-data options as required for your shop and clear all page/CDN caches.
     465. Test a fresh visit, cart changes, customer-data settings and a test order.
    8047
    81 [Sign-up](https://www.uptain.de/en/portfolio/woocommerce/) for uptain
     48== Frequently Asked Questions ==
    8249
    83 After you have successfully signed up for a free uptain-ID our service team will contact you immediately to configure the uptain-software based on your specific wishes. Additional costs apply only in case of success on a commission basis.
     50= Do I need a new plugin entry or to reconfigure existing installations? =
     51
     52No. This release retains the uptain-connect folder, wf-uptain-tracking.php filename and existing option keys. It updates the existing plugin.
     53
     54= What should I check with caching? =
     55
     56Do not cache personalized cart/customer data across visitors. Exclude personalized pages from shared page caches and clear cached pages after changing consent settings. Disabling initial data sending suppresses the plugin's initial uptain.readData event; it does not remove tracking data from the page HTML. Ensure visitors can access WordPress admin-ajax.php for on-page refreshes.
    8457
    8558== Changelog ==
     59
     60= 2.4.2 =
     61* Enable personal data and net order value by default for new installations, preserving existing shops' choices.
     62* Include a known visitor's email before SDK startup; include names, customer ID and net order value on order creation without waiting for payment.
     63* Support guest personal data through their own checkout session without looking up other orders by email.
     64* Calculate net product value after discounts and item refunds; clear stale personal attributes on refresh.
     65* Update compatibility metadata for WordPress 7.1 and WooCommerce 11.3.
     66* Support the Store API checkout hook used by Checkout blocks and declare HPOS compatibility.
     67* Keep initial blocking optional and preserve existing settings and plugin identity.
     68* Escape dynamic script values, validate settings and use the correct AJAX URL for subdirectory installations.
     69* Avoid duplicate refresh timers and JavaScript errors when the external script is unavailable.
     70* Handle missing orders safely and retain a new-order marker across cart refreshes until the next page load.
     71* Initialize order sessions before block themes flush page output, preserving delayed order confirmations and avoiding competing checkout sessions.
     72* Remove the former agency's activation webhook, obsolete external updater and their bundled HTTP dependencies.
     73* Preserve credit for the original integration by Timo Förster / webförsterei. Maintenance by uptain GmbH.
    8674
    8775= 2.4.0 =
    … …  
    121109== Upgrade Notice ==
    122110
    123 = 1.1 =
    124 This update allows a quicker integration of the uptain product.
     111= 2.4.2 =
     112Compatibility and customer-data update. Existing settings are preserved. Test installation, checkout and customer-data settings in staging before updating production, and clear page caches.
  • uptain-connect/tags/2.4.2/src/Admin.php

    r3130976 r3834804  
    99
    1010namespace Webfoersterei\Wordpress\Plugin\UptainTracking;
     11
     12defined('ABSPATH') || exit;
    1113
    1214class Admin implements RegistrableWordpressInterface
    … …  
    2527    public const MIN_REFRESH_MS = 5000;
    2628
     29    public static function initializeSettings(): void
     30    {
     31        // Activation only: an upgrade must not opt an existing shop into personal data.
     32        // Empty/false values are saved choices, not missing options.
     33        foreach ([self::OPTION_NAME_TRACKING_ID, self::OPTION_NAME_INCLUDE_PERSONAL_DATA,
     34            self::OPTION_NAME_INCLUDE_NET_WORTH, self::OPTION_NAME_INCLUDE_DEFERRED,
     35            self::OPTION_NAME_DEBUG, self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL,
     36            self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE, self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE,
     37            self::OPTION_NAME_CONSENTMANAGER_VENDORID] as $name) {
     38            if (get_option($name, null) !== null) {
     39                return;
     40            }
     41        }
     42        add_option(self::OPTION_NAME_INCLUDE_PERSONAL_DATA, '1');
     43        add_option(self::OPTION_NAME_INCLUDE_NET_WORTH, '1');
     44    }
     45
    2746    public function registerInWordpress(): void
    2847    {
    … …  
    3352    public function registerSettings()
    3453    {
    35         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_TRACKING_ID);
    36         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_DEFERRED);
    37         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_PERSONAL_DATA);
    38         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_NET_WORTH);
    39         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL);
    40         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE);
    41         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE);
    42         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_CONSENTMANAGER_VENDORID);
    43         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_DEBUG);
     54        foreach ([self::OPTION_NAME_TRACKING_ID, self::OPTION_NAME_CONSENTMANAGER_VENDORID] as $name) {
     55            register_setting(self::OPTIONS_NAMESPACE_SLUG, $name, ['sanitize_callback' => 'sanitize_text_field']);
     56        }
     57        foreach ([self::OPTION_NAME_INCLUDE_DEFERRED, self::OPTION_NAME_INCLUDE_PERSONAL_DATA,
     58            self::OPTION_NAME_INCLUDE_NET_WORTH, self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE,
     59            self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE, self::OPTION_NAME_DEBUG] as $name) {
     60            register_setting(self::OPTIONS_NAMESPACE_SLUG, $name, ['sanitize_callback' => [self::class, 'sanitizeCheckbox']]);
     61        }
     62        register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL,
     63            ['sanitize_callback' => [self::class, 'sanitizeInterval']]);
     64    }
     65
     66    public static function sanitizeCheckbox($value): string
     67    {
     68        return $value === '1' || $value === 1 || $value === true ? '1' : '';
     69    }
     70
     71    public static function sanitizeInterval($value): int
     72    {
     73        return max(self::MIN_REFRESH_MS, min(120000, (int) $value));
    4474    }
    4575
    … …  
    5787    public function renderOptionsPage()
    5888    {
     89        if (!current_user_can('manage_options')) {
     90            return;
     91        }
    5992        ?>
    6093        <style>
    … …  
    106139                <?php printf(
    107140                    '<input type="text" name="%s" value="%s" />',
    108                     self::OPTION_NAME_TRACKING_ID,
     141                    esc_attr(self::OPTION_NAME_TRACKING_ID),
    109142                    esc_attr(get_option(self::OPTION_NAME_TRACKING_ID, ''))
    110143                ); ?>
    … …  
    113146            </div>
    114147            <div class="row">
    115                 <label>Include personal data?</label>
     148                <label for="wf-uptain-personal-data">Include personal data?</label>
    116149                <input type="checkbox" id="wf-uptain-personal-data"
    117                        name="<?php echo self::OPTION_NAME_INCLUDE_PERSONAL_DATA ?>" value="1" <?php checked(
     150                       name="<?php echo esc_attr(self::OPTION_NAME_INCLUDE_PERSONAL_DATA); ?>" value="1" <?php checked(
    118151                    1,
    119152                    get_option(self::OPTION_NAME_INCLUDE_PERSONAL_DATA),
    120153                    true
    121154                ); ?> onchange="if(!this.checked) { document.getElementById('wf-uptain-netsum').checked = false; }"/>
    122                 <small>Personal data (e.g. E-Mail, Name) of the customer is only included if this checkbox is set
    123                     <strong>and</strong> the customer already has at least ordered once in the past (any order status)</small>
     155                <small>If enabled, an available email address is included from the first page load, even before a first
     156                    order. Names and customer ID are included as soon as an order is created, without waiting
     157                    for payment. Guest checkout data is limited to orders from the current
     158                    shop session. Default: enabled for new installations. Consent settings still apply.</small>
    124159            </div>
    125160            <div class="row suboption">
    126                 <label>Include total net sum?</label>
    127                 <input type="checkbox" id="wf-uptain-netsum" name="<?php echo self::OPTION_NAME_INCLUDE_NET_WORTH ?>"
     161                <label for="wf-uptain-netsum">Include total net sum?</label>
     162                <input type="checkbox" id="wf-uptain-netsum" name="<?php echo esc_attr(self::OPTION_NAME_INCLUDE_NET_WORTH); ?>"
    128163                       value="1" <?php checked(
    129164                    1,
    … …  
    132167                ); ?>
    133168                       onchange="if(this.checked) { document.getElementById('wf-uptain-personal-data').checked = true; }"/>
    134                 <small>If personal data is being included also include the customers worth calculated as net sum of all
    135                     their orders</small>
     169                <small>Include the net product value of created orders, including unpaid orders, after discounts and item refunds, excluding
     170                    tax, shipping and fees. Requires personal data to be enabled. For guests, only orders from the
     171                    current shop session are included. Default: enabled for new installations.</small>
    136172            </div>
    137173            <div class="row">
    138174                <label>Block inclusion initially?</label>
    139                 <input type="checkbox" name="<?php echo self::OPTION_NAME_INCLUDE_DEFERRED ?>" value="1" <?php checked(
     175                <input type="checkbox" name="<?php echo esc_attr(self::OPTION_NAME_INCLUDE_DEFERRED); ?>" value="1" <?php checked(
    140176                    1,
    141177                    get_option(self::OPTION_NAME_INCLUDE_DEFERRED),
    142178                    true
    143179                ); ?> />
    144                 <small>If set, initially blocks cookies (and thus uptain) and waits until the JS-function <span
    145                             class="code">uptainEnable();</span> is executed (e.g. by Cookie-Consent-Tool)</small>
     180                <small>If checked, uptain waits for consent to the Usercentrics service "Uptain" and then starts
     181                    automatically. Without Usercentrics, it waits for a manual <span class="code">uptainEnable();</span>
     182                    call. If unchecked, this plugin does not wait for Usercentrics consent.
     183                    Existing Cookiebot and Consentmanager integrations still apply.</small>
    146184            </div>
    147185            <h2>WordPress</h2>
    … …  
    150188                <?php printf(
    151189                    '<input type="text" name="%s" value="%s" />',
    152                     self::OPTION_NAME_CONSENTMANAGER_VENDORID,
     190                    esc_attr(self::OPTION_NAME_CONSENTMANAGER_VENDORID),
    153191                    esc_attr(function_exists('consentmanager_start_cmp') ? get_option(self::OPTION_NAME_CONSENTMANAGER_VENDORID, '') : '')
    154192                ); ?>
    … …  
    156194            <div class="row">
    157195                <label>Debug-Modus:</label>
    158                 <input type="checkbox" name="<?php echo self::OPTION_NAME_DEBUG ?>" value="1" <?php checked(
     196                <input type="checkbox" name="<?php echo esc_attr(self::OPTION_NAME_DEBUG); ?>" value="1" <?php checked(
    159197                    1,
    160198                    get_option(self::OPTION_NAME_DEBUG),
    … …  
    165203            <div class="row <?php echo get_option(self::OPTION_NAME_DEBUG) ? '' : 'hidden' ?>">
    166204                <label>Disable on-page refresh:</label>
    167                 <input type="checkbox" name="<?php echo self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE ?>"
     205                <input type="checkbox" name="<?php echo esc_attr(self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE); ?>"
    168206                       value="1" <?php checked(
    169207                    1,
    … …  
    176214            <div class="row <?php echo get_option(self::OPTION_NAME_DEBUG) ? '' : 'hidden' ?>">
    177215                <label>on-page refresh interval:</label>
    178                 <input type="number" min="<?php echo self::MIN_REFRESH_MS ?>" max="120000"
    179                        name="<?php echo self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL ?>"
     216                <input type="number" min="<?php echo esc_attr(self::MIN_REFRESH_MS); ?>" max="120000"
     217                       name="<?php echo esc_attr(self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL); ?>"
    180218                       value="<?php echo esc_attr(
    181219                           get_option(self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL, self::DEFAULT_REFRESH_MS)
    182220                       ); ?>"/>
    183                 <small>Milliseconds. Do not set below <?php echo self::MIN_REFRESH_MS ?>. Recommended: Between 20000 and
     221                <small>Milliseconds. Do not set below <?php echo esc_attr(self::MIN_REFRESH_MS); ?>. Recommended: Between 20000 and
    184222                    30000. Lower values do have
    185223                    impact on WordPress overall Performance. Use option above to disable</small>
    … …  
    187225            <div class="row <?php echo get_option(self::OPTION_NAME_DEBUG) ? '' : 'hidden' ?>">
    188226                <label>Disable initial data sending:</label>
    189                 <input type="checkbox" name="<?php echo self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE ?>"
     227                <input type="checkbox" name="<?php echo esc_attr(self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE); ?>"
    190228                       value="1" <?php checked(
    191229                    1,
    … …  
    193231                    true
    194232                ); ?> />
    195                 <small>Check to disable data transmission to uptain on full-page-load. See information below when to do
    196                     so</small>
     233                <small>Disables the plugin's initial uptain.readData event after script startup.
     234                    Data already present in the page remains available to the uptain script.</small>
    197235            </div>
    198236            <div class="row <?php echo get_option(self::OPTION_NAME_DEBUG) ? '' : 'hidden' ?>">
    199237                <label>Information:</label>
    200                 <div><p>This plugin uses the WP-REST-API to update values and push them to uptain when no
    201                         full-page-refresh is happening client side. If you disabled WP-Rest-API this will not work.
    202                         Worse, if you added basic authentication in front of your Rest-API, users will be prompted a
    203                         credential window. Disable on-page refresh in those cases.</p>
    204                     <p>This plugin may send wrong information if aggressive server-side-caching is being performed. If
    205                         you encounter such issues you can disable the initial data sending (and should so enable the
    206                         on-page-refresh which is not being cached). Please also clear your cache after changing those
    207                         settings.</p></div>
     238                <div><p>This plugin uses WordPress admin-ajax.php to refresh cart values without a full page load.
     239                        Visitors must be able to access this endpoint. Disable on-page refresh if your server blocks it.</p>
     240                    <p>Exclude pages containing personalized cart or customer data from shared page caches.
     241                        Disabling initial data sending does not remove that data from the HTML.
     242                        Please clear your cache after changing these settings.</p></div>
    208243            </div>
    209244            <?php submit_button(); ?>
  • uptain-connect/tags/2.4.2/src/Plugin.php

    r3130976 r3834804  
    11<?php
    2 
    3 declare(strict_types=1);
    4 
    52/**
    6  * @author Timo Förster <tfoerster@webfoersterei.de>
    7  * @date 15.05.2023
     3 * Consent-aware loader for the existing uptain-connect integration.
     4 * Original integration: Timo Förster / webförsterei, 2023.
     5 * Maintenance: uptain GmbH, 2026. GPL-2.0-or-later.
    86 */
    9 
    107namespace Webfoersterei\Wordpress\Plugin\UptainTracking;
    118
    12 use Webfoersterei\Wordpress\Plugin\UptainTracking\Dependencies\GuzzleHttp\Client;
     9defined('ABSPATH') || exit;
    1310
    1411class Plugin implements RegistrableWordpressInterface
    1512{
    16     private const STATIC_DATA_KEYS = ['page', 'plugin'];
     13    private const JSON_FLAGS = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
    1714    private static string $slug;
    1815    private static string $version;
    1916    private static string $wpAjaxAction;
    20     private ?TrackerInterface $tracker = null;
    2117    public const REST_ROUTE_TRACKING_VALUES = 'values';
    22     private const HOTDEV_HTTP_HEADER_NAME = 'HTTP_X_WEBFOERSTEREI_HOTDEV';
    2318
    24     public function __construct($slug, $version)
     19    public function __construct(string $slug, string $version)
    2520    {
    2621        self::$slug = $slug;
    2722        self::$version = $version;
    28         self::$wpAjaxAction = sprintf('%s_%s', $slug, self::REST_ROUTE_TRACKING_VALUES);
     23        self::$wpAjaxAction = $slug . '_' . self::REST_ROUTE_TRACKING_VALUES;
    2924    }
    3025
    31     public function onActivation(): void
    32     {
    33         try {
    34             $httpClient = new Client();
    35             $httpClient->post('https://hooks.zapier.com/hooks/catch/1548047/3tasect/', [
    36                 'json' => [
    37                     'email' => get_option('admin_email'),
    38                     'url'   => get_home_url(),
    39                 ],
    40             ]);
    41         } catch (\Throwable $ex) {
    42             // Ignore failed home call
    43             return;
    44         }
    45     }
    46 
    47     /**
    48      * @return string
    49      */
    5026    public static function getSlug(): string
    5127    {
    … …  
    5329    }
    5430
    55     private static function getPluginIdentifier()
    56     {
    57         return trim('woocommerce_'.preg_replace('/[^a-z0-9.-]/i', '', self::getVersion()));
    58     }
    59 
    60     private function getTracker(): TrackerInterface
    61     {
    62         if (!$this->tracker) {
    63             $this->tracker = new WooCommerceTracker(); // TODO: Generalize. e.g. Admin-Property
    64         }
    65 
    66         return $this->tracker;
    67     }
    68 
    69     /**
    70      * @return string
    71      */
    7231    public static function getVersion(): string
    7332    {
    7433        return self::$version;
    7534    }
    76 
    77     public function sendAjaxTrackingData() {
    78         wp_send_json($this->formatAsJsonArray($this->getTrackingData(), true));
    79     }
     35    private const STATIC_DATA_KEYS = ['page', 'plugin'];
    8036
    8137    public function registerInWordpress(): void
    8238    {
    83         add_action('wp_footer', [&$this, 'injectJsDataSnippet']);
    84         add_action('wp_ajax_'.self::$wpAjaxAction, [&$this, 'sendAjaxTrackingData']);
    85         add_action('wp_ajax_nopriv_'.self::$wpAjaxAction, [&$this, 'sendAjaxTrackingData']);
     39        (new Admin())->registerInWordpress();
     40        (new WooCommerceTracker())->registerInWordpress();
     41        add_action('wp_footer', [$this, 'injectJsDataSnippet']);
     42        add_action('wp_ajax_' . self::$wpAjaxAction, [$this, 'sendAjaxTrackingData']);
     43        add_action('wp_ajax_nopriv_' . self::$wpAjaxAction, [$this, 'sendAjaxTrackingData']);
     44    }
    8645
    87         foreach (array_merge(glob(__DIR__.'/*.php')) as $potentialPhpClassFilePath) {
    88             [$className] = explode('.', basename($potentialPhpClassFilePath));
    89             $className = __NAMESPACE__.'\\'.$className;
    90             $interfaces = class_implements($className);
     46    public function sendAjaxTrackingData(): void
     47    {
     48        // Read-only response for the visitor's own WooCommerce session; no supplied IDs.
     49        wp_send_json($this->trackingData(true));
     50    }
    9151
    92             if (isset($interfaces[RegistrableWordpressInterface::class]) && $className !== __CLASS__) {
    93                 (new $className())->registerInWordpress();
     52    private function trackingData(bool $refresh = false): array
     53    {
     54        $data = (new WooCommerceTracker())->getCurrentTrackingData();
     55        $data['plugin'] = 'woocommerce_' . self::getVersion();
     56        $result = [];
     57        foreach ($data as $key => $value) {
     58            if ($refresh && in_array($key, self::STATIC_DATA_KEYS, true)) {
     59                continue;
    9460            }
     61            $result[] = [
     62                'key' => preg_replace('/[^a-z0-9]/i', '', strtolower($key)),
     63                'value' => trim(wp_strip_all_tags((string) $value)),
     64            ];
     65        }
     66        return $result;
     67    }
     68
     69    public function injectJsDataSnippet(): void
     70    {
     71        $id = trim((string) get_option(Admin::OPTION_NAME_TRACKING_ID, ''));
     72        if ($id === '' || !function_exists('WC')) {
     73            return;
     74        }
     75        $vendor = trim((string) get_option(Admin::OPTION_NAME_CONSENTMANAGER_VENDORID, ''));
     76        $attributes = ['data-no-minify' => '1', 'type' => 'text/javascript'];
     77        $cookiebot = function_exists('\cybot\cookiebot\lib\cookiebot_active')
     78            ? \cybot\cookiebot\lib\cookiebot_active()
     79            : (function_exists('cookiebot_active') && cookiebot_active());
     80        $blockInitially = (bool) get_option(Admin::OPTION_NAME_INCLUDE_DEFERRED, false);
     81        $usercentricsBlocking = $blockInitially && !$cookiebot;
     82        if ($cookiebot) {
     83            $attributes['type'] = 'text/plain';
     84            $attributes['data-cookieconsent'] = 'marketing';
     85        } elseif ($usercentricsBlocking) {
     86            $attributes['type'] = 'text/plain';
     87            $attributes['data-usercentrics'] = 'Uptain';
     88            $attributes['data-uptain-auto-consent'] = '1';
     89        }
     90        if ($vendor !== '') {
     91            $attributes['data-cmp-ab'] = '2';
     92        }
     93
     94        $url = wp_json_encode('https://app.uptain.de/js/uptain.js?x=' . rawurlencode($id), self::JSON_FLAGS);
     95        try {
     96            $data = wp_json_encode($this->trackingData(), self::JSON_FLAGS);
     97        } catch (\Throwable $error) {
     98            // Preserve the original fail-soft behavior if a shop extension cannot supply tracking data.
     99            self::debug('tracking-error', $error->getMessage());
     100            return;
     101        }
     102        $initial = wp_json_encode(!get_option(Admin::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE, false));
     103        $refresh = wp_json_encode(!get_option(Admin::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE, false));
     104        $interval = Admin::sanitizeInterval(get_option(Admin::OPTION_NAME_INCLUDE_REFRESH_INTERVAL, Admin::DEFAULT_REFRESH_MS));
     105        $ajaxUrl = wp_json_encode(admin_url('admin-ajax.php'), self::JSON_FLAGS);
     106        $ajaxBody = wp_json_encode('action=' . self::$wpAjaxAction, self::JSON_FLAGS);
     107
     108        // WordPress escapes attributes; all dynamic JavaScript strings are JSON encoded with HEX flags.
     109        wp_print_inline_script_tag(strtr(file_get_contents(__DIR__ . '/uptain-loader.js'), [
     110            'UPTAIN_URL' => $url, 'UPTAIN_DATA' => $data, 'UPTAIN_INITIAL' => $initial, 'UPTAIN_REFRESH' => $refresh, 'UPTAIN_INTERVAL' => $interval
     111        ]), array_merge($attributes, ['id' => self::getSlug() . '-pre-consent']));
     112
     113        wp_print_inline_script_tag(strtr(file_get_contents(__DIR__ . '/uptain-refresh.js'), [
     114            'UPTAIN_AJAX_URL' => $ajaxUrl, 'UPTAIN_AJAX_BODY' => $ajaxBody
     115        ]), array_merge($attributes, ['id' => self::getSlug() . '-refresh']));
     116
     117        if (!$blockInitially || $usercentricsBlocking) {
     118            $execute = 'uptainEnable();';
     119            if ($vendor !== '' && !$usercentricsBlocking) {
     120                $vendorJson = wp_json_encode($vendor, self::JSON_FLAGS);
     121                $execute = 'if (typeof __cmp === "function") { __cmp("addEventListener", ["consent", function() {'
     122                    . 'var data = __cmp("getCMPData"); if (data && data.vendorConsents && data.vendorConsents[' . $vendorJson . ']) uptainEnable();'
     123                    . '}, false], null); }';
     124            }
     125            $startAttributes = ['id' => self::getSlug() . '-direct-execute'];
     126            if ($usercentricsBlocking) {
     127                $startAttributes['data-uptain-consent-start'] = '1';
     128            }
     129            wp_print_inline_script_tag($execute, array_merge($attributes, $startAttributes));
     130        }
     131        if ($usercentricsBlocking) {
     132            wp_print_inline_script_tag(file_get_contents(__DIR__ . '/consent-bootstrap.js'), [
     133                'id' => self::getSlug() . '-consent-bootstrap',
     134                'data-no-minify' => '1',
     135                'data-cmp-ab' => '2',
     136                'data-cookieconsent' => 'ignore',
     137            ]);
    95138        }
    96139    }
    97140
    98     public function injectJsDataSnippet()
     141    public static function debug($name, $value): void
    99142    {
    100         Plugin::debug('version', self::getVersion());
    101         if (!$this->isEnabled()) {
    102             Plugin::debug('enabled', false);
    103 
    104             return;
    105         }
    106         Plugin::debug('enabled', true);
    107 
    108         if (function_exists('\cybot\cookiebot\lib\cookiebot_active')) {
    109             Plugin::debug('-cookiebot-exists', 'namespaced');
    110             $cookieBotEnabled = \cybot\cookiebot\lib\cookiebot_active();
    111         } else {
    112             Plugin::debug('cookiebot-exists', 'legacy');
    113             $cookieBotEnabled = function_exists('cookiebot_active') && cookiebot_active();
    114         }
    115 
    116         Plugin::debug('cookiebot-enabled', $cookieBotEnabled);
    117         Plugin::debug('consentmanager-enabled', function_exists('consentmanager_start_cmp'));
    118 
    119         if ($cookieBotEnabled) {
    120             $scriptType = (function_exists('\cybot\cookiebot\lib\cookiebot_assist') ?
    121                 \cybot\cookiebot\lib\cookiebot_assist('marketing')
    122                 : cookiebot_assist('marketing'));
    123         } else {
    124             $scriptType = 'type="application/javascript"';
    125         }
    126 
    127         $scriptTagGeneralAmend = '';
    128         $scriptTagImmediateAmend = '';
    129         $consentManagerVendorId = trim((string)get_option(Admin::OPTION_NAME_CONSENTMANAGER_VENDORID, ''));
    130         $scriptImmediateEventEmitter = 'uptainEnable();';
    131 
    132         if ($consentManagerVendorId) {
    133             $scriptTagGeneralAmend = 'data-cmp-ab="2"';
    134             // $scriptTagImmediateAmend = sprintf('class="cmplazyload" data-cmp-vendor="%s"', $consentManagerVendorId);
    135 
    136             $scriptImmediateEventEmitter = sprintf('__cmp("addEventListener",["consent",function() {
    137                                 if(__cmp("getCMPData").vendorConsents && __cmp("getCMPData").vendorConsents["%s"]) {
    138                                 uptainEnable();
    139                                 }
    140                                 },false],null);', $consentManagerVendorId);
    141 
    142             Plugin::debug('consentmanager-vendorid', $consentManagerVendorId);
    143         }
    144 
    145         try {
    146             printf(
    147                 '<script data-no-minify="1" id="%1$s" %7$s %8$s>
    148             function uptainEnable(retry = 0) {
    149                 var maxRetry = 10;
    150                 var retryInterval = 500;
    151                 var uptainTag = document.getElementById("__up_data_qp");
    152                
    153                 if (!uptainTag) {
    154                     uptainTag = document.createElement("script");
    155                     uptainTag.setAttribute("src", "https://app.uptain.de/js/uptain.js?x=%2$s");
    156                     uptainTag.setAttribute("id", "__up_data_qp");
    157                     uptainTag.setAttribute("defer", "");
    158                     uptainTag.setAttribute("async", "");
    159                     document.head.appendChild(uptainTag);
    160                 }
    161                
    162                 var data = %3$s;
    163                
    164                 for (var i = 0; i < data.length; i++) {
    165                     var elem = data[i];
    166                     uptainTag.setAttribute("data-"+elem.key, elem.value);
    167                 }
    168                 uptainTag.setAttribute("data-x-retry", retry);
    169                
    170                 if(typeof window._upEventBus === "undefined" && retry <= maxRetry) {
    171                     setTimeout(function() { uptainEnable(++retry); }, retryInterval * retry);
    172                     return;
    173                 }
    174 
    175                 if(%4$s) { window._upEventBus.publish("uptain.readData"); }
    176                 if(%5$s) { setInterval(uptainRefresh, %6$d); }
    177                 if((%4$s || %5$s) && document.getElementById("%1$s")) { document.getElementById("%1$s").remove(); }
    178             }
    179         </script>',
    180                 self::getSlug().'-pre-consent',
    181                 $this->getUptainTrackingId(),
    182                 json_encode(
    183                     $this->formatAsJsonArray($this->getTrackingData()),
    184                     JSON_THROW_ON_ERROR
    185                 ),
    186                 json_encode(!get_option(Admin::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE, false)),
    187                 json_encode(!get_option(Admin::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE, false)),
    188                 max(
    189                     (int)get_option(Admin::OPTION_NAME_INCLUDE_REFRESH_INTERVAL, Admin::DEFAULT_REFRESH_MS),
    190                     Admin::MIN_REFRESH_MS
    191                 ),
    192                 $scriptType,
    193                 $scriptTagGeneralAmend
    194             );
    195             printf(
    196                 '<script data-no-minify="1" id="%1$s" %3$s %4$s>
    197             var lastSetKeys = [];
    198             async function uptainRefresh() {
    199                 console.log("uptainRefresh");
    200                 var uptainTag = document.getElementById("__up_data_qp");
    201                
    202                 if (!uptainTag) {
    203                     return;
    204                 }
    205                 if (uptainTag.getAttribute("data-success")) {
    206                     console.log("Successful order will not be updated");
    207                     return;
    208                 }
    209                
    210                 var response = await fetch("/wp-admin/admin-ajax.php", { method: "POST",
    211                     headers: {
    212                       "Content-Type": "application/x-www-form-urlencoded",
    213                     },
    214                     body: "action=%5$s"}
    215                 );
    216                 var data = await response.json();
    217                
    218                 for (var i = 0; i < lastSetKeys.length; i++) {
    219                     uptainTag.removeAttribute("data-"+lastSetKeys[i]);
    220                 }
    221                
    222                 lastSetKeys = [];
    223 
    224                 for (var i = 0; i < data.length; i++) {
    225                     var elem = data[i];
    226                     uptainTag.setAttribute("data-"+elem.key, elem.value);
    227                     lastSetKeys.push(elem.key);
    228                 }
    229 
    230                 window._upEventBus.publish("uptain.readData");
    231             }
    232         </script>',
    233                 self::getSlug().'-refresh',
    234                 get_rest_url(null, self::getSlug().'/v1/'.self::REST_ROUTE_TRACKING_VALUES),
    235                 $scriptType,
    236                 $scriptTagGeneralAmend,
    237                 self::$wpAjaxAction
    238             );
    239         } catch (\Throwable $ex) {
    240             Plugin::debug('Error: ', $ex->getMessage());
    241 
    242             return;
    243         }
    244 
    245         if ($this->immediateInclude()) {
    246             Plugin::debug('immediate-include', true);
    247             printf(
    248                 '<script data-no-minify="1" id="%1$s" %2$s>
    249                                 %3$s
    250                                 </script>',
    251                 self::getSlug().'-direct-execute',
    252                 $scriptType,
    253                 $scriptImmediateEventEmitter
    254             );
    255         }
    256     }
    257 
    258     private function getTrackingData()
    259     {
    260         return array_merge($this->getTracker()->getCurrentTrackingData(), ['plugin' => self::getPluginIdentifier()]);
    261     }
    262 
    263     private function formatAsJsonArray(array $array, bool $deleteStaticKeys = false): array
    264     {
    265         return array_values(array_filter(
    266             array_map(
    267                 fn($key, $value) => [
    268                     'key'   => $this->getHtmlKey($key),
    269                     'value' => $this->getHtmlValue($value),
    270                 ],
    271                 array_keys($array),
    272                 array_values($array)
    273             ),
    274             static fn($element) => !$deleteStaticKeys || !in_array(
    275                     strtolower($element['key']),
    276                     self::STATIC_DATA_KEYS,
    277                     true
    278                 )
    279         ));
    280     }
    281 
    282     private function getHtmlValue($value)
    283     {
    284         $value = strip_tags((string)$value);
    285         if (is_scalar($value)) {
    286             return trim($value);
    287         }
    288 
    289         return json_encode($value);
    290     }
    291 
    292     private function getHtmlKey(string $key)
    293     {
    294         return trim(preg_replace('/[^a-z0-9]/i', '', strtolower(strip_tags($key))));
    295     }
    296 
    297     private function isEnabled()
    298     {
    299         return !empty(trim(str_replace('X', 'X', $this->getUptainTrackingId() ?: '')));
    300     }
    301 
    302     private function getUptainTrackingId()
    303     {
    304         return \get_option(Admin::OPTION_NAME_TRACKING_ID, '');
    305     }
    306 
    307     private function immediateInclude(): bool
    308     {
    309         return !\get_option(Admin::OPTION_NAME_INCLUDE_DEFERRED);
    310     }
    311 
    312     public static function debug($header, $value)
    313     {
    314         $isHotDev = isset($_SERVER[self::HOTDEV_HTTP_HEADER_NAME]) && ((int)$_SERVER[self::HOTDEV_HTTP_HEADER_NAME] >= 1024 && (int)$_SERVER[self::HOTDEV_HTTP_HEADER_NAME] <= 65534);
    315 
    316         if (!$isHotDev && !get_option(Admin::OPTION_NAME_DEBUG, false)) {
    317             return;
    318         }
    319         $value = var_export($value, true);
    320 
    321         if (!headers_sent()) {
    322             if (strpos($value, "\n")) {
    323                 $value = base64_encode($value);
    324             }
    325             header(sprintf("x-wf-uptain-%s: %s", strtolower($header), $value));
    326 
    327             return;
    328         }
    329 
    330         if ($isHotDev) {
    331             printf("DEBUG %s: %s", $header, $value);
     143        if (get_option(Admin::OPTION_NAME_DEBUG, false) && !headers_sent()) {
     144            $header = preg_replace('/[^a-z0-9-]/i', '', (string) $name);
     145            header('X-Wf-Uptain-' . $header . ': ' . rawurlencode(wp_json_encode($value)));
    332146        }
    333147    }
  • uptain-connect/tags/2.4.2/src/WooCommerceTracker.php

    r3102401 r3834804  
    1010namespace Webfoersterei\Wordpress\Plugin\UptainTracking;
    1111
     12defined('ABSPATH') || exit;
     13
    1214class WooCommerceTracker implements TrackerInterface, RegistrableWordpressInterface
    1315{
     16    private const GUEST_ORDERS_SESSION_KEY = 'uptain_guest_orders';
    1417    private $WC;
    1518    private static $overrideOrderId = null;
    … …  
    4649    public function registerInWordpress(): void
    4750    {
    48         add_action('woocommerce_checkout_order_created', function ($order) {
    49             Plugin::debug('wc-hook-order-created', true);
    50             Plugin::debug('wc-hook-order-created-id', $order->get_id());
    51             if (!headers_sent() && session_status() !== PHP_SESSION_ACTIVE) {
    52                 session_start();
    53             }
    54             $_SESSION['freshOrder'] = $order->get_id();
    55             self::$overrideOrderId = $order->get_id();
    56         });
     51        add_action('template_redirect', [$this, 'prepareOrderSession'], 0);
     52        add_action('woocommerce_checkout_order_created', [$this, 'rememberOrder']);
     53        // The block checkout uses the Store API instead of the classic checkout hook.
     54        add_action('woocommerce_store_api_checkout_order_processed', [$this, 'rememberOrder']);
    5755
    5856        add_action('woocommerce_thankyou', function ($orderID) {
    … …  
    6260            }
    6361            $order = wc_get_order($orderID);
     62            if (!$order) {
     63                return;
     64            }
    6465            Plugin::debug(
    6566                'wc-hook-thankyou-created-ts',
    … …  
    7980    }
    8081
     82    public function prepareOrderSession(): void
     83    {
     84        // The original integration starts this session in the footer. Block themes
     85        // can flush headers earlier, leaving concurrent checkout/refresh requests
     86        // to create different sessions. Establish it before any frontend output.
     87        if (function_exists('WC') && get_option(Admin::OPTION_NAME_TRACKING_ID, '')
     88            && !headers_sent()
     89            && session_status() !== PHP_SESSION_ACTIVE) {
     90            session_start();
     91        }
     92    }
     93
     94    public function rememberOrder($order): void
     95    {
     96        if (!$order instanceof \WC_Order) {
     97            return;
     98        }
     99        if (!headers_sent() && session_status() !== PHP_SESSION_ACTIVE) {
     100            session_start();
     101        }
     102        $_SESSION['freshOrder'] = $order->get_id();
     103        self::$overrideOrderId = $order->get_id();
     104        // Only the server-side checkout hooks may associate an order with a guest.
     105        // An email address or an order ID supplied in a URL is not proof of ownership.
     106        if (!is_user_logged_in() && !$order->get_customer_id() && WC()->session
     107            && get_option(Admin::OPTION_NAME_INCLUDE_PERSONAL_DATA, false)) {
     108            $orders = (array) WC()->session->get(self::GUEST_ORDERS_SESSION_KEY, []);
     109            $orders[$order->get_id()] = $order->get_order_key();
     110            WC()->session->set(self::GUEST_ORDERS_SESSION_KEY, $orders);
     111        }
     112    }
     113
    81114    public function getCurrentTrackingData(): array
    82115    {
    … …  
    96129
    97130        Plugin::debug('override-orderid', self::$overrideOrderId);
    98         Plugin::debug('session-orderid', $_SESSION['freshOrder'] ?? null);
     131        Plugin::debug('session-orderid', absint($_SESSION['freshOrder'] ?? 0));
    99132
    100133        if (null === self::$overrideOrderId && isset($_SESSION['freshOrder']) && (int)$_SESSION['freshOrder']) {
    101             self::$overrideOrderId = $_SESSION['freshOrder'];
    102             $_SESSION['freshOrder'] = null;
     134            self::$overrideOrderId = absint($_SESSION['freshOrder']);
     135        }
     136        // A cart refresh on the checkout page must not consume the order before
     137        // the visitor reaches the confirmation page (possibly after a payment redirect).
     138        if (self::$overrideOrderId && !wp_doing_ajax()) {
     139            unset($_SESSION['freshOrder']);
    103140        }
    104141
    … …  
    142179    public function getPersonalData(): array
    143180    {
    144         $currentUser = \wp_get_current_user();
    145 
     181        if (!get_option(Admin::OPTION_NAME_INCLUDE_PERSONAL_DATA, false) || !$this->getWooCommerce()) {
     182            return [];
     183        }
     184
     185        $currentUser = wp_get_current_user();
     186        $includeRevenue = (bool) get_option(Admin::OPTION_NAME_INCLUDE_NET_WORTH, false);
     187        $orders = [];
     188        if ($currentUser->ID) {
     189            $email = $currentUser->user_email;
     190            // Never query by an unverified billing email: it could expose another customer's history.
     191            // Checkout blocks can create a draft before the visitor submits an order.
     192            $createdStatuses = array_values(array_diff(array_keys(wc_get_order_statuses()), ['wc-checkout-draft']));
     193            if ($createdStatuses) {
     194                $orders = wc_get_orders([
     195                    'customer_id' => $currentUser->ID, 'status' => $createdStatuses,
     196                    'limit' => $includeRevenue ? -1 : 1, 'orderby' => 'date', 'order' => 'DESC',
     197                ]);
     198            }
     199        } else {
     200            $email = $this->WC->customer ? $this->WC->customer->get_billing_email() : '';
     201            $sessionOrders = $this->getGuestOrders();
     202            if (!$email && $sessionOrders) {
     203                $email = $sessionOrders[0]->get_billing_email();
     204            }
     205            foreach ($sessionOrders as $order) {
     206                if ($email && strcasecmp($email, $order->get_billing_email()) === 0 && !$order->has_status('checkout-draft')) {
     207                    $orders[] = $order;
     208                }
     209            }
     210        }
     211
     212        // The SDK sees these attributes before it executes, including on session start.
     213        // Email is the only personal field allowed before the first order is created.
     214        $result = $email ? ['email' => $email] : [];
     215        if (!$orders) {
     216            return $result;
     217        }
     218        $order = $orders[0];
     219        $result['firstname'] = $currentUser->ID && $currentUser->user_firstname
     220            ? $currentUser->user_firstname : $order->get_billing_first_name();
     221        $result['lastname'] = $currentUser->ID && $currentUser->user_lastname
     222            ? $currentUser->user_lastname : $order->get_billing_last_name();
     223        if ($currentUser->ID) {
     224            $result['uid'] = $currentUser->ID;
     225        }
     226        // WooCommerce has no standard gender, title or customer-group field. Do not infer them.
     227        if ($includeRevenue) {
     228            $net = 0.0;
     229            foreach ($orders as $customerOrder) {
     230                foreach ($customerOrder->get_items('line_item') as $itemId => $item) {
     231                    $net += max(0, (float) $item->get_total() - $customerOrder->get_total_refunded_for_item($itemId));
     232                }
     233            }
     234            $result['revenue'] = number_format($net, 2, '.', '');
     235        }
     236        return $result;
     237    }
     238
     239    private function getGuestOrders(): array
     240    {
    146241        $result = [];
    147 
    148         Plugin::debug('user-id', $currentUser->ID);
    149 
    150         if ($this->shouldIncludePersonalData($currentUser)) {
    151             Plugin::debug('will-include-personal-data', 'yes');
    152             $result['email'] = $currentUser->user_email;
    153             $nameParts = explode(' ', $currentUser->display_name);
    154             $firstname = array_pop($nameParts);
    155             $result['firstname'] = $currentUser->user_firstname ?: ($firstname ?? '');
    156             $result['lastname'] = $currentUser->user_lastname ?: implode(' ', $nameParts);
    157             // $result['gender'] = ''; // Call 2.6. mit hn: Weglassen
    158             // $result['customergroup'] = ''; // Call 2.6. mit hn: Weglassen oder filtern aus beliebten Plugins. WooCommerce Groups sind eher Memberships für Subscriptions. Daher weggelassen. https://woocommerce.com/document/groups-woocommerce/
    159             $result['uid'] = $currentUser->ID;
    160 
    161             if (get_option(Admin::OPTION_NAME_INCLUDE_NET_WORTH, false)) {
    162                 Plugin::debug('will-include-net-worth', 'yes');
    163                 $orders = wc_get_orders(['customer' => $currentUser->ID, 'limit' => -1]);
    164                 $subtotals = array_map(fn($order) => $order->get_subtotal(), $orders);
    165                 $result['revenue'] = array_sum($subtotals);
    166             }
    167         }
    168 
     242        $remembered = $this->WC->session ? $this->WC->session->get(self::GUEST_ORDERS_SESSION_KEY, []) : [];
     243        foreach (array_reverse((array) $remembered, true) as $id => $key) {
     244            $order = wc_get_order(absint($id));
     245            if ($order instanceof \WC_Order && !$order->get_customer_id() && is_string($key) && $key !== ''
     246                && hash_equals($order->get_order_key(), $key)) {
     247                $result[] = $order;
     248            }
     249        }
    169250        return $result;
    170     }
    171 
    172     private function shouldIncludePersonalData($currentUser): bool
    173     {
    174         if (!$currentUser || !$currentUser->ID || !get_option(Admin::OPTION_NAME_INCLUDE_PERSONAL_DATA, false)) {
    175             Plugin::debug('will-include-personal-data', 'no-user-or-no-setting');
    176 
    177             return false;
    178         }
    179 
    180         if (!$this->getWooCommerce()) {
    181             return false;
    182         }
    183 
    184         $completedOrders = wc_get_orders(['customer' => $currentUser->ID, 'limit' => 1]);
    185 
    186         return count($completedOrders) >= 1;
    187251    }
    188252
  • uptain-connect/tags/2.4.2/wf-uptain-tracking.php

    r3130976 r3834804  
    11<?php
     2/**
     3 * Plugin Name:       uptain Conversion-Rate Optimierung
     4 * Plugin URI:        https://wordpress.org/plugins/uptain-connect/
     5 * Description:       Connects WooCommerce with uptain for exit-intent popups and abandoned-cart recovery.
     6 * Version:           2.4.2
     7 * Requires at least: 5.8
     8 * Requires PHP:      7.4
     9 * Requires Plugins:  woocommerce
     10 * WC tested up to:   11.3.0
     11 * Author:            uptain GmbH
     12 * Author URI:        https://uptain.de/
     13 * License:           GPL-2.0-or-later
     14 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
     15 * Text Domain:       uptain-connect
     16 *
     17 * Original integration by Timo Förster / webförsterei, 2023.
     18 * Maintained by uptain GmbH, 2026.
     19 */
    220
    321declare(strict_types=1);
    422
    5 use Webfoersterei\Wordpress\Plugin\UptainTracking\Dependencies\GuzzleHttp\Client;
    6 use Webfoersterei\Wordpress\Plugin\UptainTracking\Dependencies\Psr\Http\Client\ClientExceptionInterface;
    723use Webfoersterei\Wordpress\Plugin\UptainTracking\Plugin;
    824
    9 require_once __DIR__.'/vendor/autoload.php';
     25defined('ABSPATH') || exit;
    1026
    11 /**
    12  * Plugin Name:       uptain Conversion-Rate Optimierung
    13  * Description:       Wir entwickeln automatisierte Lösungen zur Rückgewinnung von Kaufabbrechern nach dem neuesten Stand der Technik – gepaart mit absoluter Kundenorientierung.
    14  * Requires at least: 5.8
    15  * Version:           2.4.1
    16  * Requires PHP:      7.4
    17  * Tested up to:      6.6
    18  * Tags:              E-Commerce, Conversion-Optimierung, Exit-Intent, Warenkorb, Shop, Conversion, E-Mail, Big Data, DSGVO, Kundengewinnung, Marketing, Optimierung
    19  * Author:            uptain GmbH
    20  * Author URI:        https://www.uptain.de/
    21  * Contributors:      webfoersterei
    22  */
     27// Preserve the original filename, namespace and option keys for existing installations.
     28require_once __DIR__ . '/src/RegistrableWordpressInterface.php';
     29require_once __DIR__ . '/src/TrackerInterface.php';
     30require_once __DIR__ . '/src/Admin.php';
     31require_once __DIR__ . '/src/WooCommerceTracker.php';
     32require_once __DIR__ . '/src/Plugin.php';
    2333
    24 $slug = 'wf-uptain-tracking';
    25 $plugin = new Plugin(strpos($slug, '$') !== false ? 'plugin' : $slug, '2.4.1');
    26 $plugin->registerInWordpress();
     34register_activation_hook(__FILE__, [\Webfoersterei\Wordpress\Plugin\UptainTracking\Admin::class, 'initializeSettings']);
    2735
    28 register_activation_hook(__FILE__, [&$plugin, 'onActivation']);
     36(new Plugin('wf-uptain-tracking', '2.4.2'))->registerInWordpress();
    2937
    30 if (!function_exists('wf_plugin_update_handler')) {
    31     add_filter('update_plugins_updates.webfoersterei.de', 'wf_plugin_update_handler', 10, 4);
    32     function wf_plugin_update_handler($updateInfo, $pluginHeaders, $pluginFile, $language)
    33     {
    34         $pluginSlug = dirname($pluginFile);
    35 
    36         $checkUri = $pluginHeaders['UpdateURI'].sprintf('/%s', $pluginSlug);
    37 
    38         try {
    39             $client = new Client();
    40             $response = $client->get($checkUri, [
    41                 'query' => ['version' => $pluginHeaders['Version']],
    42             ]);
    43 
    44             return json_decode($response->getBody()->getContents(), true);
    45         } catch (Exception $exception) {
    46             return $updateInfo;
    47         }
     38add_action('before_woocommerce_init', static function () {
     39    if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
     40        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
     41        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
    4842    }
    49 }
     43});
  • uptain-connect/trunk/readme.txt

    r3834802 r3834804  
    1 === Conversion Optimization with Exit-Intent Popups and Abandoned Shopping Cart Emails ===
    2 Stable tag: 2.4
    3 Donate link: www.uptain.de
    4 License: GPLv2
    5 License URI: http://www.gnu.org/licenses/gpl-2.0.html
     1=== uptain Conversion-Rate Optimierung ===
     2Contributors: uptaingmbh, webfoersterei
     3Tags: woocommerce, conversion, exit-intent, cart recovery, marketing
     4Requires at least: 5.8
     5Tested up to: 7.1
     6Requires PHP: 7.4
     7Stable tag: 2.4.2
     8License: GPL-2.0-or-later
     9License URI: https://www.gnu.org/licenses/gpl-2.0.html
    610
    7 We develop automated state-of-the-art solutions for regaining lost customers coupled with absolute customer orientation.
     11Connect WooCommerce with uptain for personalized exit-intent popups and abandoned-cart recovery.
    812
    913== Description ==
    1014
    11 uptain offers intelligent solutions for the recovery of shopping cart abandonments for online shops in real time and uses the strengths of state-of-the-art data processing, big data benchmarks and automated A/B tests.
     15uptain connects your WooCommerce shop to the uptain service. Enter your uptain ID to make shop, cart and order information available to uptain's conversion tools.
    1216
    13 The uptain plugin is integrated in the website and automatically detects shopping cart abandonments as well as the corresponding reasons for abandonment. The uptain® ALGORITHM generates an individual service message or a personalized dialog box for each abandoner based on the determined data in order to win him back as a customer. With the plugin, the integration of uptain is very quick and easy.
    14 About 70% of your customers abandon their shopping with a filled shopping cart. Use this revenue potential for your online shop.
     17* Exit-intent popups and abandoned-cart recovery through your uptain account.
     18* Cart value, currency, coupon and order information from WooCommerce.
     19* Configurable personal data for known visitors and customers who have placed an order, including guest checkouts, and a net order-value sum.
     20* Classic checkout, Cart and Checkout blocks, and WooCommerce High-Performance Order Storage (HPOS).
    1521
    16 == Solutions ==
     22The plugin is free. An uptain account and an uptain ID are required; the external uptain service is subject to its own commercial terms. See [uptain](https://uptain.de/) for the service and [your integrations page](https://customer.uptain.de/integrations) for your ID.
    1723
    18 **Activation-Popups**
     24= External service and data =
    1925
    20 * uptain recognizes the problem of each and every customer who abandon the shopping cart and provides Activation Popups to support your customers in closing the sale.
    21 * Depending on the website visitor and the reason for abandonment, a distinction is made between individual vouchers, telephone or e-mail service and other communication channels.
    22 * The Activation Popups adapt to your website in terms of colour, font and type of communication.
    23 * The Activation Popups from uptain work on all operating systems and browsers and are designed not to disturb your customers while browsing.
     26When configured and activated according to the consent settings, this plugin loads JavaScript from https://app.uptain.de/js/uptain.js. This connects the visitor's browser to uptain and makes cart value, currency, page type, coupons, order number and order success available to that script. The browser also sends connection metadata, such as its IP address, when contacting the service.
    2427
    25 **Abandonment-Mail**
     28"Include personal data?" and "Include total net sum?" are enabled by default on new installations. Upgrades and reactivation preserve existing choices. When personal data is enabled, an available email from the logged-in account or current WooCommerce checkout session is included before the uptain script starts, even without a previous order. Names and the WordPress customer ID are included as soon as an order is created, without waiting for payment. Unsubmitted checkout drafts do not qualify. Guests receive no account ID; their names and revenue are limited to their own orders recorded in the current WooCommerce session. An entered email alone never grants access to earlier orders. Unavailable fields, such as gender or title, are omitted.
    2629
    27 * based on visitor behaviour, uptain calculates what is the most likely reason for abandonment and automatically sends a suitable service e-mail to the shopping cart abandoner.
    28 * Depending on the website visitor and reason for abandonment, a distinction is made between individual vouchers and automated assistance.
    29 * Each individual Abandonment-Mail is optimized and individualized according to time, address, content, etc.
    30 * With uptain's Abandonment-Mails you can win back your shopping cart abandoners in accordance with the GDPR.
    31 * Our technologies consider the customer journey across the various devices of your end customers - also for guest and new customers.
     30The net-sum option includes product totals from created orders, including unpaid orders, after discounts and itemized refunds, excluding tax, shipping and fees. As in the original integration, payment status does not filter these orders; failed and cancelled orders remain included. This is order value, not confirmed paid revenue. Disabling personal data also disables email and revenue transmission. The plugin reads the visitor's current WooCommerce session through WordPress admin-ajax.php for on-page refreshes. A server-side PHP session keeps a newly placed order available for the confirmation page. Consent settings continue to control when the external script starts.
    3231
    33 **Payment Models**
     32No account, email address or shop URL is sent to the former agency's activation webhook. No external update server is used; updates use the existing WordPress.org entry.
    3433
    35 An uptain ID is required to use the plugin. You will receive this from the service team after you have decided on one of the models.
    36 uptain offers transparent and success-oriented payment models:
     34* [uptain service](https://uptain.de/)
     35* [Terms](https://uptain.de/agb/)
     36* [Privacy policy](https://uptain.de/datenschutz/)
    3737
    38 *Lead*
    39 
    40 * Pay for real contacts only
    41 
    42 *Provision*
    43 
    44 * Pay for additional revenue only
    45 
    46 *Flat-Fee*
    47 
    48 * Pay reliable in budget and planning
    49 
    50 No contract period. No fixed costs. Our most popular model is success-based invoicing via commission. Calculate your individual commission rate using our online calculator:
    51 https://uptain.de/en/pricing/
    52 
    53 You will then receive your personal uptain ID so that you can use the plugin.
    54 If you wish to use one of the other models, simply contact our experts:
    55 https://uptain.de/en/contact/
    56 
    57 == Why uptain? ==
    58 
    59 uptain uses real-time data processing to react quickly and effectively to shopping cart abandonments. This allows you to use the traffic on your website from the very first minute in order to perform better.
    60 
    61 **Conversion Optimization**
    62 
    63 * Increase your conversion rate without great effort by automatically recovering up to 30% of your shopping cart abandoners.
    64 
    65 **More customers- satisfied and sustainable**
    66 
    67 * Take advantage of the potential behind shopping cart abandonment and convert approximately 30% of your shopping cart abandoners into profitable conversions. With our individually customized service-oriented customer communication, you will achieve particularly high response rates and long-term customer loyalty.
    68 
    69 **Up to 10% more revenue**
    70 
    71 * With the help of our solutions you can increase your revenue sustainably by up to 10%.
    72 
    73 **Relief of IT**
    74 
    75 * Our solutions adapt effortlessly to your corporate design - without IT or design knowledge.
     38You are responsible for selecting the appropriate consent settings for your shop. Consent tools are installed and configured separately.
    7639
    7740== Installation ==
    7841
    79 For using uptain-connect an individual uptain-ID is required. Please visit the following website to sign up for a free uptain-ID:
     421. Back up the shop and test the update in staging.
     432. Install and activate WooCommerce, then install or update "uptain-connect". For a ZIP update, use Plugins > Add New > Upload Plugin and replace the existing version.
     443. Open Settings > uptain and enter your uptain ID. Existing IDs and settings are retained when updating.
     454. Configure the consent and personal-data options as required for your shop and clear all page/CDN caches.
     465. Test a fresh visit, cart changes, customer-data settings and a test order.
    8047
    81 [Sign-up](https://www.uptain.de/en/portfolio/woocommerce/) for uptain
     48== Frequently Asked Questions ==
    8249
    83 After you have successfully signed up for a free uptain-ID our service team will contact you immediately to configure the uptain-software based on your specific wishes. Additional costs apply only in case of success on a commission basis.
     50= Do I need a new plugin entry or to reconfigure existing installations? =
     51
     52No. This release retains the uptain-connect folder, wf-uptain-tracking.php filename and existing option keys. It updates the existing plugin.
     53
     54= What should I check with caching? =
     55
     56Do not cache personalized cart/customer data across visitors. Exclude personalized pages from shared page caches and clear cached pages after changing consent settings. Disabling initial data sending suppresses the plugin's initial uptain.readData event; it does not remove tracking data from the page HTML. Ensure visitors can access WordPress admin-ajax.php for on-page refreshes.
    8457
    8558== Changelog ==
     59
     60= 2.4.2 =
     61* Enable personal data and net order value by default for new installations, preserving existing shops' choices.
     62* Include a known visitor's email before SDK startup; include names, customer ID and net order value on order creation without waiting for payment.
     63* Support guest personal data through their own checkout session without looking up other orders by email.
     64* Calculate net product value after discounts and item refunds; clear stale personal attributes on refresh.
     65* Update compatibility metadata for WordPress 7.1 and WooCommerce 11.3.
     66* Support the Store API checkout hook used by Checkout blocks and declare HPOS compatibility.
     67* Keep initial blocking optional and preserve existing settings and plugin identity.
     68* Escape dynamic script values, validate settings and use the correct AJAX URL for subdirectory installations.
     69* Avoid duplicate refresh timers and JavaScript errors when the external script is unavailable.
     70* Handle missing orders safely and retain a new-order marker across cart refreshes until the next page load.
     71* Initialize order sessions before block themes flush page output, preserving delayed order confirmations and avoiding competing checkout sessions.
     72* Remove the former agency's activation webhook, obsolete external updater and their bundled HTTP dependencies.
     73* Preserve credit for the original integration by Timo Förster / webförsterei. Maintenance by uptain GmbH.
    8674
    8775= 2.4.0 =
    … …  
    121109== Upgrade Notice ==
    122110
    123 = 1.1 =
    124 This update allows a quicker integration of the uptain product.
     111= 2.4.2 =
     112Compatibility and customer-data update. Existing settings are preserved. Test installation, checkout and customer-data settings in staging before updating production, and clear page caches.
  • uptain-connect/trunk/src/Admin.php

    r3130976 r3834804  
    99
    1010namespace Webfoersterei\Wordpress\Plugin\UptainTracking;
     11
     12defined('ABSPATH') || exit;
    1113
    1214class Admin implements RegistrableWordpressInterface
    … …  
    2527    public const MIN_REFRESH_MS = 5000;
    2628
     29    public static function initializeSettings(): void
     30    {
     31        // Activation only: an upgrade must not opt an existing shop into personal data.
     32        // Empty/false values are saved choices, not missing options.
     33        foreach ([self::OPTION_NAME_TRACKING_ID, self::OPTION_NAME_INCLUDE_PERSONAL_DATA,
     34            self::OPTION_NAME_INCLUDE_NET_WORTH, self::OPTION_NAME_INCLUDE_DEFERRED,
     35            self::OPTION_NAME_DEBUG, self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL,
     36            self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE, self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE,
     37            self::OPTION_NAME_CONSENTMANAGER_VENDORID] as $name) {
     38            if (get_option($name, null) !== null) {
     39                return;
     40            }
     41        }
     42        add_option(self::OPTION_NAME_INCLUDE_PERSONAL_DATA, '1');
     43        add_option(self::OPTION_NAME_INCLUDE_NET_WORTH, '1');
     44    }
     45
    2746    public function registerInWordpress(): void
    2847    {
    … …  
    3352    public function registerSettings()
    3453    {
    35         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_TRACKING_ID);
    36         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_DEFERRED);
    37         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_PERSONAL_DATA);
    38         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_NET_WORTH);
    39         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL);
    40         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE);
    41         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE);
    42         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_CONSENTMANAGER_VENDORID);
    43         register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_DEBUG);
     54        foreach ([self::OPTION_NAME_TRACKING_ID, self::OPTION_NAME_CONSENTMANAGER_VENDORID] as $name) {
     55            register_setting(self::OPTIONS_NAMESPACE_SLUG, $name, ['sanitize_callback' => 'sanitize_text_field']);
     56        }
     57        foreach ([self::OPTION_NAME_INCLUDE_DEFERRED, self::OPTION_NAME_INCLUDE_PERSONAL_DATA,
     58            self::OPTION_NAME_INCLUDE_NET_WORTH, self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE,
     59            self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE, self::OPTION_NAME_DEBUG] as $name) {
     60            register_setting(self::OPTIONS_NAMESPACE_SLUG, $name, ['sanitize_callback' => [self::class, 'sanitizeCheckbox']]);
     61        }
     62        register_setting(self::OPTIONS_NAMESPACE_SLUG, self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL,
     63            ['sanitize_callback' => [self::class, 'sanitizeInterval']]);
     64    }
     65
     66    public static function sanitizeCheckbox($value): string
     67    {
     68        return $value === '1' || $value === 1 || $value === true ? '1' : '';
     69    }
     70
     71    public static function sanitizeInterval($value): int
     72    {
     73        return max(self::MIN_REFRESH_MS, min(120000, (int) $value));
    4474    }
    4575
    … …  
    5787    public function renderOptionsPage()
    5888    {
     89        if (!current_user_can('manage_options')) {
     90            return;
     91        }
    5992        ?>
    6093        <style>
    … …  
    106139                <?php printf(
    107140                    '<input type="text" name="%s" value="%s" />',
    108                     self::OPTION_NAME_TRACKING_ID,
     141                    esc_attr(self::OPTION_NAME_TRACKING_ID),
    109142                    esc_attr(get_option(self::OPTION_NAME_TRACKING_ID, ''))
    110143                ); ?>
    … …  
    113146            </div>
    114147            <div class="row">
    115                 <label>Include personal data?</label>
     148                <label for="wf-uptain-personal-data">Include personal data?</label>
    116149                <input type="checkbox" id="wf-uptain-personal-data"
    117                        name="<?php echo self::OPTION_NAME_INCLUDE_PERSONAL_DATA ?>" value="1" <?php checked(
     150                       name="<?php echo esc_attr(self::OPTION_NAME_INCLUDE_PERSONAL_DATA); ?>" value="1" <?php checked(
    118151                    1,
    119152                    get_option(self::OPTION_NAME_INCLUDE_PERSONAL_DATA),
    120153                    true
    121154                ); ?> onchange="if(!this.checked) { document.getElementById('wf-uptain-netsum').checked = false; }"/>
    122                 <small>Personal data (e.g. E-Mail, Name) of the customer is only included if this checkbox is set
    123                     <strong>and</strong> the customer already has at least ordered once in the past (any order status)</small>
     155                <small>If enabled, an available email address is included from the first page load, even before a first
     156                    order. Names and customer ID are included as soon as an order is created, without waiting
     157                    for payment. Guest checkout data is limited to orders from the current
     158                    shop session. Default: enabled for new installations. Consent settings still apply.</small>
    124159            </div>
    125160            <div class="row suboption">
    126                 <label>Include total net sum?</label>
    127                 <input type="checkbox" id="wf-uptain-netsum" name="<?php echo self::OPTION_NAME_INCLUDE_NET_WORTH ?>"
     161                <label for="wf-uptain-netsum">Include total net sum?</label>
     162                <input type="checkbox" id="wf-uptain-netsum" name="<?php echo esc_attr(self::OPTION_NAME_INCLUDE_NET_WORTH); ?>"
    128163                       value="1" <?php checked(
    129164                    1,
    … …  
    132167                ); ?>
    133168                       onchange="if(this.checked) { document.getElementById('wf-uptain-personal-data').checked = true; }"/>
    134                 <small>If personal data is being included also include the customers worth calculated as net sum of all
    135                     their orders</small>
     169                <small>Include the net product value of created orders, including unpaid orders, after discounts and item refunds, excluding
     170                    tax, shipping and fees. Requires personal data to be enabled. For guests, only orders from the
     171                    current shop session are included. Default: enabled for new installations.</small>
    136172            </div>
    137173            <div class="row">
    138174                <label>Block inclusion initially?</label>
    139                 <input type="checkbox" name="<?php echo self::OPTION_NAME_INCLUDE_DEFERRED ?>" value="1" <?php checked(
     175                <input type="checkbox" name="<?php echo esc_attr(self::OPTION_NAME_INCLUDE_DEFERRED); ?>" value="1" <?php checked(
    140176                    1,
    141177                    get_option(self::OPTION_NAME_INCLUDE_DEFERRED),
    142178                    true
    143179                ); ?> />
    144                 <small>If set, initially blocks cookies (and thus uptain) and waits until the JS-function <span
    145                             class="code">uptainEnable();</span> is executed (e.g. by Cookie-Consent-Tool)</small>
     180                <small>If checked, uptain waits for consent to the Usercentrics service "Uptain" and then starts
     181                    automatically. Without Usercentrics, it waits for a manual <span class="code">uptainEnable();</span>
     182                    call. If unchecked, this plugin does not wait for Usercentrics consent.
     183                    Existing Cookiebot and Consentmanager integrations still apply.</small>
    146184            </div>
    147185            <h2>WordPress</h2>
    … …  
    150188                <?php printf(
    151189                    '<input type="text" name="%s" value="%s" />',
    152                     self::OPTION_NAME_CONSENTMANAGER_VENDORID,
     190                    esc_attr(self::OPTION_NAME_CONSENTMANAGER_VENDORID),
    153191                    esc_attr(function_exists('consentmanager_start_cmp') ? get_option(self::OPTION_NAME_CONSENTMANAGER_VENDORID, '') : '')
    154192                ); ?>
    … …  
    156194            <div class="row">
    157195                <label>Debug-Modus:</label>
    158                 <input type="checkbox" name="<?php echo self::OPTION_NAME_DEBUG ?>" value="1" <?php checked(
     196                <input type="checkbox" name="<?php echo esc_attr(self::OPTION_NAME_DEBUG); ?>" value="1" <?php checked(
    159197                    1,
    160198                    get_option(self::OPTION_NAME_DEBUG),
    … …  
    165203            <div class="row <?php echo get_option(self::OPTION_NAME_DEBUG) ? '' : 'hidden' ?>">
    166204                <label>Disable on-page refresh:</label>
    167                 <input type="checkbox" name="<?php echo self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE ?>"
     205                <input type="checkbox" name="<?php echo esc_attr(self::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE); ?>"
    168206                       value="1" <?php checked(
    169207                    1,
    … …  
    176214            <div class="row <?php echo get_option(self::OPTION_NAME_DEBUG) ? '' : 'hidden' ?>">
    177215                <label>on-page refresh interval:</label>
    178                 <input type="number" min="<?php echo self::MIN_REFRESH_MS ?>" max="120000"
    179                        name="<?php echo self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL ?>"
     216                <input type="number" min="<?php echo esc_attr(self::MIN_REFRESH_MS); ?>" max="120000"
     217                       name="<?php echo esc_attr(self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL); ?>"
    180218                       value="<?php echo esc_attr(
    181219                           get_option(self::OPTION_NAME_INCLUDE_REFRESH_INTERVAL, self::DEFAULT_REFRESH_MS)
    182220                       ); ?>"/>
    183                 <small>Milliseconds. Do not set below <?php echo self::MIN_REFRESH_MS ?>. Recommended: Between 20000 and
     221                <small>Milliseconds. Do not set below <?php echo esc_attr(self::MIN_REFRESH_MS); ?>. Recommended: Between 20000 and
    184222                    30000. Lower values do have
    185223                    impact on WordPress overall Performance. Use option above to disable</small>
    … …  
    187225            <div class="row <?php echo get_option(self::OPTION_NAME_DEBUG) ? '' : 'hidden' ?>">
    188226                <label>Disable initial data sending:</label>
    189                 <input type="checkbox" name="<?php echo self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE ?>"
     227                <input type="checkbox" name="<?php echo esc_attr(self::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE); ?>"
    190228                       value="1" <?php checked(
    191229                    1,
    … …  
    193231                    true
    194232                ); ?> />
    195                 <small>Check to disable data transmission to uptain on full-page-load. See information below when to do
    196                     so</small>
     233                <small>Disables the plugin's initial uptain.readData event after script startup.
     234                    Data already present in the page remains available to the uptain script.</small>
    197235            </div>
    198236            <div class="row <?php echo get_option(self::OPTION_NAME_DEBUG) ? '' : 'hidden' ?>">
    199237                <label>Information:</label>
    200                 <div><p>This plugin uses the WP-REST-API to update values and push them to uptain when no
    201                         full-page-refresh is happening client side. If you disabled WP-Rest-API this will not work.
    202                         Worse, if you added basic authentication in front of your Rest-API, users will be prompted a
    203                         credential window. Disable on-page refresh in those cases.</p>
    204                     <p>This plugin may send wrong information if aggressive server-side-caching is being performed. If
    205                         you encounter such issues you can disable the initial data sending (and should so enable the
    206                         on-page-refresh which is not being cached). Please also clear your cache after changing those
    207                         settings.</p></div>
     238                <div><p>This plugin uses WordPress admin-ajax.php to refresh cart values without a full page load.
     239                        Visitors must be able to access this endpoint. Disable on-page refresh if your server blocks it.</p>
     240                    <p>Exclude pages containing personalized cart or customer data from shared page caches.
     241                        Disabling initial data sending does not remove that data from the HTML.
     242                        Please clear your cache after changing these settings.</p></div>
    208243            </div>
    209244            <?php submit_button(); ?>
  • uptain-connect/trunk/src/Plugin.php

    r3130976 r3834804  
    11<?php
    2 
    3 declare(strict_types=1);
    4 
    52/**
    6  * @author Timo Förster <tfoerster@webfoersterei.de>
    7  * @date 15.05.2023
     3 * Consent-aware loader for the existing uptain-connect integration.
     4 * Original integration: Timo Förster / webförsterei, 2023.
     5 * Maintenance: uptain GmbH, 2026. GPL-2.0-or-later.
    86 */
    9 
    107namespace Webfoersterei\Wordpress\Plugin\UptainTracking;
    118
    12 use Webfoersterei\Wordpress\Plugin\UptainTracking\Dependencies\GuzzleHttp\Client;
     9defined('ABSPATH') || exit;
    1310
    1411class Plugin implements RegistrableWordpressInterface
    1512{
    16     private const STATIC_DATA_KEYS = ['page', 'plugin'];
     13    private const JSON_FLAGS = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
    1714    private static string $slug;
    1815    private static string $version;
    1916    private static string $wpAjaxAction;
    20     private ?TrackerInterface $tracker = null;
    2117    public const REST_ROUTE_TRACKING_VALUES = 'values';
    22     private const HOTDEV_HTTP_HEADER_NAME = 'HTTP_X_WEBFOERSTEREI_HOTDEV';
    2318
    24     public function __construct($slug, $version)
     19    public function __construct(string $slug, string $version)
    2520    {
    2621        self::$slug = $slug;
    2722        self::$version = $version;
    28         self::$wpAjaxAction = sprintf('%s_%s', $slug, self::REST_ROUTE_TRACKING_VALUES);
     23        self::$wpAjaxAction = $slug . '_' . self::REST_ROUTE_TRACKING_VALUES;
    2924    }
    3025
    31     public function onActivation(): void
    32     {
    33         try {
    34             $httpClient = new Client();
    35             $httpClient->post('https://hooks.zapier.com/hooks/catch/1548047/3tasect/', [
    36                 'json' => [
    37                     'email' => get_option('admin_email'),
    38                     'url'   => get_home_url(),
    39                 ],
    40             ]);
    41         } catch (\Throwable $ex) {
    42             // Ignore failed home call
    43             return;
    44         }
    45     }
    46 
    47     /**
    48      * @return string
    49      */
    5026    public static function getSlug(): string
    5127    {
    … …  
    5329    }
    5430
    55     private static function getPluginIdentifier()
    56     {
    57         return trim('woocommerce_'.preg_replace('/[^a-z0-9.-]/i', '', self::getVersion()));
    58     }
    59 
    60     private function getTracker(): TrackerInterface
    61     {
    62         if (!$this->tracker) {
    63             $this->tracker = new WooCommerceTracker(); // TODO: Generalize. e.g. Admin-Property
    64         }
    65 
    66         return $this->tracker;
    67     }
    68 
    69     /**
    70      * @return string
    71      */
    7231    public static function getVersion(): string
    7332    {
    7433        return self::$version;
    7534    }
    76 
    77     public function sendAjaxTrackingData() {
    78         wp_send_json($this->formatAsJsonArray($this->getTrackingData(), true));
    79     }
     35    private const STATIC_DATA_KEYS = ['page', 'plugin'];
    8036
    8137    public function registerInWordpress(): void
    8238    {
    83         add_action('wp_footer', [&$this, 'injectJsDataSnippet']);
    84         add_action('wp_ajax_'.self::$wpAjaxAction, [&$this, 'sendAjaxTrackingData']);
    85         add_action('wp_ajax_nopriv_'.self::$wpAjaxAction, [&$this, 'sendAjaxTrackingData']);
     39        (new Admin())->registerInWordpress();
     40        (new WooCommerceTracker())->registerInWordpress();
     41        add_action('wp_footer', [$this, 'injectJsDataSnippet']);
     42        add_action('wp_ajax_' . self::$wpAjaxAction, [$this, 'sendAjaxTrackingData']);
     43        add_action('wp_ajax_nopriv_' . self::$wpAjaxAction, [$this, 'sendAjaxTrackingData']);
     44    }
    8645
    87         foreach (array_merge(glob(__DIR__.'/*.php')) as $potentialPhpClassFilePath) {
    88             [$className] = explode('.', basename($potentialPhpClassFilePath));
    89             $className = __NAMESPACE__.'\\'.$className;
    90             $interfaces = class_implements($className);
     46    public function sendAjaxTrackingData(): void
     47    {
     48        // Read-only response for the visitor's own WooCommerce session; no supplied IDs.
     49        wp_send_json($this->trackingData(true));
     50    }
    9151
    92             if (isset($interfaces[RegistrableWordpressInterface::class]) && $className !== __CLASS__) {
    93                 (new $className())->registerInWordpress();
     52    private function trackingData(bool $refresh = false): array
     53    {
     54        $data = (new WooCommerceTracker())->getCurrentTrackingData();
     55        $data['plugin'] = 'woocommerce_' . self::getVersion();
     56        $result = [];
     57        foreach ($data as $key => $value) {
     58            if ($refresh && in_array($key, self::STATIC_DATA_KEYS, true)) {
     59                continue;
    9460            }
     61            $result[] = [
     62                'key' => preg_replace('/[^a-z0-9]/i', '', strtolower($key)),
     63                'value' => trim(wp_strip_all_tags((string) $value)),
     64            ];
     65        }
     66        return $result;
     67    }
     68
     69    public function injectJsDataSnippet(): void
     70    {
     71        $id = trim((string) get_option(Admin::OPTION_NAME_TRACKING_ID, ''));
     72        if ($id === '' || !function_exists('WC')) {
     73            return;
     74        }
     75        $vendor = trim((string) get_option(Admin::OPTION_NAME_CONSENTMANAGER_VENDORID, ''));
     76        $attributes = ['data-no-minify' => '1', 'type' => 'text/javascript'];
     77        $cookiebot = function_exists('\cybot\cookiebot\lib\cookiebot_active')
     78            ? \cybot\cookiebot\lib\cookiebot_active()
     79            : (function_exists('cookiebot_active') && cookiebot_active());
     80        $blockInitially = (bool) get_option(Admin::OPTION_NAME_INCLUDE_DEFERRED, false);
     81        $usercentricsBlocking = $blockInitially && !$cookiebot;
     82        if ($cookiebot) {
     83            $attributes['type'] = 'text/plain';
     84            $attributes['data-cookieconsent'] = 'marketing';
     85        } elseif ($usercentricsBlocking) {
     86            $attributes['type'] = 'text/plain';
     87            $attributes['data-usercentrics'] = 'Uptain';
     88            $attributes['data-uptain-auto-consent'] = '1';
     89        }
     90        if ($vendor !== '') {
     91            $attributes['data-cmp-ab'] = '2';
     92        }
     93
     94        $url = wp_json_encode('https://app.uptain.de/js/uptain.js?x=' . rawurlencode($id), self::JSON_FLAGS);
     95        try {
     96            $data = wp_json_encode($this->trackingData(), self::JSON_FLAGS);
     97        } catch (\Throwable $error) {
     98            // Preserve the original fail-soft behavior if a shop extension cannot supply tracking data.
     99            self::debug('tracking-error', $error->getMessage());
     100            return;
     101        }
     102        $initial = wp_json_encode(!get_option(Admin::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE, false));
     103        $refresh = wp_json_encode(!get_option(Admin::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE, false));
     104        $interval = Admin::sanitizeInterval(get_option(Admin::OPTION_NAME_INCLUDE_REFRESH_INTERVAL, Admin::DEFAULT_REFRESH_MS));
     105        $ajaxUrl = wp_json_encode(admin_url('admin-ajax.php'), self::JSON_FLAGS);
     106        $ajaxBody = wp_json_encode('action=' . self::$wpAjaxAction, self::JSON_FLAGS);
     107
     108        // WordPress escapes attributes; all dynamic JavaScript strings are JSON encoded with HEX flags.
     109        wp_print_inline_script_tag(strtr(file_get_contents(__DIR__ . '/uptain-loader.js'), [
     110            'UPTAIN_URL' => $url, 'UPTAIN_DATA' => $data, 'UPTAIN_INITIAL' => $initial, 'UPTAIN_REFRESH' => $refresh, 'UPTAIN_INTERVAL' => $interval
     111        ]), array_merge($attributes, ['id' => self::getSlug() . '-pre-consent']));
     112
     113        wp_print_inline_script_tag(strtr(file_get_contents(__DIR__ . '/uptain-refresh.js'), [
     114            'UPTAIN_AJAX_URL' => $ajaxUrl, 'UPTAIN_AJAX_BODY' => $ajaxBody
     115        ]), array_merge($attributes, ['id' => self::getSlug() . '-refresh']));
     116
     117        if (!$blockInitially || $usercentricsBlocking) {
     118            $execute = 'uptainEnable();';
     119            if ($vendor !== '' && !$usercentricsBlocking) {
     120                $vendorJson = wp_json_encode($vendor, self::JSON_FLAGS);
     121                $execute = 'if (typeof __cmp === "function") { __cmp("addEventListener", ["consent", function() {'
     122                    . 'var data = __cmp("getCMPData"); if (data && data.vendorConsents && data.vendorConsents[' . $vendorJson . ']) uptainEnable();'
     123                    . '}, false], null); }';
     124            }
     125            $startAttributes = ['id' => self::getSlug() . '-direct-execute'];
     126            if ($usercentricsBlocking) {
     127                $startAttributes['data-uptain-consent-start'] = '1';
     128            }
     129            wp_print_inline_script_tag($execute, array_merge($attributes, $startAttributes));
     130        }
     131        if ($usercentricsBlocking) {
     132            wp_print_inline_script_tag(file_get_contents(__DIR__ . '/consent-bootstrap.js'), [
     133                'id' => self::getSlug() . '-consent-bootstrap',
     134                'data-no-minify' => '1',
     135                'data-cmp-ab' => '2',
     136                'data-cookieconsent' => 'ignore',
     137            ]);
    95138        }
    96139    }
    97140
    98     public function injectJsDataSnippet()
     141    public static function debug($name, $value): void
    99142    {
    100         Plugin::debug('version', self::getVersion());
    101         if (!$this->isEnabled()) {
    102             Plugin::debug('enabled', false);
    103 
    104             return;
    105         }
    106         Plugin::debug('enabled', true);
    107 
    108         if (function_exists('\cybot\cookiebot\lib\cookiebot_active')) {
    109             Plugin::debug('-cookiebot-exists', 'namespaced');
    110             $cookieBotEnabled = \cybot\cookiebot\lib\cookiebot_active();
    111         } else {
    112             Plugin::debug('cookiebot-exists', 'legacy');
    113             $cookieBotEnabled = function_exists('cookiebot_active') && cookiebot_active();
    114         }
    115 
    116         Plugin::debug('cookiebot-enabled', $cookieBotEnabled);
    117         Plugin::debug('consentmanager-enabled', function_exists('consentmanager_start_cmp'));
    118 
    119         if ($cookieBotEnabled) {
    120             $scriptType = (function_exists('\cybot\cookiebot\lib\cookiebot_assist') ?
    121                 \cybot\cookiebot\lib\cookiebot_assist('marketing')
    122                 : cookiebot_assist('marketing'));
    123         } else {
    124             $scriptType = 'type="application/javascript"';
    125         }
    126 
    127         $scriptTagGeneralAmend = '';
    128         $scriptTagImmediateAmend = '';
    129         $consentManagerVendorId = trim((string)get_option(Admin::OPTION_NAME_CONSENTMANAGER_VENDORID, ''));
    130         $scriptImmediateEventEmitter = 'uptainEnable();';
    131 
    132         if ($consentManagerVendorId) {
    133             $scriptTagGeneralAmend = 'data-cmp-ab="2"';
    134             // $scriptTagImmediateAmend = sprintf('class="cmplazyload" data-cmp-vendor="%s"', $consentManagerVendorId);
    135 
    136             $scriptImmediateEventEmitter = sprintf('__cmp("addEventListener",["consent",function() {
    137                                 if(__cmp("getCMPData").vendorConsents && __cmp("getCMPData").vendorConsents["%s"]) {
    138                                 uptainEnable();
    139                                 }
    140                                 },false],null);', $consentManagerVendorId);
    141 
    142             Plugin::debug('consentmanager-vendorid', $consentManagerVendorId);
    143         }
    144 
    145         try {
    146             printf(
    147                 '<script data-no-minify="1" id="%1$s" %7$s %8$s>
    148             function uptainEnable(retry = 0) {
    149                 var maxRetry = 10;
    150                 var retryInterval = 500;
    151                 var uptainTag = document.getElementById("__up_data_qp");
    152                
    153                 if (!uptainTag) {
    154                     uptainTag = document.createElement("script");
    155                     uptainTag.setAttribute("src", "https://app.uptain.de/js/uptain.js?x=%2$s");
    156                     uptainTag.setAttribute("id", "__up_data_qp");
    157                     uptainTag.setAttribute("defer", "");
    158                     uptainTag.setAttribute("async", "");
    159                     document.head.appendChild(uptainTag);
    160                 }
    161                
    162                 var data = %3$s;
    163                
    164                 for (var i = 0; i < data.length; i++) {
    165                     var elem = data[i];
    166                     uptainTag.setAttribute("data-"+elem.key, elem.value);
    167                 }
    168                 uptainTag.setAttribute("data-x-retry", retry);
    169                
    170                 if(typeof window._upEventBus === "undefined" && retry <= maxRetry) {
    171                     setTimeout(function() { uptainEnable(++retry); }, retryInterval * retry);
    172                     return;
    173                 }
    174 
    175                 if(%4$s) { window._upEventBus.publish("uptain.readData"); }
    176                 if(%5$s) { setInterval(uptainRefresh, %6$d); }
    177                 if((%4$s || %5$s) && document.getElementById("%1$s")) { document.getElementById("%1$s").remove(); }
    178             }
    179         </script>',
    180                 self::getSlug().'-pre-consent',
    181                 $this->getUptainTrackingId(),
    182                 json_encode(
    183                     $this->formatAsJsonArray($this->getTrackingData()),
    184                     JSON_THROW_ON_ERROR
    185                 ),
    186                 json_encode(!get_option(Admin::OPTION_NAME_INITIAL_TRANSMISSION_DISABLE, false)),
    187                 json_encode(!get_option(Admin::OPTION_NAME_REFRESH_TRANSMISSION_DISABLE, false)),
    188                 max(
    189                     (int)get_option(Admin::OPTION_NAME_INCLUDE_REFRESH_INTERVAL, Admin::DEFAULT_REFRESH_MS),
    190                     Admin::MIN_REFRESH_MS
    191                 ),
    192                 $scriptType,
    193                 $scriptTagGeneralAmend
    194             );
    195             printf(
    196                 '<script data-no-minify="1" id="%1$s" %3$s %4$s>
    197             var lastSetKeys = [];
    198             async function uptainRefresh() {
    199                 console.log("uptainRefresh");
    200                 var uptainTag = document.getElementById("__up_data_qp");
    201                
    202                 if (!uptainTag) {
    203                     return;
    204                 }
    205                 if (uptainTag.getAttribute("data-success")) {
    206                     console.log("Successful order will not be updated");
    207                     return;
    208                 }
    209                
    210                 var response = await fetch("/wp-admin/admin-ajax.php", { method: "POST",
    211                     headers: {
    212                       "Content-Type": "application/x-www-form-urlencoded",
    213                     },
    214                     body: "action=%5$s"}
    215                 );
    216                 var data = await response.json();
    217                
    218                 for (var i = 0; i < lastSetKeys.length; i++) {
    219                     uptainTag.removeAttribute("data-"+lastSetKeys[i]);
    220                 }
    221                
    222                 lastSetKeys = [];
    223 
    224                 for (var i = 0; i < data.length; i++) {
    225                     var elem = data[i];
    226                     uptainTag.setAttribute("data-"+elem.key, elem.value);
    227                     lastSetKeys.push(elem.key);
    228                 }
    229 
    230                 window._upEventBus.publish("uptain.readData");
    231             }
    232         </script>',
    233                 self::getSlug().'-refresh',
    234                 get_rest_url(null, self::getSlug().'/v1/'.self::REST_ROUTE_TRACKING_VALUES),
    235                 $scriptType,
    236                 $scriptTagGeneralAmend,
    237                 self::$wpAjaxAction
    238             );
    239         } catch (\Throwable $ex) {
    240             Plugin::debug('Error: ', $ex->getMessage());
    241 
    242             return;
    243         }
    244 
    245         if ($this->immediateInclude()) {
    246             Plugin::debug('immediate-include', true);
    247             printf(
    248                 '<script data-no-minify="1" id="%1$s" %2$s>
    249                                 %3$s
    250                                 </script>',
    251                 self::getSlug().'-direct-execute',
    252                 $scriptType,
    253                 $scriptImmediateEventEmitter
    254             );
    255         }
    256     }
    257 
    258     private function getTrackingData()
    259     {
    260         return array_merge($this->getTracker()->getCurrentTrackingData(), ['plugin' => self::getPluginIdentifier()]);
    261     }
    262 
    263     private function formatAsJsonArray(array $array, bool $deleteStaticKeys = false): array
    264     {
    265         return array_values(array_filter(
    266             array_map(
    267                 fn($key, $value) => [
    268                     'key'   => $this->getHtmlKey($key),
    269                     'value' => $this->getHtmlValue($value),
    270                 ],
    271                 array_keys($array),
    272                 array_values($array)
    273             ),
    274             static fn($element) => !$deleteStaticKeys || !in_array(
    275                     strtolower($element['key']),
    276                     self::STATIC_DATA_KEYS,
    277                     true
    278                 )
    279         ));
    280     }
    281 
    282     private function getHtmlValue($value)
    283     {
    284         $value = strip_tags((string)$value);
    285         if (is_scalar($value)) {
    286             return trim($value);
    287         }
    288 
    289         return json_encode($value);
    290     }
    291 
    292     private function getHtmlKey(string $key)
    293     {
    294         return trim(preg_replace('/[^a-z0-9]/i', '', strtolower(strip_tags($key))));
    295     }
    296 
    297     private function isEnabled()
    298     {
    299         return !empty(trim(str_replace('X', 'X', $this->getUptainTrackingId() ?: '')));
    300     }
    301 
    302     private function getUptainTrackingId()
    303     {
    304         return \get_option(Admin::OPTION_NAME_TRACKING_ID, '');
    305     }
    306 
    307     private function immediateInclude(): bool
    308     {
    309         return !\get_option(Admin::OPTION_NAME_INCLUDE_DEFERRED);
    310     }
    311 
    312     public static function debug($header, $value)
    313     {
    314         $isHotDev = isset($_SERVER[self::HOTDEV_HTTP_HEADER_NAME]) && ((int)$_SERVER[self::HOTDEV_HTTP_HEADER_NAME] >= 1024 && (int)$_SERVER[self::HOTDEV_HTTP_HEADER_NAME] <= 65534);
    315 
    316         if (!$isHotDev && !get_option(Admin::OPTION_NAME_DEBUG, false)) {
    317             return;
    318         }
    319         $value = var_export($value, true);
    320 
    321         if (!headers_sent()) {
    322             if (strpos($value, "\n")) {
    323                 $value = base64_encode($value);
    324             }
    325             header(sprintf("x-wf-uptain-%s: %s", strtolower($header), $value));
    326 
    327             return;
    328         }
    329 
    330         if ($isHotDev) {
    331             printf("DEBUG %s: %s", $header, $value);
     143        if (get_option(Admin::OPTION_NAME_DEBUG, false) && !headers_sent()) {
     144            $header = preg_replace('/[^a-z0-9-]/i', '', (string) $name);
     145            header('X-Wf-Uptain-' . $header . ': ' . rawurlencode(wp_json_encode($value)));
    332146        }
    333147    }
  • uptain-connect/trunk/src/WooCommerceTracker.php

    r3102401 r3834804  
    1010namespace Webfoersterei\Wordpress\Plugin\UptainTracking;
    1111
     12defined('ABSPATH') || exit;
     13
    1214class WooCommerceTracker implements TrackerInterface, RegistrableWordpressInterface
    1315{
     16    private const GUEST_ORDERS_SESSION_KEY = 'uptain_guest_orders';
    1417    private $WC;
    1518    private static $overrideOrderId = null;
    … …  
    4649    public function registerInWordpress(): void
    4750    {
    48         add_action('woocommerce_checkout_order_created', function ($order) {
    49             Plugin::debug('wc-hook-order-created', true);
    50             Plugin::debug('wc-hook-order-created-id', $order->get_id());
    51             if (!headers_sent() && session_status() !== PHP_SESSION_ACTIVE) {
    52                 session_start();
    53             }
    54             $_SESSION['freshOrder'] = $order->get_id();
    55             self::$overrideOrderId = $order->get_id();
    56         });
     51        add_action('template_redirect', [$this, 'prepareOrderSession'], 0);
     52        add_action('woocommerce_checkout_order_created', [$this, 'rememberOrder']);
     53        // The block checkout uses the Store API instead of the classic checkout hook.
     54        add_action('woocommerce_store_api_checkout_order_processed', [$this, 'rememberOrder']);
    5755
    5856        add_action('woocommerce_thankyou', function ($orderID) {
    … …  
    6260            }
    6361            $order = wc_get_order($orderID);
     62            if (!$order) {
     63                return;
     64            }
    6465            Plugin::debug(
    6566                'wc-hook-thankyou-created-ts',
    … …  
    7980    }
    8081
     82    public function prepareOrderSession(): void
     83    {
     84        // The original integration starts this session in the footer. Block themes
     85        // can flush headers earlier, leaving concurrent checkout/refresh requests
     86        // to create different sessions. Establish it before any frontend output.
     87        if (function_exists('WC') && get_option(Admin::OPTION_NAME_TRACKING_ID, '')
     88            && !headers_sent()
     89            && session_status() !== PHP_SESSION_ACTIVE) {
     90            session_start();
     91        }
     92    }
     93
     94    public function rememberOrder($order): void
     95    {
     96        if (!$order instanceof \WC_Order) {
     97            return;
     98        }
     99        if (!headers_sent() && session_status() !== PHP_SESSION_ACTIVE) {
     100            session_start();
     101        }
     102        $_SESSION['freshOrder'] = $order->get_id();
     103        self::$overrideOrderId = $order->get_id();
     104        // Only the server-side checkout hooks may associate an order with a guest.
     105        // An email address or an order ID supplied in a URL is not proof of ownership.
     106        if (!is_user_logged_in() && !$order->get_customer_id() && WC()->session
     107            && get_option(Admin::OPTION_NAME_INCLUDE_PERSONAL_DATA, false)) {
     108            $orders = (array) WC()->session->get(self::GUEST_ORDERS_SESSION_KEY, []);
     109            $orders[$order->get_id()] = $order->get_order_key();
     110            WC()->session->set(self::GUEST_ORDERS_SESSION_KEY, $orders);
     111        }
     112    }
     113
    81114    public function getCurrentTrackingData(): array
    82115    {
    … …  
    96129
    97130        Plugin::debug('override-orderid', self::$overrideOrderId);
    98         Plugin::debug('session-orderid', $_SESSION['freshOrder'] ?? null);
     131        Plugin::debug('session-orderid', absint($_SESSION['freshOrder'] ?? 0));
    99132
    100133        if (null === self::$overrideOrderId && isset($_SESSION['freshOrder']) && (int)$_SESSION['freshOrder']) {
    101             self::$overrideOrderId = $_SESSION['freshOrder'];
    102             $_SESSION['freshOrder'] = null;
     134            self::$overrideOrderId = absint($_SESSION['freshOrder']);
     135        }
     136        // A cart refresh on the checkout page must not consume the order before
     137        // the visitor reaches the confirmation page (possibly after a payment redirect).
     138        if (self::$overrideOrderId && !wp_doing_ajax()) {
     139            unset($_SESSION['freshOrder']);
    103140        }
    104141
    … …  
    142179    public function getPersonalData(): array
    143180    {
    144         $currentUser = \wp_get_current_user();
    145 
     181        if (!get_option(Admin::OPTION_NAME_INCLUDE_PERSONAL_DATA, false) || !$this->getWooCommerce()) {
     182            return [];
     183        }
     184
     185        $currentUser = wp_get_current_user();
     186        $includeRevenue = (bool) get_option(Admin::OPTION_NAME_INCLUDE_NET_WORTH, false);
     187        $orders = [];
     188        if ($currentUser->ID) {
     189            $email = $currentUser->user_email;
     190            // Never query by an unverified billing email: it could expose another customer's history.
     191            // Checkout blocks can create a draft before the visitor submits an order.
     192            $createdStatuses = array_values(array_diff(array_keys(wc_get_order_statuses()), ['wc-checkout-draft']));
     193            if ($createdStatuses) {
     194                $orders = wc_get_orders([
     195                    'customer_id' => $currentUser->ID, 'status' => $createdStatuses,
     196                    'limit' => $includeRevenue ? -1 : 1, 'orderby' => 'date', 'order' => 'DESC',
     197                ]);
     198            }
     199        } else {
     200            $email = $this->WC->customer ? $this->WC->customer->get_billing_email() : '';
     201            $sessionOrders = $this->getGuestOrders();
     202            if (!$email && $sessionOrders) {
     203                $email = $sessionOrders[0]->get_billing_email();
     204            }
     205            foreach ($sessionOrders as $order) {
     206                if ($email && strcasecmp($email, $order->get_billing_email()) === 0 && !$order->has_status('checkout-draft')) {
     207                    $orders[] = $order;
     208                }
     209            }
     210        }
     211
     212        // The SDK sees these attributes before it executes, including on session start.
     213        // Email is the only personal field allowed before the first order is created.
     214        $result = $email ? ['email' => $email] : [];
     215        if (!$orders) {
     216            return $result;
     217        }
     218        $order = $orders[0];
     219        $result['firstname'] = $currentUser->ID && $currentUser->user_firstname
     220            ? $currentUser->user_firstname : $order->get_billing_first_name();
     221        $result['lastname'] = $currentUser->ID && $currentUser->user_lastname
     222            ? $currentUser->user_lastname : $order->get_billing_last_name();
     223        if ($currentUser->ID) {
     224            $result['uid'] = $currentUser->ID;
     225        }
     226        // WooCommerce has no standard gender, title or customer-group field. Do not infer them.
     227        if ($includeRevenue) {
     228            $net = 0.0;
     229            foreach ($orders as $customerOrder) {
     230                foreach ($customerOrder->get_items('line_item') as $itemId => $item) {
     231                    $net += max(0, (float) $item->get_total() - $customerOrder->get_total_refunded_for_item($itemId));
     232                }
     233            }
     234            $result['revenue'] = number_format($net, 2, '.', '');
     235        }
     236        return $result;
     237    }
     238
     239    private function getGuestOrders(): array
     240    {
    146241        $result = [];
    147 
    148         Plugin::debug('user-id', $currentUser->ID);
    149 
    150         if ($this->shouldIncludePersonalData($currentUser)) {
    151             Plugin::debug('will-include-personal-data', 'yes');
    152             $result['email'] = $currentUser->user_email;
    153             $nameParts = explode(' ', $currentUser->display_name);
    154             $firstname = array_pop($nameParts);
    155             $result['firstname'] = $currentUser->user_firstname ?: ($firstname ?? '');
    156             $result['lastname'] = $currentUser->user_lastname ?: implode(' ', $nameParts);
    157             // $result['gender'] = ''; // Call 2.6. mit hn: Weglassen
    158             // $result['customergroup'] = ''; // Call 2.6. mit hn: Weglassen oder filtern aus beliebten Plugins. WooCommerce Groups sind eher Memberships für Subscriptions. Daher weggelassen. https://woocommerce.com/document/groups-woocommerce/
    159             $result['uid'] = $currentUser->ID;
    160 
    161             if (get_option(Admin::OPTION_NAME_INCLUDE_NET_WORTH, false)) {
    162                 Plugin::debug('will-include-net-worth', 'yes');
    163                 $orders = wc_get_orders(['customer' => $currentUser->ID, 'limit' => -1]);
    164                 $subtotals = array_map(fn($order) => $order->get_subtotal(), $orders);
    165                 $result['revenue'] = array_sum($subtotals);
    166             }
    167         }
    168 
     242        $remembered = $this->WC->session ? $this->WC->session->get(self::GUEST_ORDERS_SESSION_KEY, []) : [];
     243        foreach (array_reverse((array) $remembered, true) as $id => $key) {
     244            $order = wc_get_order(absint($id));
     245            if ($order instanceof \WC_Order && !$order->get_customer_id() && is_string($key) && $key !== ''
     246                && hash_equals($order->get_order_key(), $key)) {
     247                $result[] = $order;
     248            }
     249        }
    169250        return $result;
    170     }
    171 
    172     private function shouldIncludePersonalData($currentUser): bool
    173     {
    174         if (!$currentUser || !$currentUser->ID || !get_option(Admin::OPTION_NAME_INCLUDE_PERSONAL_DATA, false)) {
    175             Plugin::debug('will-include-personal-data', 'no-user-or-no-setting');
    176 
    177             return false;
    178         }
    179 
    180         if (!$this->getWooCommerce()) {
    181             return false;
    182         }
    183 
    184         $completedOrders = wc_get_orders(['customer' => $currentUser->ID, 'limit' => 1]);
    185 
    186         return count($completedOrders) >= 1;
    187251    }
    188252
  • uptain-connect/trunk/wf-uptain-tracking.php

    r3130976 r3834804  
    11<?php
     2/**
     3 * Plugin Name:       uptain Conversion-Rate Optimierung
     4 * Plugin URI:        https://wordpress.org/plugins/uptain-connect/
     5 * Description:       Connects WooCommerce with uptain for exit-intent popups and abandoned-cart recovery.
     6 * Version:           2.4.2
     7 * Requires at least: 5.8
     8 * Requires PHP:      7.4
     9 * Requires Plugins:  woocommerce
     10 * WC tested up to:   11.3.0
     11 * Author:            uptain GmbH
     12 * Author URI:        https://uptain.de/
     13 * License:           GPL-2.0-or-later
     14 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
     15 * Text Domain:       uptain-connect
     16 *
     17 * Original integration by Timo Förster / webförsterei, 2023.
     18 * Maintained by uptain GmbH, 2026.
     19 */
    220
    321declare(strict_types=1);
    422
    5 use Webfoersterei\Wordpress\Plugin\UptainTracking\Dependencies\GuzzleHttp\Client;
    6 use Webfoersterei\Wordpress\Plugin\UptainTracking\Dependencies\Psr\Http\Client\ClientExceptionInterface;
    723use Webfoersterei\Wordpress\Plugin\UptainTracking\Plugin;
    824
    9 require_once __DIR__.'/vendor/autoload.php';
     25defined('ABSPATH') || exit;
    1026
    11 /**
    12  * Plugin Name:       uptain Conversion-Rate Optimierung
    13  * Description:       Wir entwickeln automatisierte Lösungen zur Rückgewinnung von Kaufabbrechern nach dem neuesten Stand der Technik – gepaart mit absoluter Kundenorientierung.
    14  * Requires at least: 5.8
    15  * Version:           2.4.1
    16  * Requires PHP:      7.4
    17  * Tested up to:      6.6
    18  * Tags:              E-Commerce, Conversion-Optimierung, Exit-Intent, Warenkorb, Shop, Conversion, E-Mail, Big Data, DSGVO, Kundengewinnung, Marketing, Optimierung
    19  * Author:            uptain GmbH
    20  * Author URI:        https://www.uptain.de/
    21  * Contributors:      webfoersterei
    22  */
     27// Preserve the original filename, namespace and option keys for existing installations.
     28require_once __DIR__ . '/src/RegistrableWordpressInterface.php';
     29require_once __DIR__ . '/src/TrackerInterface.php';
     30require_once __DIR__ . '/src/Admin.php';
     31require_once __DIR__ . '/src/WooCommerceTracker.php';
     32require_once __DIR__ . '/src/Plugin.php';
    2333
    24 $slug = 'wf-uptain-tracking';
    25 $plugin = new Plugin(strpos($slug, '$') !== false ? 'plugin' : $slug, '2.4.1');
    26 $plugin->registerInWordpress();
     34register_activation_hook(__FILE__, [\Webfoersterei\Wordpress\Plugin\UptainTracking\Admin::class, 'initializeSettings']);
    2735
    28 register_activation_hook(__FILE__, [&$plugin, 'onActivation']);
     36(new Plugin('wf-uptain-tracking', '2.4.2'))->registerInWordpress();
    2937
    30 if (!function_exists('wf_plugin_update_handler')) {
    31     add_filter('update_plugins_updates.webfoersterei.de', 'wf_plugin_update_handler', 10, 4);
    32     function wf_plugin_update_handler($updateInfo, $pluginHeaders, $pluginFile, $language)
    33     {
    34         $pluginSlug = dirname($pluginFile);
    35 
    36         $checkUri = $pluginHeaders['UpdateURI'].sprintf('/%s', $pluginSlug);
    37 
    38         try {
    39             $client = new Client();
    40             $response = $client->get($checkUri, [
    41                 'query' => ['version' => $pluginHeaders['Version']],
    42             ]);
    43 
    44             return json_decode($response->getBody()->getContents(), true);
    45         } catch (Exception $exception) {
    46             return $updateInfo;
    47         }
     38add_action('before_woocommerce_init', static function () {
     39    if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
     40        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
     41        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
    4842    }
    49 }
     43});
Note: See TracChangeset for help on using the changeset viewer.