cardTitle Apple: the text beside the logo. Google: the top line. * header line -> subheader Apple: the small label above the title. Google: the * small line above the title. * pass title -> header The big line on both. * fields -> textModulesData Up to three, in the row under the title. * back sections -> linksModuleData Apple: the back of the pass. Google: Details. */ if (!defined('ABSPATH')) { exit; } class ATW_Bookly_Pass_Builder { /** * The API rejects more than three text modules and requires exactly these ids, in * this order. Verified against a live 400 response, which the API docs do not mention. */ const TEXT_MODULE_IDS = ['r1start', 'r1middle', 'r1end']; const MAX_TEXT_MODULES = 3; /** * logoUrl is effectively required: omitting it makes the API substitute its own * placeholder, which is itself unreachable and returns * "Image cannot be loaded ... logo-placeholder.png" with a 400. So an unset logo * falls back to the site icon. */ public static function logo(array $settings) { $value = isset($settings['logo_url']) ? trim((string) $settings['logo_url']) : ''; if ($value !== '') { return $value; } return ATW_Bookly_Settings::site_icon_url(); } /** * heroImage, despite being marked required in the API docs, is genuinely optional — a * pass without it is accepted — so it is omitted rather than substituted. A variation * for the booking's service wins over the main image. */ public static function hero(array $settings, array $booking) { $template = isset($settings['template']) ? $settings['template'] : ATW_Bookly_Template::defaults(); $key = isset($booking['hero_key']) ? (string) $booking['hero_key'] : ''; if ($key !== '' && !empty($template['hero_rules'])) { foreach ($template['hero_rules'] as $rule) { if ((string) $rule['type_id'] === $key && trim((string) $rule['url']) !== '') { return trim((string) $rule['url']); } } } return isset($settings['hero_image']) ? trim((string) $settings['hero_image']) : ''; } /** * Apple renders the pass text over the background colour, so a light background with * white text is unreadable. Pick black or white by perceived luminance (ITU-R BT.601) * rather than making the user get it right. */ public static function font_color($background) { $hex = ltrim((string) $background, '#'); if (strlen($hex) === 3) { $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; } if (strlen($hex) !== 6 || !ctype_xdigit($hex)) { return '#FFFFFF'; } $r = hexdec(substr($hex, 0, 2)); $g = hexdec(substr($hex, 2, 2)); $b = hexdec(substr($hex, 4, 2)); $luminance = (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255; return $luminance > 0.6 ? '#000000' : '#FFFFFF'; } public static function build(array $booking, array $settings) { $template = isset($settings['template']) ? ATW_Bookly_Template::normalize($settings['template']) : ATW_Bookly_Template::defaults(); $values = ATW_Bookly_Template::values($booking); $zone = ATW_Bookly_Template::zone($booking); $start = ATW_Bookly_Template::to_datetime($booking['booking_start'], $zone); $end = ATW_Bookly_Template::to_datetime($booking['booking_end'], $zone); // Business name: left blank, it is Bookly's company name (or the site name). $card_title = ATW_Bookly_Template::fill($template['business_name'], $values); if ($card_title === '') { $card_title = $values['business_name'] !== '' ? $values['business_name'] : (string) get_bloginfo('name'); } // The API needs a header; a title that fills in empty falls back to the service, // then to the business name, rather than sending a blank pass. $header = ATW_Bookly_Template::fill($template['title'], $values); if ($header === '') { $header = $values['service'] !== '' ? $values['service'] : $card_title; } $payload = [ 'cardTitle' => $card_title, 'header' => $header, 'logoUrl' => self::logo($settings), 'hexBackgroundColor' => $settings['background_color'], 'appleFontColor' => self::font_color($settings['background_color']), 'textModulesData' => self::text_modules($template['fields'], $values), 'linksModuleData' => self::links($template['back'], $values), ]; // Omitted when empty: Google and Apple both draw an empty label as a gap. $subheader = ATW_Bookly_Template::fill($template['header'], $values); if ($subheader !== '') { $payload['subheader'] = $subheader; } /** * "No barcode" means omitting the fields rather than sending an empty type: the * API treats an unrecognised barcodeType by clearing all three anyway, and * leaving them out keeps the payload honest. * * The value is the numeric booking id, which is always printable ASCII, so the * CODE_128 restriction on non-ASCII values cannot bite here. */ $barcode = isset($settings['barcode_type']) ? $settings['barcode_type'] : 'QR_CODE'; if ($barcode !== 'NONE') { $payload['barcodeType'] = $barcode; $payload['barcodeValue'] = (string) $booking['booking_id']; $payload['barcodeAltText'] = ''; } if ($start) { $payload['startDate'] = $start->format('c'); // The Wallet reminder before the appointment, unless it was switched off. if (!empty($template['reminder'])) { $payload['notificationValues'] = ['upcomingNotification']; } } if ($end) { $payload['endDate'] = $end->format('c'); } // Omitted entirely when unset, rather than sent empty — an empty string is a URL // the API will try, and fail, to load. $hero = self::hero($settings, $booking); if ($hero !== '') { $payload['heroImage'] = $hero; } /** * Adjust the pass payload before it is sent. * * @param array $payload * @param array $booking Normalised booking read from Bookly. * @param array $settings Saved plugin settings. */ $payload = apply_filters('atw_bookly_pass_payload', $payload, $booking, $settings); /** * Stamp the integration that created this pass, so admin analytics can tell * this plugin apart from every other WordPress site hitting the API. * * Set after the filter on purpose: a site's own filter may rebuild $payload * wholesale, and dropping the source would silently make its passes * unattributable. The API allowlists this value, so it cannot be forged * into some other integration's bucket either. */ $payload['source'] = 'bookly'; return $payload; } /** * The front fields, filled in. A field whose value comes out empty is dropped and the * rest close up, so the required ids are assigned by position after filtering. */ private static function text_modules(array $fields, array $values) { $rows = []; foreach ($fields as $field) { if (count($rows) >= self::MAX_TEXT_MODULES) { break; } $body = ATW_Bookly_Template::fill($field['value'], $values); if ($body === '') { continue; } $rows[] = [ 'id' => self::TEXT_MODULE_IDS[count($rows)], 'header' => ATW_Bookly_Template::fill($field['label'], $values), 'body' => $body, ]; } return $rows; } /** * The back sections. The API carries them all as links, telling them apart by the * URI's scheme, and silently drops any it cannot validate — so each is checked here * against the same rules first, and one that would be dropped is left out. * * text -> text: Apple: a plain back field. Google: a Details row. * phone -> tel: The API wants at least 7 digits, spaces, dashes or (). * email -> mailto: * address -> a Google Maps search link. The API only accepts geo: with coordinates * ("geo:lat,lng") and drops a geo: street address, so a maps https link * is the form that survives and opens a map on both wallets. * link -> https URL, with https:// added when no scheme was typed. */ private static function links(array $sections, array $values) { $defaults = [ 'text' => __('Info', 'addtowallet-for-bookly'), 'link' => __('Website', 'addtowallet-for-bookly'), 'phone' => __('Phone', 'addtowallet-for-bookly'), 'email' => __('Email', 'addtowallet-for-bookly'), 'address' => __('Address', 'addtowallet-for-bookly'), ]; $links = []; foreach ($sections as $section) { $type = in_array($section['type'], ATW_Bookly_Template::BACK_TYPES, true) ? $section['type'] : 'text'; $value = ATW_Bookly_Template::fill($section['value'], $values); if ($value === '') { continue; } $uri = self::uri($type, $value); if ($uri === '') { continue; } $label = ATW_Bookly_Template::fill($section['label'], $values); $links[] = [ 'id' => 'r' . (count($links) + 1), 'description' => $label !== '' ? $label : $defaults[$type], 'uri' => $uri, ]; } return $links; } /** One back section's URI, or '' when the API would reject it. */ private static function uri($type, $value) { switch ($type) { case 'phone': $number = trim(preg_replace('/[^\d+\s\-()]/', '', $value)); return preg_match('/^\+?[\d\s\-()]{7,}$/', $number) ? 'tel:' . $number : ''; case 'email': $email = sanitize_email($value); return is_email($email) ? 'mailto:' . $email : ''; case 'address': return 'https://www.google.com/maps/search/?api=1&query=' . rawurlencode($value); case 'link': $url = preg_match('#^[a-z][a-z0-9+.-]*://#i', $value) ? $value : 'https://' . $value; $url = esc_url_raw($url, ['http', 'https']); return ($url !== '' && filter_var($url, FILTER_VALIDATE_URL)) ? $url : ''; default: return 'text:' . $value; } } }