300, 'display' => 'ADCELL: alle 5 Minuten', ); return $schedules; } public static function capture_order_object( $order ) { if ( $order instanceof WC_Order ) { self::ensure_events( $order ); } } public static function capture_order( $order_id ) { $order = wc_get_order( $order_id ); if ( $order ) { self::ensure_events( $order ); } } public static function handle_order( $order_id ) { $order = wc_get_order( $order_id ); if ( ! $order ) { return; } if ( self::ensure_events( $order ) && self::reportable( $order ) ) { self::release( $order->get_id(), 'Danke-Seite, Status ' . $order->get_status() ); } } public static function reportable( $order ) { return ! $order->has_status( array( 'pending', 'failed', 'cancelled', 'refunded', 'checkout-draft' ) ); } public static function handle_status_change( $order_id, $from, $to, $order = null ) { if ( ! $order instanceof WC_Order ) { $order = wc_get_order( $order_id ); } if ( $order && self::reportable( $order ) ) { self::release( $order->get_id(), 'Statuswechsel ' . $from . ' -> ' . $to ); } } private static function release( $order_id, $trigger ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $released = $wpdb->query( $wpdb->prepare( "UPDATE `{$table}` SET status = 'pending', next_try = %s WHERE order_id = %d AND status = 'held'", current_time( 'mysql', true ), $order_id ) ); if ( $released ) { RoleWcAdcell::log( 'Conversion freigegeben', array( 'order' => $order_id, 'ausloeser' => $trigger, 'events' => (int) $released ) ); } $events = self::events_for_order( $order_id ); if ( ! $events ) { return; } foreach ( $events as $event ) { self::$due[ (int) $event['id'] ] = true; } if ( ! self::$flush_registered ) { self::$flush_registered = true; add_action( 'shutdown', array( __CLASS__, 'flush' ), 99 ); } } public static function flush() { if ( ! self::$due ) { return; } if ( function_exists( 'fastcgi_finish_request' ) ) { fastcgi_finish_request(); } $ids = array_keys( self::$due ); self::$due = array(); foreach ( $ids as $id ) { $row = self::claim( $id ); if ( $row ) { self::send( $row ); } } } public static function ensure_events( $order ) { global $wpdb; $existing = self::events_for_order( $order->get_id() ); if ( $existing ) { return $existing; } $program_id = (string) get_option( 'roleWcAdcellProgramId' ); if ( '' === $program_id ) { return array(); } if ( ! RoleWcAdcellBidStore::has_consent() ) { RoleWcAdcell::log( 'Conversion uebersprungen: kein Consent', array( 'order' => $order->get_id() ) ); return array(); } $attribution = RoleWcAdcellBidStore::resolve_attribution(); $signed = (string) $attribution['signed']; if ( '' !== $signed && null === RoleWcAdcellBidStore::parse_signed_click( $signed, time() ) ) { RoleWcAdcell::log( 'Signierter Klick abgelaufen oder ungueltig, sende ohne', array( 'order' => $order->get_id() ) ); $signed = ''; } $vouchers = RoleWcAdcellOrderAmounts::voucher_codes( $order ); $now = current_time( 'mysql', true ); $table = self::table(); foreach ( self::build_events( $order ) as $event ) { $suppress = $wpdb->suppress_errors( true ); $wpdb->insert( $table, array( 'order_id' => $order->get_id(), 'event_id' => $event['event_id'], 'referenz' => $event['referenz'], 'betrag' => $event['betrag'], 'product_ids' => $event['product_ids'], 'quantities' => $event['quantities'], 'product_count' => $event['product_count'], 'bid' => (string) $attribution['bid'], 'ck' => (string) $attribution['ck'], 'vck' => (string) $attribution['view'], 'referer' => (string) $attribution['referer'], 's2s' => $signed, 'vouchers' => wp_json_encode( array_values( $vouchers ) ), 'status' => 'held', 'attempts' => 0, 'next_try' => $now, 'created_at' => $now, ) ); $wpdb->suppress_errors( $suppress ); } RoleWcAdcell::log( 'Conversion eingefroren', array( 'order' => $order->get_id(), 'zuordnung' => '' !== $signed ? 'signiert' : ( $attribution['ck'] ? 'ck' : ( $attribution['bid'] ? 'bid' : ( $attribution['view'] ? 'nur view' : 'keine' ) ) ), ) ); return self::events_for_order( $order->get_id() ); } public static function build_events( $order ) { $products = RoleWcAdcellOrderAmounts::product_amounts( $order ); $fallback = self::default_event_id( $order ); $by_event = array(); $by_category = RoleWcAdcell::option_bool( 'roleWcAdcellCategoryEvents', false ); foreach ( $products as $product ) { $event_id = $by_category ? RoleWcAdcellOrderAmounts::category_event_id( $product['product_id'] ) : ''; if ( '' === $event_id ) { $event_id = $fallback; } if ( '' === $event_id || '0' === $event_id ) { continue; } $by_event[ $event_id ][] = $product; } $events = array(); $referenz = (string) $order->get_order_number(); foreach ( $by_event as $event_id => $items ) { $amount = 0.0; $ids = array(); $quantities = array(); $count = 0; foreach ( $items as $item ) { $amount += $item['amount']; $ids[] = $item['product_id']; $quantities[] = $item['quantity']; $count += $item['quantity']; } $amount = round( $amount, 2 ); if ( $amount <= 0 ) { RoleWcAdcell::log( 'Conversion uebersprungen: Betrag <= 0', array( 'order' => $order->get_id(), 'eventid' => $event_id, 'betrag' => $amount ) ); continue; } $events[] = array( 'event_id' => (string) $event_id, 'referenz' => $referenz, 'betrag' => number_format( $amount, 2, '.', '' ), 'product_ids' => implode( ',', $ids ), 'quantities' => implode( ',', $quantities ), 'product_count' => $count, ); } return $events; } private static function default_event_id( $order ) { $default = (string) get_option( 'roleWcAdcellEventId' ); if ( ! RoleWcAdcell::option_bool( 'roleWcAdcellCustomerEvents', false ) ) { return $default; } $option = RoleWcAdcellOrderAmounts::is_new_customer( $order ) ? 'roleWcAdcellEventIdNewCustomer' : 'roleWcAdcellEventIdOldCustomer'; $event_id = (string) get_option( $option ); return ( '' !== $event_id && '0' !== $event_id ) ? $event_id : $default; } public static function process_queue() { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM `{$table}` WHERE status IN ('pending','sending') AND attempts < %d AND next_try <= %s ORDER BY id ASC LIMIT 25", self::MAX_ATTEMPTS, current_time( 'mysql', true ) ) ); foreach ( $ids as $id ) { $row = self::claim( (int) $id ); if ( $row ) { self::send( $row ); } } } private static function claim( $id ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $claimed = $wpdb->query( $wpdb->prepare( "UPDATE `{$table}` SET status = 'sending', attempts = attempts + 1, next_try = %s WHERE id = %d AND status IN ('pending','sending') AND attempts < %d AND next_try <= %s", gmdate( 'Y-m-d H:i:s', time() + self::TIMEOUT + 60 ), $id, self::MAX_ATTEMPTS, current_time( 'mysql', true ) ) ); if ( 1 !== (int) $claimed ) { return null; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$table}` WHERE id = %d", $id ), ARRAY_A ); return is_array( $row ) ? $row : null; } private static function send( array $row ) { global $wpdb; if ( ! self::has_attribution( $row ) ) { self::finish( (int) $row['id'], 'skipped', 0, 'ohne Zuordnung' ); RoleWcAdcell::log( 'S2S uebersprungen: keine belegte Zuordnung', array( 'referenz' => $row['referenz'] ) ); return; } $url = self::build_url( $row ); $attempts = (int) $row['attempts']; $response = wp_remote_get( $url, array( 'timeout' => self::TIMEOUT, 'redirection' => 2, 'user-agent' => 'ADCELL-WordPress/' . ROLE_WC_ADCELL_VERSION, ) ); if ( is_wp_error( $response ) ) { self::retry( (int) $row['id'], $attempts, 0, $response->get_error_message() ); RoleWcAdcell::log( 'S2S fehlgeschlagen', array( 'referenz' => $row['referenz'], 'error' => $response->get_error_message(), 'url' => $url ) ); return; } $code = (int) wp_remote_retrieve_response_code( $response ); if ( $code >= 200 && $code < 400 ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->update( self::table(), array( 'status' => 'sent', 'attempts' => $attempts, 'http_code' => $code, 'last_error' => '', 'sent_at' => current_time( 'mysql', true ), ), array( 'id' => (int) $row['id'] ) ); RoleWcAdcell::log( 'S2S gesendet', array( 'referenz' => $row['referenz'], 'eventid' => $row['event_id'], 'betrag' => $row['betrag'], 'status' => $code, 'url' => $url ) ); return; } self::retry( (int) $row['id'], $attempts, $code, 'HTTP ' . $code ); RoleWcAdcell::log( 'S2S abgelehnt', array( 'referenz' => $row['referenz'], 'status' => $code, 'url' => $url ) ); } public static function has_attribution( array $row ) { foreach ( array( 'ck', 'bid', 'vck', 's2s' ) as $column ) { if ( isset( $row[ $column ] ) && '' !== (string) $row[ $column ] ) { return true; } } return false; } public static function conversion_query( array $row, $s2s = false ) { global $wp_version; $created = isset( $row['created_at'] ) ? strtotime( (string) $row['created_at'] . ' UTC' ) : 0; $query = http_build_query( array( 's2s' => $s2s ? 1 : 0, 's' => 'wordpress', 'sv' => $wp_version, 'v' => ROLE_WC_ADCELL_VERSION, 'pid' => get_option( 'roleWcAdcellProgramId' ), 'eventid' => $row['event_id'], 'referenz' => $row['referenz'], 'betrag' => $row['betrag'], ) ); return $query . self::voucher_params( $row['vouchers'] ) . '&cv=' . ( $created ? $created : 0 ); } public static function voucher_params( $vouchers ) { $codes = json_decode( (string) $vouchers, true ); if ( ! is_array( $codes ) || ! $codes ) { return '&vouchers%5B%5D='; } $params = ''; foreach ( $codes as $code ) { $params .= '&vouchers%5B%5D=' . rawurlencode( (string) $code ); } return $params; } public static function build_url( array $row ) { $url = self::ENDPOINT . '?' . self::conversion_query( $row, true ); $created = isset( $row['created_at'] ) ? strtotime( (string) $row['created_at'] . ' UTC' ) : time(); $signed = isset( $row['s2s'] ) ? RoleWcAdcellBidStore::parse_signed_click( (string) $row['s2s'], (int) $created ) : null; $params = array(); foreach ( array( 'bid', 'ck', 'vck', 'referer' ) as $column ) { if ( $signed && ( 'bid' === $column || 'referer' === $column ) ) { continue; } if ( '' !== (string) $row[ $column ] ) { $params[ $column ] = $row[ $column ]; } } if ( $signed ) { $params = array_merge( $params, array_filter( $signed, 'is_string' ) ); } return $params ? $url . '&' . http_build_query( $params ) : $url; } private static function retry( $id, $attempts, $code, $error ) { global $wpdb; $failed = ( $attempts >= self::MAX_ATTEMPTS ); $delay = 300 * pow( 2, max( 0, $attempts - 1 ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->update( self::table(), array( 'status' => $failed ? 'failed' : 'pending', 'attempts' => $attempts, 'http_code' => (int) $code, 'last_error' => substr( (string) $error, 0, 500 ), 'next_try' => gmdate( 'Y-m-d H:i:s', time() + $delay ), ), array( 'id' => (int) $id ) ); } private static function finish( $id, $status, $code, $error ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->update( self::table(), array( 'status' => $status, 'http_code' => (int) $code, 'last_error' => substr( (string) $error, 0, 500 ), ), array( 'id' => (int) $id ) ); } public static function table() { global $wpdb; return $wpdb->prefix . 'adcell_conversions'; } public static function events_for_order( $order_id ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (array) $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$table}` WHERE order_id = %d ORDER BY id ASC", (int) $order_id ), ARRAY_A ); } public static function stats() { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( "SELECT status, COUNT(*) AS anzahl FROM `{$table}` GROUP BY status", ARRAY_A ); $stats = array( 'held' => 0, 'sent' => 0, 'pending' => 0, 'sending' => 0, 'failed' => 0, 'skipped' => 0 ); foreach ( (array) $rows as $row ) { $stats[ $row['status'] ] = (int) $row['anzahl']; } return $stats; } public static function recent( $limit = 20 ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (array) $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$table}` ORDER BY id DESC LIMIT %d", (int) $limit ), ARRAY_A ); } }