Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions php/class-admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -487,17 +487,25 @@ protected function save_settings( $submission, $data ) {
$this->add_admin_notice( 'error_notice', __( 'Settings updated successfully', 'cloudinary' ), 'success' );

$analytics = $this->plugin->get_component( 'analytics' );
if ( $analytics ) {
$analytics->track(
'settings_saved',
'settings',
null,
array(
'page' => $submission,
'changed_keys' => $changed_keys,
)
if ( $analytics && $analytics->is_enabled() ) {
$params = array(
'page' => $submission,
'changed_keys' => $changed_keys,
);

// Saves of a feature page carry the full feature
// configuration as it stands after the save, flat like
// `feature_config_snapshot`, so every such save is a
// baseline and the changed keys show what was deliberately
// overridden. Other pages can't change it, so it is left
// out. Only allowlisted settings are included: secrets and
// free text never leave the site.
if ( isset( Analytics::FEATURE_SETTINGS[ $submission ] ) ) {
$params = array_merge( $analytics->get_feature_snapshot(), $params );
}

$analytics->track( 'settings_saved', 'settings', null, $params );

if ( 'gallery' === $submission ) {
$this->track_gallery_configured( $analytics, $data );
}
Expand Down
249 changes: 249 additions & 0 deletions php/class-analytics.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ public function __construct( Plugin $plugin ) {
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_script_data' ) );
add_action( 'admin_init', array( $this, 'maybe_send_smoke_event' ) );
add_action( 'admin_init', array( $this, 'maybe_send_pending_activation' ) );
add_action( 'admin_init', array( $this, 'maybe_send_feature_snapshot' ) );
add_action( 'cloudinary_uploaded_asset', array( $this, 'maybe_first_api_consumption' ), 10, 2 );
}

Expand All @@ -75,6 +76,251 @@ public function __construct( Plugin $plugin ) {
const LAST_ACTIVE = '_cloudinary_last_active';
const FIRST_API_FLAG = '_cloudinary_first_api_emitted';

/**
* Option key marking the feature-config snapshot as sent (per cloud_name).
*/
const FEATURE_SNAPSHOT_FLAG = '_cloudinary_feature_snapshot_emitted';

/**
* Allowlist of feature settings whose values may be emitted, per settings
* page, mapped to how each value is normalised before it leaves the site.
*
* Anything not listed here is never sent as a value. Free-text fields are
* reduced to a presence boolean, since they can hold public IDs, overlay
* text or URLs.
*
* - bool: `on`/`off` toggle → true/false.
* - int: numeric field → int.
* - enum: select/radio → the value when it is one of the setting's
* own options, `other` when it isn't.
* - css_length: free-text CSS length → the length, lowercased, or dropped
* when it is anything else.
* - presence: free text → whether it is non-empty.
* - crops: per-size crop map → number of sizes with a custom crop.
* - derived: not sent as stored; get_feature_snapshot() works the value
* out from other settings.
*/
const FEATURE_SETTINGS = array(
'image_settings' => array(
'image_delivery' => 'bool',
'image_optimization' => 'bool',
'image_format' => 'enum',
'image_quality' => 'enum',
'image_freeform' => 'presence',
'svg_support' => 'bool',
'crop_sizes' => 'crops',
),
'lazy_loading' => array(
'use_lazy_load' => 'bool',
'lazy_threshold' => 'css_length',
'lazy_placeholder' => 'enum',
'lazy_animate' => 'bool',
'dpr' => 'enum',
),
'responsive' => array(
'enable_breakpoints' => 'bool',
'pixel_step' => 'int',
'breakpoints' => 'derived',
'max_width' => 'int',
'min_width' => 'int',
),
'video_settings' => array(
'video_delivery' => 'bool',
'video_player' => 'enum',
'adaptive_streaming' => 'bool',
'adaptive_streaming_mode' => 'enum',
'video_controls' => 'bool',
'video_loop' => 'bool',
'video_autoplay_mode' => 'enum',
'video_optimization' => 'bool',
'video_format' => 'enum',
'video_quality' => 'enum',
'video_freeform' => 'presence',
),
);

/**
* Normalises a feature setting value for emission.
*
* @param string $page The settings page slug the setting belongs to.
* @param string $key The setting slug.
* @param mixed $value The raw setting value.
*
* @return bool|int|string|null The normalised value, or null when the
* setting is not allowlisted for that page or
* its value is missing or unusable.
*/
public function normalize_feature_value( $page, $key, $value ) {
if ( ! isset( self::FEATURE_SETTINGS[ $page ][ $key ] ) || null === $value ) {
return null;
}

switch ( self::FEATURE_SETTINGS[ $page ][ $key ] ) {
case 'bool':
return 'on' === $value || true === $value;
case 'int':
return is_numeric( $value ) ? (int) $value : null;
case 'css_length':
$value = is_string( $value ) ? trim( $value ) : '';

$value = strtolower( $value );

return preg_match( '/^\d+(\.\d+)?(px|%|r?em|vh|vw)?$/', $value ) ? $value : null;
case 'presence':
return is_string( $value ) && '' !== trim( $value );
case 'crops':
// Each size maps to '' (default crop), '--' (crop disabled) or
// a custom transformation string.
if ( ! is_array( $value ) ) {
return 0;
}

return count(
array_filter(
$value,
static function ( $crop ) {
return is_string( $crop ) && '' !== trim( $crop ) && '--' !== $crop;
}
)
);
case 'enum':
// Select and radio values are only sanitised as text, and
// filters can return anything, so only known options are sent.
if ( ! is_scalar( $value ) ) {
return null;
}
$options = $this->plugin->settings->get_setting( $key )->get_param( 'options' );

return is_array( $options ) && array_key_exists( (string) $value, $options ) ? (string) $value : 'other';
default:
return null;
}
}

/**
* Emits the one-time `feature_config_snapshot` adoption baseline.
*
* Captures the full state of the delivery features, including those left
* at their defaults, for sites that never save their settings. Sent on the
* first admin page load by an administrator once the site is connected,
* then again whenever the connected cloud_name changes (only the last one
* is kept, so switching A → B → A sends three). That covers wizard
* setups, sites connected through the `CLOUDINARY_CONNECTION_STRING`
* constant, existing installs upgrading to this version, and account
* switches.
*
* The `trigger` param tells the two cases apart:
*
* - `setup`: the site was installed, or seen unconnected, by a version
* that sends the snapshot, then connected (or switched
* account). The flag holds an empty string until then.
* - `upgrade`: the site was already connected the first time a version
* that sends the snapshot ran, so the flag was never set.
*
* A site connected through the constant before any admin page loads is
* only recognised as a setup on a fresh install. A reinstall after the
* uninstall clean-up (which keeps the plugin's DB version) and subsites of
* a network activation report `upgrade` instead. So can a site whose
* unconnected admin load writes the "not set up" marker while another
* admin load, already connected, is claiming the send: that request
* cached the flag as missing, so its add_option() overwrites the marker.
*
* @return void
*/
public function maybe_send_feature_snapshot() {
// `admin_init` also runs for admin-ajax requests, including logged-out
// ones, and for non-admin users visiting their profile.
if ( wp_doing_ajax() || ! Utils::user_can( 'analytics', 'manage_options' ) ) {
return;
}

// Autoloaded, so once the flag is stored this check costs no query.
// It isn't stored while a connected site has analytics disabled, so
// the snapshot is still sent with the right trigger once they are
// enabled: each admin load then runs one option query.
$sent = get_option( self::FEATURE_SNAPSHOT_FLAG );

$connect = $this->plugin->get_component( 'connect' );
$cloud = $connect && $connect->is_connected() ? (string) $connect->get_cloud_name() : '';
if ( '' === $cloud ) {
if ( false === $sent ) {
// Remembers the site as not yet set up, so connecting it later
// counts as a setup rather than an upgrade.
add_option( self::FEATURE_SNAPSHOT_FLAG, '', '', true );
}
return;
}

if ( $sent === $cloud || ! $this->is_enabled() ) {
return;
}

// Only one of several concurrent requests sends: add_option() upserts
// and update_option() updates, and a request writing the same cloud
// name as an earlier one changes no row, so it gets false back.
$claimed = false === $sent
? add_option( self::FEATURE_SNAPSHOT_FLAG, $cloud, '', true )
: update_option( self::FEATURE_SNAPSHOT_FLAG, $cloud, true );
if ( ! $claimed ) {
return;
}

$params = $this->get_feature_snapshot();
$params['trigger'] = false === $sent ? 'upgrade' : 'setup';
Comment on lines +261 to +269

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: In one race, trigger can be upgrade when it should be setup. Request A reads the flag as missing, so its notoptions cache marks the flag as missing. Then request B (still unconnected) writes ''. Then A, now connected, calls add_option(). add_option() does not check again because notoptions has the flag, so the INSERT ... ON DUPLICATE KEY UPDATE replaces '', returns true, and A sends trigger: upgrade. This needs a concurrent unconnected admin load at the moment of connection, so it is rare. Add this case to the list of known limits in the docblock at L212-223.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, confirmed. It's rare and only mislabels the trigger (still a single snapshot), so I've added it to the known limits in the docblock (9051498).


$this->track( 'feature_config_snapshot', 'features', null, $params );
}

/**
* Reads the current, normalised value of every allowlisted feature setting.
*
* @return array
*/
public function get_feature_snapshot() {
$snapshot = array();
foreach ( self::FEATURE_SETTINGS as $page => $settings ) {
foreach ( array_keys( $settings ) as $key ) {
$value = $this->normalize_feature_value( $page, $key, $this->plugin->settings->get_value( $key ) );
if ( null !== $value ) {
$snapshot[ $key ] = $value;
}
}
}

// "Max images" is only ever what the settings page derives from the
// other responsive fields, and is stored only once that page is saved.
$snapshot['breakpoints'] = $this->get_breakpoint_count();

return $snapshot;
}

/**
* Counts the responsive image widths, as the settings page shows them in
* "Max images" (see `breakpoints-preview.js`): from the max width down to
* the min width, one image per breakpoint distance.
*
* @return int
*/
public function get_breakpoint_count() {
$settings = $this->plugin->settings;
$max = (int) $settings->get_value( 'max_width' );
$min = (int) $settings->get_value( 'min_width' );
$step = (int) $settings->get_value( 'pixel_step' );

// The same fallbacks as the settings page.
if ( $max < 1 ) {
$max = (int) $this->plugin->get_component( 'media' )->default_max_width();
}
if ( $min < 1 ) {
$min = 100;
}
if ( $step < 1 ) {
$step = 50;
}

return $max < $min ? 1 : 1 + (int) floor( ( $max - $min ) / $step );
}

/**
* Records the activation type on plugin activation (funnel step 1).
*
Expand All @@ -94,6 +340,9 @@ public static function stash_activation() {
if ( empty( $db_version ) ) {
$type = 'fresh_install';
$previous = null;
// A fresh install's first feature snapshot is a setup, even
// when it is connected through the constant from the start.
add_option( self::FEATURE_SNAPSHOT_FLAG, '', '', true );
} elseif ( version_compare( $db_version, $current, '<' ) ) {
$type = 'upgrade';
$previous = $db_version;
Expand Down
2 changes: 2 additions & 0 deletions php/class-deactivation.php
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,8 @@ protected function cleanup_options() {
'_cld_disable_http_upload',
Report::REPORT_KEY,
Media::GLOBAL_VIDEO_TRANSFORMATIONS,
Analytics::FIRST_API_FLAG,
Analytics::FEATURE_SNAPSHOT_FLAG,
self::CLEANING_KEY,
)
);
Expand Down
47 changes: 46 additions & 1 deletion tests/e2e/features-analytics.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const { test, expect } = require( './fixtures' );
/**
* Internal dependencies
*/
const { wpEvalFile } = require( './utils/wizard' );
const { wpCli, wpEvalFile } = require( './utils/wizard' );
const { fakeCloudinaryConnected } = require( './utils/connection' );
const {
clearAnalyticsEvents,
Expand Down Expand Up @@ -80,5 +80,50 @@ test.describe( 'Extensions & gallery analytics', () => {
expect( events.length ).toBe( 1 );
expect( events[ 0 ].layout ).toBe( 'expand' );
expect( events[ 0 ].media_count ).toBe( 2 );

// The gallery page can't change the feature configuration, so its
// settings_saved event doesn't carry it.
const saved = findAnalyticsEvents(
readAnalyticsEvents(),
'settings_saved'
);
expect( saved.length ).toBe( 1 );
expect( saved[ 0 ].page ).toBe( 'gallery' );
expect( saved[ 0 ] ).not.toHaveProperty( 'use_lazy_load' );
} );
} );

// @serial: the snapshot's one-time flag is shared by the whole site, so a
// parallel worker's admin load could send it into that worker's log instead.
// The sending rules are covered by PHPUnit; this checks the admin wiring.
test.describe( 'Feature config snapshot', { tag: '@serial' }, () => {
test.beforeEach( () => {
fakeCloudinaryConnected();
// Earlier admin loads already sent the snapshot for this cloud_name,
// so reset the one-time flag to simulate a fresh setup.
wpCli( [ 'option', 'delete', '_cloudinary_feature_snapshot_emitted' ] );
clearAnalyticsEvents();
} );

test( 'the first admin load once connected emits feature_config_snapshot once', async ( {
admin,
} ) => {
await admin.visitAdminPage( 'admin.php', 'page=cloudinary' );
await admin.visitAdminPage( 'admin.php', 'page=cloudinary' );

const events = findAnalyticsEvents(
readAnalyticsEvents(),
'feature_config_snapshot'
);
expect( events.length ).toBe( 1 );
expect( events[ 0 ].event_category ).toBe( 'features' );
// The flag was deleted while the site was connected, as on a site
// that was already set up before upgrading.
expect( events[ 0 ].trigger ).toBe( 'upgrade' );

// Default values are reported even though they were never saved.
expect( typeof events[ 0 ].use_lazy_load ).toBe( 'boolean' );
expect( typeof events[ 0 ].pixel_step ).toBe( 'number' );
expect( typeof events[ 0 ].image_format ).toBe( 'string' );
} );
} );
Loading
Loading