Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
10.00% covered (danger)
10.00%
3 / 30
0.00% covered (danger)
0.00%
0 / 2
CRAP
n/a
0 / 0
wpcomsh_get_site_creation_timestamp
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
72
wpcomsh_featured_image_in_email_default
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
4.12
1<?php
2/**
3 * Featured Image in Email default setting for WordPress.com sites.
4 *
5 * @package wpcomsh
6 */
7
8/**
9 * Get the site creation timestamp via API request.
10 *
11 * @return int The site creation date as a Unix timestamp or 0 for default fallback.
12 */
13function wpcomsh_get_site_creation_timestamp() {
14    $default_timestamp = 0;
15
16    // Check if Jetpack is connected
17    if ( ! class_exists( 'Jetpack' ) || ! Jetpack::is_connection_ready() ) {
18        return $default_timestamp;
19    }
20
21    $transient_key             = 'wpcomsh_featured_image_site_creation';
22    $cached_creation_timestamp = get_transient( $transient_key );
23
24    if ( false !== $cached_creation_timestamp ) {
25        return $cached_creation_timestamp;
26    }
27
28    // Make authenticated API request to get site creation date
29    $site_id = Automattic\Jetpack\Connection\Manager::get_site_id( true );
30
31    if ( ! $site_id ) {
32        return $default_timestamp;
33    }
34
35    $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_blog(
36        sprintf( '/sites/%d?force=wpcom&options=created_at', $site_id ),
37        '1.1'
38    );
39
40    if ( is_wp_error( $response ) ) {
41        return $default_timestamp;
42    }
43
44    $body      = wp_remote_retrieve_body( $response );
45    $site_data = json_decode( $body );
46
47    if ( ! $site_data || ! isset( $site_data->options->created_at ) ) {
48        return $default_timestamp;
49    }
50
51    $site_creation_timestamp = strtotime( $site_data->options->created_at );
52
53    // Cache the result for 24 hours
54    set_transient( $transient_key, $site_creation_timestamp, DAY_IN_SECONDS );
55
56    return $site_creation_timestamp;
57}
58
59/**
60 * Set the default value for wpcom_featured_image_in_email.
61 * For Atomic sites created after May 2, 2025, default to true.
62 *
63 * @return bool The conditional default value.
64 */
65function wpcomsh_featured_image_in_email_default() {
66    $site_creation_timestamp = wpcomsh_get_site_creation_timestamp();
67
68    if ( $site_creation_timestamp ) {
69        // Check if site was created after May 2, 2025
70        $cutoff_timestamp = strtotime( '2025-05-02' );
71        if ( $site_creation_timestamp > $cutoff_timestamp ) {
72            return true;
73        }
74    }
75
76    // Fallback: return false for older sites or if we can't determine
77    return false;
78}
79
80// Hook to default_option_* filter for when option doesn't exist
81add_filter( 'default_option_wpcom_featured_image_in_email', 'wpcomsh_featured_image_in_email_default' );