*/ private $deferred_purchase_order_ids = array(); /** @var AAMSettings aam settings instance, used to filter advanced matching fields*/ private $aam_settings; /** @var bool whether the pixel should be enabled */ private $is_pixel_enabled; /** @var CostOfGoods CostOfGoods provider instance. Used to calculate the profit margin */ private $cogs_provider; /** @var POS_Integration_Registry point-of-sale integrations, used to recognise offline orders */ private $pos_registry; /** @var array|null Pending pixel event data for Store API response */ private $pending_store_api_pixel_event = null; /** @var Event|null Server-side CF7 Lead event, stored so its browser pixel code can be injected into the CF7 REST response */ private $cf7_lead_event = null; /** @var array|null Reportable cart items, memoized per cart state so the clamp is only evaluated (and logged) once */ private $reportable_cart_items = null; /** @var string|null Cart hash the memoized reportable cart items were built from */ private $reportable_cart_items_hash = null; /** * @var \FacebookAds\ParamBuilder|null shared ParamBuilder instance */ private static $param_builder = null; /** @var string|null Cached fbc value from ParamBuilder */ private static $cached_fbc = null; /** @var string|null Cached fbp value from ParamBuilder */ private static $cached_fbp = null; /** * Order meta keys used by the tracker. */ const META_PURCHASE_TRACKED_BROWSER = '_meta_purchase_tracked_browser'; const META_PURCHASE_TRACKED_SERVER = '_meta_purchase_tracked_server'; const META_OFFLINE_PURCHASE_TRACKED = '_meta_offline_purchase_tracked'; const META_EVENT_ID = '_meta_event_id'; /** * Events tracker constructor. * * @param array $user_info * @param AAMSettings $aam_settings */ public function __construct( $user_info, $aam_settings ) { if ( ! $this->is_pixel_enabled() ) { return; } $this->pixel = new \WC_Facebookcommerce_Pixel( $user_info ); $this->aam_settings = $aam_settings; $this->tracked_events = array(); // Initialize external JS hooks early so script is enqueued before wp_enqueue_scripts fires. \WC_Facebookcommerce_Pixel::init_external_js_hooks(); $this->param_builder_server_setup(); $this->add_hooks(); $this->cogs_provider = new CostOfGoods(); $this->pos_registry = new POS_Integration_Registry(); } public static function get_param_builder() { if ( null === self::$param_builder ) { try { $site_url = get_site_url(); self::$param_builder = new \FacebookAds\ParamBuilder( array( $site_url ) ); self::$param_builder->processRequest( $site_url, // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Param builder intentionally inspects current request query parameters. self::get_scalar_request_values( $_GET ), self::get_scalar_request_values( $_COOKIE ), isset( $_SERVER['HTTP_REFERER'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : null ); } catch ( \Throwable $exception ) { Logger::log( 'Error initializing CAPI Parameter Builder: ' . $exception->getMessage(), array(), array( 'should_send_log_to_meta' => true, 'should_save_log_in_woocommerce' => true, 'woocommerce_log_level' => \WC_Log_Levels::ERROR, ) ); } } return self::$param_builder; } /** * Returns a copy of a request superglobal that only contains scalar values. * * PHP parses `name[key]=value` cookies and query parameters into arrays. The CAPI * Parameter Builder expects `_fbc`, `_fbp`, `_fbi` and `fbclid` to be strings and * throws a TypeError otherwise, which would take the whole request down and trip the * plugin crash handler. Array-shaped values are therefore dropped and treated as absent. * * @since 3.7.9 * * @param mixed $values superglobal contents, e.g. $_GET or $_COOKIE. * @return array */ public static function get_scalar_request_values( $values ) { if ( ! is_array( $values ) ) { return array(); } $scalar_values = array(); foreach ( $values as $key => $value ) { if ( is_scalar( $value ) ) { $scalar_values[ $key ] = (string) $value; } } return $scalar_values; } public static function get_fbc() { if ( null === self::$cached_fbc ) { $param_builder = self::get_param_builder(); if ( $param_builder ) { self::$cached_fbc = $param_builder->getFbc(); } } return self::$cached_fbc; } public static function get_fbp() { if ( null === self::$cached_fbp ) { $param_builder = self::get_param_builder(); if ( $param_builder ) { self::$cached_fbp = $param_builder->getFbp(); } } return self::$cached_fbp; } /** * Initializes the CAPI server side Parameter Builder and sets cookies as needed. */ public function param_builder_server_setup() { try { if ( ! (bool) apply_filters( 'facebook_for_woocommerce_integration_pixel_enabled', true ) ) { return; } $param_builder = self::get_param_builder(); // When signals are held, still run ParamBuilder so it can generate // attribution IDs, but do not write cookies until signals are released. if ( FacebookSignalsState::is_held() ) { $fbc = self::get_fbc(); $fbp = self::get_fbp(); if ( ! empty( $fbc ) ) { FacebookSignalsState::set_attribution_data( 'fbc', $fbc ); } if ( ! empty( $fbp ) ) { FacebookSignalsState::set_attribution_data( 'fbp', $fbp ); } foreach ( $param_builder->getCookiesToSet() as $cookie ) { if ( '_fbp' === $cookie->name ) { FacebookSignalsState::set_attribution_data( 'fbp_domain', $cookie->domain ); } elseif ( '_fbc' === $cookie->name ) { FacebookSignalsState::set_attribution_data( 'fbc_domain', $cookie->domain ); } } } else { foreach ( $param_builder->getCookiesToSet() as $cookie ) { $this->set_param_builder_cookie( $cookie ); } } } catch ( \Throwable $exception ) { Logger::log( 'Error setting up server side CAPI Parameter Builder: ' . $exception->getMessage(), array(), array( 'should_send_log_to_meta' => true, 'should_save_log_in_woocommerce' => true, 'woocommerce_log_level' => \WC_Log_Levels::ERROR, ) ); } } /** * Writes one cookie the CAPI Parameter Builder asked for. * * Kept apart from param_builder_server_setup() so tests can record cookie writes, which * the CLI SAPI that PHPUnit runs under cannot observe. * * @since 3.7.9 * * @param object $cookie a cookie from ParamBuilder::getCookiesToSet(). */ protected function set_param_builder_cookie( $cookie ) { if ( headers_sent() ) { return; } setcookie( $cookie->name, $cookie->value, time() + $cookie->max_age, '/', $cookie->domain ); } /** * Determines whether the Pixel should be enabled. * * @since 2.2.0 * * @return bool */ private function is_pixel_enabled() { if ( null === $this->is_pixel_enabled ) { /** * Filters whether the Pixel should be enabled. * * @param bool $enabled default true */ $this->is_pixel_enabled = (bool) apply_filters( 'facebook_for_woocommerce_integration_pixel_enabled', true ); } return $this->is_pixel_enabled; } /** * Add events tracker hooks. * * @since 2.2.0 */ private function add_hooks() { // inject Pixel add_action( 'wp_head', array( $this, 'inject_base_pixel' ) ); add_action( 'wp_footer', array( $this, 'inject_base_pixel_noscript' ) ); // set up CAPI Param Builder libraries add_action( 'wp_enqueue_scripts', array( $this, 'param_builder_client_setup' ) ); // ViewContent for individual products add_action( 'woocommerce_after_single_product', array( $this, 'inject_view_content_event' ) ); add_action( 'woocommerce_after_single_product', array( $this, 'maybe_inject_search_event' ) ); // ViewCategory events add_action( 'woocommerce_after_shop_loop', array( $this, 'inject_view_category_event' ) ); // Search events add_action( 'pre_get_posts', array( $this, 'inject_search_event' ) ); add_filter( 'woocommerce_redirect_single_search_result', array( $this, 'maybe_add_product_search_event_to_session' ) ); // AddToCart events add_action( 'woocommerce_add_to_cart', array( $this, 'inject_add_to_cart_event' ), 40, 4 ); // AddToCart while AJAX is enabled (Classic WooCommerce) add_action( 'woocommerce_ajax_added_to_cart', array( $this, 'add_filter_for_add_to_cart_fragments' ) ); // AddToCart for WooCommerce Blocks (Store API) if ( did_action( 'woocommerce_blocks_loaded' ) ) { $this->register_store_api_endpoint_data(); } else { add_action( 'woocommerce_blocks_loaded', array( $this, 'register_store_api_endpoint_data' ) ); } // AddToCart while using redirect to cart page if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add', 'no' ) ) { add_action( 'wp_head', array( WC_Facebookcommerce_Utils::class, 'print_deferred_events' ) ); add_action( 'shutdown', array( WC_Facebookcommerce_Utils::class, 'save_deferred_events' ) ); } // InitiateCheckout events add_action( 'woocommerce_after_checkout_form', array( $this, 'inject_initiate_checkout_event' ) ); // InitiateCheckout events for checkout block. add_action( 'woocommerce_blocks_checkout_enqueue_data', array( $this, 'inject_initiate_checkout_event' ) ); // Purchase and Subscribe events add_action( 'woocommerce_new_order', array( $this, 'inject_purchase_event' ), 10, 2 ); add_action( 'woocommerce_process_shop_order_meta', array( $this, 'inject_purchase_event' ), 20 ); add_action( 'woocommerce_checkout_update_order_meta', array( $this, 'inject_purchase_event' ), 30 ); add_action( 'woocommerce_thankyou', array( $this, 'inject_purchase_event' ), 40 ); // Orders created without items are reported at the end of the request, once the // integration that created them has added items and totals. add_action( 'shutdown', array( $this, 'inject_deferred_purchase_events' ), 5 ); // Offline Purchase events, reported once a point-of-sale order is paid. add_action( 'woocommerce_order_status_changed', array( $this, 'inject_offline_purchase_event_on_status_change' ), 10 ); // Lead events through Contact Form 7 / WPForms. add_action( 'wpcf7_mail_sent', array( $this, 'track_cf7_lead_event' ), 10, 1 ); add_filter( 'wpcf7_feedback_response', array( $this, 'inject_cf7_lead_event_pixel_code' ), 10, 2 ); add_action( 'wp_footer', array( $this, 'inject_cf7_lead_event_listener' ), 20 ); add_action( 'wpforms_process_complete', array( $this, 'track_wpforms_lead_event' ), 20, 3 ); add_filter( 'wpforms_ajax_submit_success_response', array( $this, 'inject_wpforms_lead_event_ajax' ), 20, 3 ); add_filter( 'wpforms_ajax_submit_redirect', array( $this, 'inject_wpforms_lead_event_ajax' ), 20, 3 ); add_action( 'wp_footer', array( $this, 'inject_wpforms_ajax_listener' ), 20 ); // New subscription-generated orders must not inherit Purchase tracking flags. add_filter( 'wc_subscriptions_renewal_order_data', array( $this, 'exclude_purchase_tracking_meta_from_renewal_orders' ), 10, 3 ); add_filter( 'wc_subscriptions_resubscribe_order_data', array( $this, 'exclude_purchase_tracking_meta_from_renewal_orders' ), 10, 3 ); add_filter( 'wc_subscriptions_parent_data', array( $this, 'exclude_purchase_tracking_meta_from_renewal_orders' ), 10, 3 ); // Flush pending events on shutdown add_action( 'shutdown', array( $this, 'send_pending_events' ) ); } /** * Prints the base JavaScript pixel code * * phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped */ public function inject_base_pixel() { if ( $this->is_pixel_enabled() && ! $this->is_pos_page_request() ) { echo $this->pixel->pixel_base_code(); $this->inject_page_view_event(); } } /** * Prints the base