Changeset 3772670
- Timestamp:
- 10/29/2026 10:46:55 AM (3 weeks ago)
- Location:
- integrate-rybbit
- Files:
-
- 30 added
- 24 edited
- 1 copied
-
assets/screenshot-1.png (modified) ( previous)
-
assets/screenshot-2.png (modified) ( previous)
-
assets/screenshot-3.png (modified) ( previous)
-
assets/screenshot-4.png (modified) ( previous)
-
assets/screenshot-5.png (added)
-
assets/screenshot-6.png (added)
-
assets/screenshot-7.png (added)
-
assets/screenshot-8.png (added)
-
tags/1.8.0 (copied) (copied from integrate-rybbit/trunk )
-
tags/1.8.0/admin/class-integrate-rybbit-admin.php (modified) (9 diffs)
-
tags/1.8.0/admin/class-integrate-rybbit-dashboard.php (added)
-
tags/1.8.0/admin/css/dashboard.css (added)
-
tags/1.8.0/admin/css/settings.css (modified) (1 diff)
-
tags/1.8.0/admin/js/dashboard.js (added)
-
tags/1.8.0/admin/js/settings.js (modified) (2 diffs)
-
tags/1.8.0/blocks (added)
-
tags/1.8.0/blocks/optout (added)
-
tags/1.8.0/blocks/optout/block.json (added)
-
tags/1.8.0/blocks/optout/index.js (added)
-
tags/1.8.0/includes/class-integrate-rybbit-admin-ajax.php (modified) (3 diffs)
-
tags/1.8.0/includes/class-integrate-rybbit-api.php (added)
-
tags/1.8.0/includes/class-integrate-rybbit-options.php (modified) (7 diffs)
-
tags/1.8.0/includes/class-integrate-rybbit-optout.php (added)
-
tags/1.8.0/includes/class-integrate-rybbit-rest.php (added)
-
tags/1.8.0/integrate-rybbit.php (modified) (4 diffs)
-
tags/1.8.0/public/class-integrate-rybbit-public.php (modified) (3 diffs)
-
tags/1.8.0/public/css (added)
-
tags/1.8.0/public/css/rybbit-optout.css (added)
-
tags/1.8.0/public/js/rybbit-helpers.js (modified) (2 diffs)
-
tags/1.8.0/public/js/rybbit-optout.js (added)
-
tags/1.8.0/readme.txt (modified) (10 diffs)
-
tags/1.8.0/uninstall.php (modified) (2 diffs)
-
trunk/admin/class-integrate-rybbit-admin.php (modified) (9 diffs)
-
trunk/admin/class-integrate-rybbit-dashboard.php (added)
-
trunk/admin/css/dashboard.css (added)
-
trunk/admin/css/settings.css (modified) (1 diff)
-
trunk/admin/js/dashboard.js (added)
-
trunk/admin/js/settings.js (modified) (2 diffs)
-
trunk/blocks (added)
-
trunk/blocks/optout (added)
-
trunk/blocks/optout/block.json (added)
-
trunk/blocks/optout/index.js (added)
-
trunk/includes/class-integrate-rybbit-admin-ajax.php (modified) (3 diffs)
-
trunk/includes/class-integrate-rybbit-api.php (added)
-
trunk/includes/class-integrate-rybbit-options.php (modified) (7 diffs)
-
trunk/includes/class-integrate-rybbit-optout.php (added)
-
trunk/includes/class-integrate-rybbit-rest.php (added)
-
trunk/integrate-rybbit.php (modified) (4 diffs)
-
trunk/public/class-integrate-rybbit-public.php (modified) (3 diffs)
-
trunk/public/css (added)
-
trunk/public/css/rybbit-optout.css (added)
-
trunk/public/js/rybbit-helpers.js (modified) (2 diffs)
-
trunk/public/js/rybbit-optout.js (added)
-
trunk/readme.txt (modified) (10 diffs)
-
trunk/uninstall.php (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
-
integrate-rybbit/tags/1.8.0/admin/class-integrate-rybbit-admin.php
r3772488 r3772670 82 82 'rybbit_debounce' => array( 'Integrate_Rybbit_Options', 'sanitize_debounce' ), 83 83 'rybbit_tag' => array( 'Integrate_Rybbit_Options', 'sanitize_tag' ), 84 'rybbit_custom_events' => array( $this, 'sanitize_custom_events' ), 84 85 'rybbit_identify_mode' => array( $this, 'sanitize_identify_mode' ), 85 86 'rybbit_identify_userid_strategy' => array( $this, 'sanitize_userid_strategy' ), … … 96 97 'rybbit_replay_sampling' => array( $this, 'sanitize_sampling' ), 97 98 'rybbit_replay_slim_dom_options' => array( $this, 'sanitize_slim_dom_options' ), 99 'rybbit_api_key' => array( $this, 'sanitize_api_key' ), 100 'rybbit_api_url' => array( $this, 'sanitize_api_url' ), 101 'rybbit_dashboard_cache' => array( 'Integrate_Rybbit_Options', 'sanitize_cache_minutes' ), 102 'rybbit_dashboard_range' => array( 'Integrate_Rybbit_Options', 'sanitize_dashboard_range' ), 98 103 'rybbit_delete_data_on_uninstall' => array( 'Integrate_Rybbit_Options', 'sanitize_checkbox' ), 99 104 ); … … 211 216 212 217 /** 218 * Sanitize the API key. 219 * 220 * The field never shows the saved key. An empty field keeps the saved key. 221 * The "Remove key" checkbox deletes it. A key from wp-config.php is not 222 * saved here. 223 * 224 * @param mixed $value Raw value. 225 * @return string 226 */ 227 public function sanitize_api_key( $value ) { 228 $old = (string) get_option( 'rybbit_api_key', '' ); 229 230 // WordPress checks the settings nonce in options.php before it calls this method. 231 // phpcs:ignore WordPress.Security.NonceVerification.Missing 232 if ( ! empty( $_POST['rybbit_api_key_remove'] ) ) { 233 return ''; 234 } 235 236 $value = is_string( $value ) ? trim( $value ) : ''; 237 if ( '' === $value ) { 238 return $old; 239 } 240 241 if ( 1 !== preg_match( '/^[A-Za-z0-9_\-.~+\/=]{8,512}$/', $value ) ) { 242 $this->add_error( 243 'rybbit_api_key', 244 'rybbit_api_key_invalid', 245 __( 'The API key has invalid characters or a wrong length. It was not saved.', 'integrate-rybbit' ) 246 ); 247 return $old; 248 } 249 250 return $value; 251 } 252 253 /** 254 * Sanitize the API URL. It must use HTTPS because the API key is sent to it. 255 * 256 * @param mixed $value Raw value. 257 * @return string 258 */ 259 public function sanitize_api_url( $value ) { 260 $value = trim( is_string( $value ) ? $value : '' ); 261 if ( '' === $value ) { 262 return ''; 263 } 264 265 $url = untrailingslashit( esc_url_raw( $value, array( 'https', 'http' ) ) ); 266 if ( '' === $url || ! Integrate_Rybbit_Options::is_allowed_api_url( $url ) ) { 267 $this->add_error( 268 'rybbit_api_url', 269 'rybbit_api_url_invalid', 270 __( 'The API URL must be a valid HTTPS URL. HTTP works only for local hosts. It was not saved.', 'integrate-rybbit' ) 271 ); 272 return (string) $this->old_value( 'rybbit_api_url' ); 273 } 274 275 return $url; 276 } 277 278 /** 213 279 * Sanitize the script loading strategy. 214 280 * … … 228 294 public function sanitize_identify_mode( $value ) { 229 295 return in_array( $value, Integrate_Rybbit_Options::IDENTIFY_MODES, true ) ? $value : 'disabled'; 296 } 297 298 /** 299 * Sanitize the custom event rules. 300 * 301 * WordPress passes null when the form has no rule rows. That clears the list. 302 * 303 * @param mixed $value Raw rules from the form. 304 * @return array<int, array<string, mixed>> 305 */ 306 public function sanitize_custom_events( $value ) { 307 $rejected = 0; 308 $rules = Integrate_Rybbit_Options::normalize_custom_events( $value, $rejected ); 309 310 if ( $rejected > 0 ) { 311 $this->add_error( 312 'rybbit_custom_events', 313 'rybbit_custom_events_rejected', 314 sprintf( 315 /* translators: 1: number of dropped rules, 2: maximum number of rules */ 316 _n( 317 '%1$d custom event rule was not saved. A rule needs a valid selector, an event name and properties as "key=value" lines. You can save at most %2$d rules.', 318 '%1$d custom event rules were not saved. A rule needs a valid selector, an event name and properties as "key=value" lines. You can save at most %2$d rules.', 319 $rejected, 320 'integrate-rybbit' 321 ), 322 $rejected, 323 Integrate_Rybbit_Options::CUSTOM_EVENTS_MAX 324 ) 325 ); 326 } 327 328 return $rules; 230 329 } 231 330 … … 371 470 'privacy' => __( 'Privacy', 'integrate-rybbit' ), 372 471 'script' => __( 'Script Attributes', 'integrate-rybbit' ), 472 'events' => __( 'Custom Events', 'integrate-rybbit' ), 373 473 'replay' => __( 'Session Replay', 'integrate-rybbit' ), 474 'dashboard' => __( 'Dashboard', 'integrate-rybbit' ), 374 475 'maintenance' => __( 'Maintenance', 'integrate-rybbit' ), 375 476 'debug' => __( 'Debug', 'integrate-rybbit' ), … … 738 839 <?php esc_html_e( 'Preview of the identify payload that would be sent for the current logged-in user.', 'integrate-rybbit' ); ?> 739 840 <a href="#" class="rybbit-refresh-payload" role="button"><?php esc_html_e( 'Refresh preview', 'integrate-rybbit' ); ?></a> 841 </p> 842 </td> 843 </tr> 844 <tr> 845 <th scope="row"><?php esc_html_e( 'Visitor opt-out', 'integrate-rybbit' ); ?></th> 846 <td> 847 <p> 848 <?php 849 printf( 850 /* translators: 1: Shortcode, 2: Block name. */ 851 esc_html__( 'Let visitors turn the tracking off. Add the shortcode %1$s or the block %2$s to a page, for example your privacy policy.', 'integrate-rybbit' ), 852 '<code>[' . esc_html( Integrate_Rybbit_Optout::SHORTCODE ) . ']</code>', 853 '<strong>' . esc_html__( 'Rybbit Opt-out', 'integrate-rybbit' ) . '</strong>' 854 ); 855 ?> 856 </p> 857 <p class="description rybbit-description-wide"> 858 <?php 859 printf( 860 /* translators: %s: Name of the storage entry, for example "disable-rybbit". */ 861 esc_html__( 'The choice is saved in the browser of the visitor under %s. It applies to this website and this browser only.', 'integrate-rybbit' ), 862 '<code>disable-' . esc_html( Integrate_Rybbit_Optout::get_namespace() ) . '</code>' 863 ); 864 ?> 740 865 </p> 741 866 </td> … … 880 1005 881 1006 /** 1007 * Print the "Custom Events" tab. 1008 */ 1009 private function render_tab_events() { 1010 $rules = Integrate_Rybbit_Options::normalize_custom_events( Integrate_Rybbit_Options::get( 'rybbit_custom_events' ) ); 1011 ?> 1012 <p class="description rybbit-description-wide"> 1013 <?php 1014 printf( 1015 /* translators: %s: Rybbit function name. */ 1016 esc_html__( 'Send a custom event to Rybbit when a visitor clicks an element. The plugin calls %s for you. You do not need to write JavaScript.', 'integrate-rybbit' ), 1017 '<code>rybbit.event()</code>' 1018 ); 1019 ?> 1020 </p> 1021 <div class="rybbit-event-rules" data-rybbit-event-rules data-next-index="<?php echo esc_attr( (string) count( $rules ) ); ?>" data-max="<?php echo esc_attr( (string) Integrate_Rybbit_Options::CUSTOM_EVENTS_MAX ); ?>"> 1022 <p class="description" data-rybbit-event-empty<?php echo empty( $rules ) ? '' : ' hidden'; ?>><?php esc_html_e( 'No event rules yet.', 'integrate-rybbit' ); ?></p> 1023 <div class="rybbit-event-rule-list" data-rybbit-event-list> 1024 <?php 1025 foreach ( $rules as $index => $rule ) { 1026 $this->render_event_rule( (string) $index, $rule ); 1027 } 1028 ?> 1029 </div> 1030 <p> 1031 <button type="button" class="button" data-rybbit-event-add><?php esc_html_e( 'Add event rule', 'integrate-rybbit' ); ?></button> 1032 </p> 1033 <template data-rybbit-event-template> 1034 <?php $this->render_event_rule( '__INDEX__', array() ); ?> 1035 </template> 1036 </div> 1037 <div class="description rybbit-description-wide"> 1038 <p> 1039 <?php 1040 printf( 1041 /* translators: %d: Maximum number of rules. */ 1042 esc_html__( 'You can add up to %d rules. A rule also matches when the visitor clicks inside a matching element, for example on an icon in a button. Visitors with an excluded role do not send events.', 'integrate-rybbit' ), 1043 (int) Integrate_Rybbit_Options::CUSTOM_EVENTS_MAX 1044 ); 1045 ?> 1046 </p> 1047 <p> 1048 <?php 1049 printf( 1050 /* translators: 1: HTML attribute name, 2: HTML attribute name. */ 1051 esc_html__( 'You can also mark elements in your HTML with the %1$s and %2$s attributes. Rybbit reads them without this plugin.', 'integrate-rybbit' ), 1052 '<code>data-rybbit-event</code>', 1053 '<code>data-rybbit-prop-*</code>' 1054 ); 1055 ?> 1056 </p> 1057 </div> 1058 <?php 1059 } 1060 1061 /** 1062 * Print one custom event rule. 1063 * 1064 * The template for new rules uses the same markup with the placeholder index. 1065 * 1066 * @param string $index Row index. "__INDEX__" for the template. 1067 * @param array<string, mixed> $rule Stored rule. 1068 */ 1069 private function render_event_rule( $index, array $rule ) { 1070 $rule = wp_parse_args( 1071 $rule, 1072 array( 1073 'selector' => '', 1074 'event' => '', 1075 'props' => array(), 1076 ) 1077 ); 1078 1079 $base = 'rybbit_custom_events[' . $index . ']'; 1080 $id = 'rybbit_custom_events_' . $index; 1081 ?> 1082 <div class="rybbit-event-rule" data-rybbit-event-rule> 1083 <div class="rybbit-event-rule-fields"> 1084 <p> 1085 <label for="<?php echo esc_attr( $id . '_selector' ); ?>"><strong><?php esc_html_e( 'CSS selector', 'integrate-rybbit' ); ?></strong></label><br /> 1086 <input type="text" class="regular-text code rybbit-input-wide" id="<?php echo esc_attr( $id . '_selector' ); ?>" name="<?php echo esc_attr( $base . '[selector]' ); ?>" value="<?php echo esc_attr( (string) $rule['selector'] ); ?>" maxlength="<?php echo esc_attr( (string) Integrate_Rybbit_Options::EVENT_SELECTOR_MAX_LENGTH ); ?>" placeholder="<?php echo esc_attr( '.buy-button, #signup-form button' ); ?>" data-rybbit-event-selector /> 1087 </p> 1088 <p> 1089 <label for="<?php echo esc_attr( $id . '_event' ); ?>"><strong><?php esc_html_e( 'Event name', 'integrate-rybbit' ); ?></strong></label><br /> 1090 <input type="text" class="regular-text rybbit-input-wide" id="<?php echo esc_attr( $id . '_event' ); ?>" name="<?php echo esc_attr( $base . '[event]' ); ?>" value="<?php echo esc_attr( (string) $rule['event'] ); ?>" maxlength="<?php echo esc_attr( (string) Integrate_Rybbit_Options::EVENT_NAME_MAX_LENGTH ); ?>" placeholder="<?php echo esc_attr( 'buy_click' ); ?>" data-rybbit-event-name /> 1091 </p> 1092 <p> 1093 <label for="<?php echo esc_attr( $id . '_props' ); ?>"><strong><?php esc_html_e( 'Properties (optional)', 'integrate-rybbit' ); ?></strong></label><br /> 1094 <textarea class="large-text code" rows="3" id="<?php echo esc_attr( $id . '_props' ); ?>" name="<?php echo esc_attr( $base . '[props]' ); ?>" placeholder="<?php echo esc_attr( "plan=pro\nsource=header" ); ?>" aria-describedby="<?php echo esc_attr( $id . '_props_description' ); ?>" data-rybbit-event-props><?php echo esc_textarea( Integrate_Rybbit_Options::format_event_props( $rule['props'] ) ); ?></textarea> 1095 <span class="description" id="<?php echo esc_attr( $id . '_props_description' ); ?>"><?php esc_html_e( 'One key=value pair per line. Values are sent as text. Maximum 2 KB in total.', 'integrate-rybbit' ); ?></span> 1096 </p> 1097 </div> 1098 <button type="button" class="button-link button-link-delete rybbit-event-remove" data-rybbit-event-remove><?php esc_html_e( 'Remove rule', 'integrate-rybbit' ); ?></button> 1099 </div> 1100 <?php 1101 } 1102 1103 /** 882 1104 * Print the "Session Replay" tab. 883 1105 */ … … 1026 1248 1027 1249 /** 1250 * Print the "Dashboard" tab. 1251 */ 1252 private function render_tab_dashboard() { 1253 $source = Integrate_Rybbit_Options::api_key_source(); 1254 $base_url = Integrate_Rybbit_Options::get_api_base_url(); 1255 $ranges = array( 1256 '24h' => __( 'Last 24 hours', 'integrate-rybbit' ), 1257 '7d' => __( 'Last 7 days', 'integrate-rybbit' ), 1258 '30d' => __( 'Last 30 days', 'integrate-rybbit' ), 1259 '90d' => __( 'Last 90 days', 'integrate-rybbit' ), 1260 ); 1261 $range = Integrate_Rybbit_Options::get_dashboard_range(); 1262 ?> 1263 <p class="description rybbit-description-wide"> 1264 <?php esc_html_e( 'Show your Rybbit analytics in the WordPress dashboard. The plugin reads the numbers from the Rybbit API with an API key. The browser of a visitor never sees the key.', 'integrate-rybbit' ); ?> 1265 <?php esc_html_e( 'Rybbit Cloud offers API keys on the Standard plan and above. Self-hosted instances have no such limit.', 'integrate-rybbit' ); ?> 1266 </p> 1267 <table class="form-table" role="presentation"> 1268 <tr> 1269 <th scope="row"><label for="rybbit_api_key"><?php esc_html_e( 'API key', 'integrate-rybbit' ); ?></label></th> 1270 <td> 1271 <?php if ( 'constant' === $source ) : ?> 1272 <div class="notice notice-info inline"><p> 1273 <?php 1274 printf( 1275 /* translators: %s: PHP constant name. */ 1276 esc_html__( 'The API key is set with the constant %s in wp-config.php. This key is used instead of the field below.', 'integrate-rybbit' ), 1277 '<code>' . esc_html( Integrate_Rybbit_Options::API_KEY_CONSTANT ) . '</code>' 1278 ); 1279 ?> 1280 </p></div> 1281 <?php endif; ?> 1282 <input type="password" id="rybbit_api_key" name="rybbit_api_key" value="" class="regular-text rybbit-input-wide" autocomplete="new-password" spellcheck="false" aria-describedby="rybbit_api_key_description" 1283 placeholder="<?php echo 'option' === $source ? esc_attr__( 'A key is saved. Enter a new key to replace it.', 'integrate-rybbit' ) : ''; ?>" /> 1284 <p class="description" id="rybbit_api_key_description"><?php esc_html_e( 'Create the key in Rybbit under Organization settings, API keys. The plugin only needs read access. The saved key is never shown again.', 'integrate-rybbit' ); ?></p> 1285 <?php if ( '' !== (string) get_option( 'rybbit_api_key', '' ) ) : ?> 1286 <p> 1287 <label for="rybbit_api_key_remove"> 1288 <input type="checkbox" id="rybbit_api_key_remove" name="rybbit_api_key_remove" value="1" /> 1289 <?php esc_html_e( 'Remove the saved API key', 'integrate-rybbit' ); ?> 1290 </label> 1291 </p> 1292 <?php endif; ?> 1293 <p class="description"><?php esc_html_e( 'For more safety, you can define the key in wp-config.php instead.', 'integrate-rybbit' ); ?> <code>define( 'INTEGRATE_RYBBIT_API_KEY', '…' );</code></p> 1294 </td> 1295 </tr> 1296 <tr> 1297 <th scope="row"><label for="rybbit_api_url"><?php esc_html_e( 'API URL', 'integrate-rybbit' ); ?></label></th> 1298 <td> 1299 <?php 1300 $this->render_input( 1301 'rybbit_api_url', 1302 array( 1303 'type' => 'url', 1304 'class' => 'regular-text rybbit-input-url', 1305 'placeholder' => '' !== $base_url ? $base_url : 'https://app.rybbit.io', 1306 'describedby' => 'rybbit_api_url_description', 1307 ) 1308 ); 1309 ?> 1310 <p class="description" id="rybbit_api_url_description"> 1311 <?php 1312 if ( '' !== $base_url ) { 1313 printf( 1314 /* translators: %s: URL. */ 1315 esc_html__( 'Leave this empty to use the address of your Script URL. Now used: %s', 'integrate-rybbit' ), 1316 '<code>' . esc_html( $base_url ) . '</code>' 1317 ); 1318 } else { 1319 esc_html_e( 'Leave this empty to use the address of your Script URL. Set it only if the API runs on another address.', 'integrate-rybbit' ); 1320 } 1321 ?> 1322 </p> 1323 </td> 1324 </tr> 1325 <tr> 1326 <th scope="row"><label for="rybbit_dashboard_range"><?php esc_html_e( 'Default time range', 'integrate-rybbit' ); ?></label></th> 1327 <td> 1328 <select id="rybbit_dashboard_range" name="rybbit_dashboard_range"> 1329 <?php foreach ( $ranges as $value => $label ) : ?> 1330 <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $range, $value ); ?>><?php echo esc_html( $label ); ?></option> 1331 <?php endforeach; ?> 1332 </select> 1333 </td> 1334 </tr> 1335 <tr> 1336 <th scope="row"><label for="rybbit_dashboard_cache"><?php esc_html_e( 'Cache time (minutes)', 'integrate-rybbit' ); ?></label></th> 1337 <td> 1338 <?php 1339 $this->render_input( 1340 'rybbit_dashboard_cache', 1341 array( 1342 'type' => 'number', 1343 'class' => 'small-text', 1344 'min' => Integrate_Rybbit_Options::CACHE_MINUTES_MIN, 1345 'describedby' => 'rybbit_dashboard_cache_description', 1346 ) 1347 ); 1348 ?> 1349 <p class="description" id="rybbit_dashboard_cache_description"><?php esc_html_e( 'The plugin keeps API answers for this time. A longer time saves API requests. This matters on plans with request limits.', 'integrate-rybbit' ); ?></p> 1350 </td> 1351 </tr> 1352 <tr> 1353 <th scope="row"><?php esc_html_e( 'Connection', 'integrate-rybbit' ); ?></th> 1354 <td> 1355 <div class="rybbit-button-row"> 1356 <button type="button" class="button" id="rybbit-test-api"><?php esc_html_e( 'Test connection', 'integrate-rybbit' ); ?></button> 1357 <button type="button" class="button" id="rybbit-clear-api-cache"><?php esc_html_e( 'Clear cache', 'integrate-rybbit' ); ?></button> 1358 </div> 1359 <p class="rybbit-api-result" id="rybbit-api-result" role="status" aria-live="polite"></p> 1360 <p class="description"><?php esc_html_e( 'The test uses the saved settings. Save your changes first.', 'integrate-rybbit' ); ?></p> 1361 <?php if ( Integrate_Rybbit_Options::is_dashboard_enabled() && current_user_can( Integrate_Rybbit_Options::get_dashboard_capability() ) ) : ?> 1362 <p><a href="<?php echo esc_url( admin_url( 'index.php?page=' . Integrate_Rybbit_Dashboard::PAGE_SLUG ) ); ?>"><?php esc_html_e( 'Open the analytics page', 'integrate-rybbit' ); ?></a></p> 1363 <?php endif; ?> 1364 </td> 1365 </tr> 1366 </table> 1367 <?php 1368 } 1369 1370 /** 1028 1371 * Print the "Maintenance" tab. 1029 1372 */ … … 1050 1393 $settings[ $name ] = Integrate_Rybbit_Options::get( $name ); 1051 1394 } 1395 // The debug output must never show the secret key. It shows where the key comes from. 1396 $settings['rybbit_api_key'] = Integrate_Rybbit_Options::api_key_source(); 1052 1397 1053 1398 $user = wp_get_current_user(); -
integrate-rybbit/tags/1.8.0/admin/css/settings.css
r3772488 r3772670 192 192 display: none; 193 193 } 194 195 /* Custom event rules */ 196 .settings_page_integrate-rybbit .rybbit-event-rule-list { 197 counter-reset: rybbit-rule; 198 max-width: 780px; 199 } 200 201 .settings_page_integrate-rybbit .rybbit-event-rule { 202 counter-increment: rybbit-rule; 203 position: relative; 204 margin: 0 0 12px; 205 padding: 12px 16px; 206 border: 1px solid #dcdcde; 207 border-radius: 6px; 208 background: #fff; 209 } 210 211 .settings_page_integrate-rybbit .rybbit-event-rule::before { 212 content: counter(rybbit-rule); 213 position: absolute; 214 top: 12px; 215 right: 16px; 216 color: #646970; 217 font-weight: 600; 218 } 219 220 .settings_page_integrate-rybbit .rybbit-event-rule-fields p { 221 margin: 0 0 12px; 222 } 223 224 .settings_page_integrate-rybbit .rybbit-event-rule-fields .description { 225 display: block; 226 margin-top: 4px; 227 } 228 229 .settings_page_integrate-rybbit .rybbit-event-remove { 230 cursor: pointer; 231 } 232 233 .settings_page_integrate-rybbit .rybbit-event-rules p[hidden] { 234 display: none; 235 } 236 237 /* Dashboard tab */ 238 .settings_page_integrate-rybbit .rybbit-api-result { 239 margin: 4px 0 8px; 240 min-height: 1.4em; 241 } 242 243 .settings_page_integrate-rybbit .rybbit-api-result--ok { 244 color: #007017; 245 } 246 247 .settings_page_integrate-rybbit .rybbit-api-result--error { 248 color: #b32d2e; 249 } 250 251 .settings_page_integrate-rybbit .notice.inline { 252 margin: 0 0 10px; 253 max-width: 720px; 254 } -
integrate-rybbit/tags/1.8.0/admin/js/settings.js
r3772488 r3772670 234 234 } 235 235 236 /* 237 * Buttons of the Dashboard tab. They call the saved API settings. 238 * The text of the answer goes in with textContent. 239 */ 240 function initApiTools() { 241 var result = document.getElementById('rybbit-api-result'); 242 var config = window.rybbitAdmin || {}; 243 var buttons = [ 244 { id: 'rybbit-test-api', action: 'rybbit_test_api_connection', busy: __('Testing…') }, 245 { id: 'rybbit-clear-api-cache', action: 'rybbit_clear_api_cache', busy: __('Clearing…') } 246 ]; 247 248 if (!result) { 249 return; 250 } 251 252 function show(text, isError) { 253 result.textContent = text; 254 result.classList.toggle('rybbit-api-result--error', !!isError); 255 result.classList.toggle('rybbit-api-result--ok', !isError); 256 } 257 258 buttons.forEach(function (item) { 259 var button = document.getElementById(item.id); 260 if (!button) { 261 return; 262 } 263 264 button.addEventListener('click', function () { 265 if (!config.ajaxUrl || !config.nonce || !window.fetch || !window.FormData) { 266 show(__('This action is not available.'), true); 267 return; 268 } 269 270 var body = new FormData(); 271 body.append('action', item.action); 272 body.append('nonce', config.nonce); 273 274 button.disabled = true; 275 show(item.busy, false); 276 277 window 278 .fetch(config.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body }) 279 .then(function (res) { 280 return res.json().catch(function () { 281 throw new Error('HTTP ' + res.status); 282 }); 283 }) 284 .then(function (json) { 285 var message = json && json.data && json.data.message ? String(json.data.message) : __('Unknown error'); 286 show(message, !json || json.success !== true); 287 }) 288 .catch(function (err) { 289 show(err && err.message ? err.message : __('Unknown error'), true); 290 }) 291 .then(function () { 292 button.disabled = false; 293 }); 294 }); 295 }); 296 } 297 236 298 function decodeBase64Utf8(b64) { 237 299 try { … … 372 434 } 373 435 436 /* 437 * Custom event rules. The limits match the PHP limits in Integrate_Rybbit_Options. 438 * The server checks them again when it saves the form. 439 */ 440 function initEventRules() { 441 var wrap = document.querySelector('[data-rybbit-event-rules]'); 442 var form = document.querySelector('.rybbit-settings-card form'); 443 if (!wrap || !form) { 444 return; 445 } 446 447 var list = wrap.querySelector('[data-rybbit-event-list]'); 448 var template = wrap.querySelector('[data-rybbit-event-template]'); 449 var addButton = wrap.querySelector('[data-rybbit-event-add]'); 450 var emptyHint = wrap.querySelector('[data-rybbit-event-empty]'); 451 if (!list || !template || !addButton) { 452 return; 453 } 454 455 var MAX_PROP_KEY_LENGTH = 128; 456 var MAX_PROPS_BYTES = 2048; 457 var maxRules = parseInt(wrap.getAttribute('data-max'), 10) || 50; 458 var nextIndex = parseInt(wrap.getAttribute('data-next-index'), 10) || 0; 459 460 function rules() { 461 return list.querySelectorAll('[data-rybbit-event-rule]'); 462 } 463 464 function fieldOf(rule, name) { 465 return rule.querySelector('[data-rybbit-event-' + name + ']'); 466 } 467 468 function byteLength(text) { 469 return window.TextEncoder ? new window.TextEncoder().encode(text).length : text.length; 470 } 471 472 function errorElement(field) { 473 var id = field.id + '-error'; 474 var el = document.getElementById(id); 475 if (el) { 476 return el; 477 } 478 479 el = document.createElement('p'); 480 el.id = id; 481 el.className = 'description rybbit-json-error'; 482 el.hidden = true; 483 field.parentNode.insertAdjacentElement('afterend', el); 484 485 var describedBy = field.getAttribute('aria-describedby'); 486 field.setAttribute('aria-describedby', describedBy ? describedBy + ' ' + id : id); 487 return el; 488 } 489 490 function setError(field, message) { 491 var el = errorElement(field); 492 el.textContent = message; 493 el.hidden = !message; 494 field.classList.toggle('rybbit-json-invalid', !!message); 495 if (message) { 496 field.setAttribute('aria-invalid', 'true'); 497 } else { 498 field.removeAttribute('aria-invalid'); 499 } 500 return !message; 501 } 502 503 function propsError(text) { 504 var props = {}; 505 var lines = text.split(/\r\n|\r|\n/); 506 var message = __('Use one key=value pair per line. A key can have up to 128 characters.'); 507 508 for (var i = 0; i < lines.length; i++) { 509 var line = lines[i].trim(); 510 if (!line) { 511 continue; 512 } 513 514 var pos = line.indexOf('='); 515 var key = pos > 0 ? line.slice(0, pos).trim() : ''; 516 if (!key || key.length > MAX_PROP_KEY_LENGTH) { 517 return message; 518 } 519 props[key] = line.slice(pos + 1).trim(); 520 } 521 522 if (byteLength(JSON.stringify(props)) > MAX_PROPS_BYTES) { 523 return __('The properties are larger than 2 KB.'); 524 } 525 526 return ''; 527 } 528 529 function isBlank(rule) { 530 return ['selector', 'name', 'props'].every(function (name) { 531 var field = fieldOf(rule, name); 532 return !field || !field.value.trim(); 533 }); 534 } 535 536 // strict also reports empty required fields. Without it, only wrong values are reported. 537 function validateField(field, strict) { 538 var rule = field.closest('[data-rybbit-event-rule]'); 539 var value = field.value.trim(); 540 541 if (!rule || isBlank(rule)) { 542 return setError(field, ''); 543 } 544 545 if (field.hasAttribute('data-rybbit-event-selector')) { 546 if (!value) { 547 return setError(field, strict ? __('Enter a CSS selector.') : ''); 548 } 549 try { 550 document.querySelector(value); 551 } catch (e) { 552 return setError(field, __('This CSS selector is not valid.')); 553 } 554 return setError(field, ''); 555 } 556 557 if (field.hasAttribute('data-rybbit-event-name')) { 558 return setError(field, !value && strict ? __('Enter an event name.') : ''); 559 } 560 561 return setError(field, propsError(value)); 562 } 563 564 function validateRule(rule, strict) { 565 var firstInvalid = null; 566 ['selector', 'name', 'props'].forEach(function (name) { 567 var field = fieldOf(rule, name); 568 if (field && !validateField(field, strict) && !firstInvalid) { 569 firstInvalid = field; 570 } 571 }); 572 return firstInvalid; 573 } 574 575 function update() { 576 var count = rules().length; 577 if (emptyHint) { 578 emptyHint.hidden = count > 0; 579 } 580 addButton.disabled = count >= maxRules; 581 } 582 583 addButton.addEventListener('click', function () { 584 if (rules().length >= maxRules) { 585 return; 586 } 587 588 var holder = document.createElement('div'); 589 holder.innerHTML = template.innerHTML.replace(/__INDEX__/g, String(nextIndex)); 590 nextIndex++; 591 592 var rule = holder.querySelector('[data-rybbit-event-rule]'); 593 if (!rule) { 594 return; 595 } 596 597 list.appendChild(rule); 598 update(); 599 600 var selector = fieldOf(rule, 'selector'); 601 if (selector) { 602 selector.focus(); 603 } 604 }); 605 606 list.addEventListener('click', function (e) { 607 var button = e.target.closest ? e.target.closest('[data-rybbit-event-remove]') : null; 608 var rule = button ? button.closest('[data-rybbit-event-rule]') : null; 609 if (!rule) { 610 return; 611 } 612 613 // Keep the focus inside the editor after the row is gone. 614 var neighbour = rule.nextElementSibling || rule.previousElementSibling; 615 var focusTarget = neighbour ? fieldOf(neighbour, 'selector') : null; 616 617 rule.parentNode.removeChild(rule); 618 update(); 619 (focusTarget || addButton).focus(); 620 }); 621 622 list.addEventListener('input', function (e) { 623 var rule = e.target.closest ? e.target.closest('[data-rybbit-event-rule]') : null; 624 if (!rule) { 625 return; 626 } 627 628 // Clear old errors while the user types. New errors appear when the field loses focus. 629 forEach(rule.querySelectorAll('[aria-invalid]'), function (field) { 630 validateField(field, true); 631 }); 632 }); 633 634 list.addEventListener('focusout', function (e) { 635 if (e.target.matches && e.target.matches('input, textarea')) { 636 validateField(e.target, false); 637 } 638 }); 639 640 form.addEventListener('submit', function (e) { 641 var firstInvalid = null; 642 forEach(rules(), function (rule) { 643 var invalid = validateRule(rule, true); 644 if (invalid && !firstInvalid) { 645 firstInvalid = invalid; 646 } 647 }); 648 649 if (firstInvalid) { 650 e.preventDefault(); 651 var panel = firstInvalid.closest('.rybbit-tab-panel'); 652 var tab = panel ? document.getElementById(panel.getAttribute('aria-labelledby')) : null; 653 if (tab && panel.hidden) { 654 tab.click(); 655 } 656 firstInvalid.focus(); 657 } 658 }); 659 660 update(); 661 } 662 374 663 ready(function () { 375 664 initTabs(); 376 665 initUserMetaKeyToggle(); 377 666 initIdentifyPreview(); 667 initApiTools(); 378 668 initResetButtons(); 379 669 initJsonValidation(); 670 initEventRules(); 380 671 }); 381 672 })(); -
integrate-rybbit/tags/1.8.0/includes/class-integrate-rybbit-admin-ajax.php
r3772488 r3772670 11 11 12 12 /** 13 * Preview of the identify payload onthe settings page.13 * AJAX handlers of the settings page. 14 14 */ 15 15 final class Integrate_Rybbit_Admin_Ajax { … … 20 20 public function __construct() { 21 21 add_action( 'wp_ajax_rybbit_preview_identify_payload', array( $this, 'preview_identify_payload' ) ); 22 add_action( 'wp_ajax_rybbit_test_api_connection', array( $this, 'test_api_connection' ) ); 23 add_action( 'wp_ajax_rybbit_clear_api_cache', array( $this, 'clear_api_cache' ) ); 24 } 25 26 /** 27 * Stop the request unless the user may change the settings and the nonce is valid. 28 */ 29 private function authorize() { 30 if ( ! current_user_can( 'manage_options' ) ) { 31 wp_send_json_error( array( 'message' => __( 'You are not allowed to do this.', 'integrate-rybbit' ) ), 403 ); 32 } 33 34 if ( ! check_ajax_referer( 'rybbit_admin_settings', 'nonce', false ) ) { 35 wp_send_json_error( array( 'message' => __( 'Invalid security token. Please reload the page.', 'integrate-rybbit' ) ), 403 ); 36 } 22 37 } 23 38 … … 71 86 ); 72 87 } 88 89 /** 90 * Check the saved API settings with a request to the Rybbit API. 91 */ 92 public function test_api_connection() { 93 $this->authorize(); 94 95 $result = Integrate_Rybbit_Api::test_connection(); 96 if ( is_wp_error( $result ) ) { 97 wp_send_json_error( array( 'message' => $result->get_error_message() ) ); 98 } 99 100 wp_send_json_success( 101 array( 102 'message' => $result['has_data'] 103 ? __( 'Connection works. The site has data.', 'integrate-rybbit' ) 104 : __( 'Connection works. The site has no data yet.', 'integrate-rybbit' ), 105 ) 106 ); 107 } 108 109 /** 110 * Delete the cached API answers. 111 */ 112 public function clear_api_cache() { 113 $this->authorize(); 114 115 Integrate_Rybbit_Api::clear_cache(); 116 117 wp_send_json_success( array( 'message' => __( 'The cache is cleared.', 'integrate-rybbit' ) ) ); 118 } 73 119 } -
integrate-rybbit/tags/1.8.0/includes/class-integrate-rybbit-options.php
r3772488 r3772670 44 44 45 45 /** 46 * Limits of the custom event rules. The name and property limits come from Rybbit. 47 */ 48 const CUSTOM_EVENTS_MAX = 50; 49 const EVENT_NAME_MAX_LENGTH = 256; 50 const EVENT_SELECTOR_MAX_LENGTH = 500; 51 const EVENT_PROP_KEY_MAX_LENGTH = 128; 52 const EVENT_PROPS_MAX_BYTES = 2048; 53 54 /** 46 55 * Allowed values for the identify mode. 47 56 */ … … 57 66 */ 58 67 const LEGACY_OPTIONS = array( 'rybbit_do_not_track_admins' ); 68 69 /** 70 * Name of the constant that can hold the API key (wp-config.php). 71 */ 72 const API_KEY_CONSTANT = 'INTEGRATE_RYBBIT_API_KEY'; 73 74 /** 75 * Internal counter. A new value makes all cached API responses invalid. 76 */ 77 const API_CACHE_VERSION_OPTION = 'rybbit_api_cache_version'; 78 79 /** 80 * Time ranges of the dashboard. 81 */ 82 const DASHBOARD_RANGES = array( '24h', '7d', '30d', '90d' ); 83 84 /** 85 * Allowed cache duration of API responses in minutes. 86 */ 87 const CACHE_MINUTES_MIN = 1; 88 const CACHE_MINUTES_MAX = 1440; 59 89 60 90 /** … … 119 149 'rybbit_debounce' => '500', 120 150 'rybbit_tag' => '', 151 'rybbit_custom_events' => array(), 121 152 'rybbit_identify_mode' => 'disabled', 122 153 'rybbit_identify_userid_strategy' => 'wp_scoped', … … 133 164 'rybbit_replay_sampling' => self::encode_json( $json['rybbit_replay_sampling'] ), 134 165 'rybbit_replay_slim_dom_options' => self::encode_json( $json['rybbit_replay_slim_dom_options'] ), 166 'rybbit_api_key' => '', 167 'rybbit_api_url' => '', 168 'rybbit_dashboard_cache' => '10', 169 'rybbit_dashboard_range' => '7d', 135 170 'rybbit_delete_data_on_uninstall' => '0', 136 171 ); … … 167 202 array_keys( self::defaults() ), 168 203 self::LEGACY_OPTIONS, 169 array( self::DB_VERSION_OPTION )204 array( self::DB_VERSION_OPTION, self::API_CACHE_VERSION_OPTION ) 170 205 ); 171 206 } … … 365 400 366 401 /** 402 * Normalize a list of custom event rules. 403 * 404 * A rule has a CSS selector, an event name and optional properties. 405 * Rows without any content are ignored. Invalid rows and rows over the 406 * limit are dropped and counted. 407 * 408 * @param mixed $value Raw list of rules. 409 * @param int|null $rejected Receives the number of dropped rows. 410 * @return array<int, array{selector: string, event: string, props: array<string, string>}> 411 */ 412 public static function normalize_custom_events( $value, &$rejected = null ) { 413 $rejected = 0; 414 415 if ( ! is_array( $value ) ) { 416 return array(); 417 } 418 419 $rules = array(); 420 foreach ( $value as $rule ) { 421 if ( ! is_array( $rule ) || self::is_blank_event_rule( $rule ) ) { 422 continue; 423 } 424 425 $clean = self::normalize_custom_event( $rule ); 426 if ( null === $clean || count( $rules ) >= self::CUSTOM_EVENTS_MAX ) { 427 ++$rejected; 428 continue; 429 } 430 431 $rules[] = $clean; 432 } 433 434 return $rules; 435 } 436 437 /** 438 * Check if a rule row has no content at all. 439 * 440 * @param array<string, mixed> $rule Raw rule. 441 * @return bool 442 */ 443 private static function is_blank_event_rule( array $rule ) { 444 $props = isset( $rule['props'] ) ? $rule['props'] : ''; 445 446 return '' === self::event_field( $rule, 'selector' ) 447 && '' === self::event_field( $rule, 'event' ) 448 && ( is_array( $props ) ? empty( $props ) : '' === trim( (string) $props ) ); 449 } 450 451 /** 452 * Trimmed string value of a rule field. 453 * 454 * @param array<string, mixed> $rule Raw rule. 455 * @param string $key Field name. 456 * @return string 457 */ 458 private static function event_field( array $rule, $key ) { 459 return isset( $rule[ $key ] ) && is_scalar( $rule[ $key ] ) ? trim( (string) $rule[ $key ] ) : ''; 460 } 461 462 /** 463 * Normalize one custom event rule. 464 * 465 * @param array<string, mixed> $rule Raw rule. 466 * @return array{selector: string, event: string, props: array<string, string>}|null Null if the rule is invalid. 467 */ 468 private static function normalize_custom_event( array $rule ) { 469 $selector = self::sanitize_css_selector( self::event_field( $rule, 'selector' ) ); 470 $selector = trim( (string) preg_replace( '/[\x00-\x1F\x7F]/', '', wp_check_invalid_utf8( $selector ) ) ); 471 $event = sanitize_text_field( self::event_field( $rule, 'event' ) ); 472 473 if ( '' === $selector || '' === $event || self::string_length( $selector ) > self::EVENT_SELECTOR_MAX_LENGTH ) { 474 return null; 475 } 476 477 if ( self::string_length( $event ) > self::EVENT_NAME_MAX_LENGTH ) { 478 return null; 479 } 480 481 $props = self::parse_event_props( isset( $rule['props'] ) ? $rule['props'] : '' ); 482 if ( null === $props || strlen( self::encode_json( (object) $props ) ) > self::EVENT_PROPS_MAX_BYTES ) { 483 return null; 484 } 485 486 return array( 487 'selector' => $selector, 488 'event' => $event, 489 'props' => $props, 490 ); 491 } 492 493 /** 494 * Parse event properties. 495 * 496 * Text format: one "key=value" pair per line. The first "=" splits key and 497 * value. An array of key => value pairs is accepted too. 498 * 499 * @param mixed $value Raw properties. 500 * @return array<string, string>|null Null if a pair is invalid. 501 */ 502 public static function parse_event_props( $value ) { 503 $pairs = array(); 504 505 if ( is_array( $value ) ) { 506 foreach ( $value as $key => $item ) { 507 $pairs[] = array( (string) $key, $item ); 508 } 509 } else { 510 foreach ( preg_split( '/\r\n|\r|\n/', (string) $value ) as $line ) { 511 $line = trim( $line ); 512 if ( '' === $line ) { 513 continue; 514 } 515 516 $pos = strpos( $line, '=' ); 517 if ( false === $pos ) { 518 return null; 519 } 520 521 $pairs[] = array( substr( $line, 0, $pos ), substr( $line, $pos + 1 ) ); 522 } 523 } 524 525 $props = array(); 526 foreach ( $pairs as $pair ) { 527 list( $key, $item ) = $pair; 528 529 if ( ! is_scalar( $item ) ) { 530 return null; 531 } 532 533 $key = sanitize_text_field( $key ); 534 if ( '' === $key || self::string_length( $key ) > self::EVENT_PROP_KEY_MAX_LENGTH ) { 535 return null; 536 } 537 538 $props[ $key ] = sanitize_text_field( (string) $item ); 539 } 540 541 return $props; 542 } 543 544 /** 545 * Convert event properties to the "key=value" text format. 546 * 547 * @param mixed $props Property map. 548 * @return string 549 */ 550 public static function format_event_props( $props ) { 551 $lines = array(); 552 foreach ( (array) $props as $key => $item ) { 553 $lines[] = $key . '=' . ( is_scalar( $item ) ? $item : '' ); 554 } 555 556 return implode( "\n", $lines ); 557 } 558 559 /** 560 * Custom event rules for the frontend. 561 * 562 * @return array<int, array{selector: string, event: string, props: array<string, string>}> 563 */ 564 public static function get_custom_events() { 565 $rules = self::normalize_custom_events( self::get( 'rybbit_custom_events' ) ); 566 567 /** 568 * Filter the custom event rules that the plugin sends to the browser. 569 * 570 * Each rule is an array with "selector" (CSS selector), "event" (event 571 * name) and "props" (map of string keys and values). Invalid rules are 572 * removed after the filter ran. 573 * 574 * @param array $rules Event rules from the settings. 575 */ 576 $filtered = apply_filters( 'integrate_rybbit_custom_events', $rules ); 577 578 return is_array( $filtered ) ? self::normalize_custom_events( $filtered ) : $rules; 579 } 580 581 /** 582 * Length of a string in characters. 583 * 584 * @param string $value String. 585 * @return int 586 */ 587 private static function string_length( $value ) { 588 return function_exists( 'mb_strlen' ) ? mb_strlen( $value ) : strlen( $value ); 589 } 590 591 /** 367 592 * Normalize a role list to existing role slugs. 368 593 * … … 424 649 return '' !== trim( (string) self::get( 'rybbit_site_id' ) ) 425 650 && '' !== trim( (string) self::get( 'rybbit_script_url' ) ); 651 } 652 653 /** 654 * Where the API key comes from: "constant", "option" or "none". 655 * 656 * @return string 657 */ 658 public static function api_key_source() { 659 if ( defined( self::API_KEY_CONSTANT ) && '' !== trim( (string) constant( self::API_KEY_CONSTANT ) ) ) { 660 return 'constant'; 661 } 662 663 return '' !== trim( (string) get_option( 'rybbit_api_key', '' ) ) ? 'option' : 'none'; 664 } 665 666 /** 667 * API key for the Rybbit Stats API. The constant wins over the option. 668 * 669 * Never print this value. It stays on the server. 670 * 671 * @return string Empty string if no key is set. 672 */ 673 public static function get_api_key() { 674 if ( 'constant' === self::api_key_source() ) { 675 return trim( (string) constant( self::API_KEY_CONSTANT ) ); 676 } 677 678 return trim( (string) get_option( 'rybbit_api_key', '' ) ); 679 } 680 681 /** 682 * Check if an API URL may be used. 683 * 684 * The API key is sent to this URL. So it must use HTTPS. HTTP is allowed 685 * only for local hosts and for host names without a dot (for example 686 * Docker service names). 687 * 688 * @param string $url URL to check. 689 * @return bool 690 */ 691 public static function is_allowed_api_url( $url ) { 692 $scheme = wp_parse_url( (string) $url, PHP_URL_SCHEME ); 693 $host = wp_parse_url( (string) $url, PHP_URL_HOST ); 694 695 if ( ! is_string( $scheme ) || ! is_string( $host ) || '' === $host ) { 696 return false; 697 } 698 699 if ( 'https' === $scheme ) { 700 return true; 701 } 702 703 if ( 'http' !== $scheme ) { 704 return false; 705 } 706 707 $host = strtolower( trim( $host, '[]' ) ); 708 return in_array( $host, array( 'localhost', '127.0.0.1', '::1' ), true ) || false === strpos( $host, '.' ); 709 } 710 711 /** 712 * Base URL of the Rybbit instance without a trailing slash. 713 * 714 * Uses the API URL option. If it is empty, the origin of the script URL is used. 715 * 716 * @return string Empty string if no valid URL is available. 717 */ 718 public static function get_api_base_url() { 719 $url = trim( (string) self::get( 'rybbit_api_url' ) ); 720 721 if ( '' === $url ) { 722 $script = trim( (string) self::get( 'rybbit_script_url' ) ); 723 $scheme = wp_parse_url( $script, PHP_URL_SCHEME ); 724 $host = wp_parse_url( $script, PHP_URL_HOST ); 725 $port = wp_parse_url( $script, PHP_URL_PORT ); 726 727 if ( ! is_string( $scheme ) || ! is_string( $host ) || '' === $host ) { 728 return ''; 729 } 730 731 $url = $scheme . '://' . $host . ( $port ? ':' . (int) $port : '' ); 732 } 733 734 $url = untrailingslashit( $url ); 735 return self::is_allowed_api_url( $url ) ? $url : ''; 736 } 737 738 /** 739 * Time range of the dashboard. Invalid values fall back to the default. 740 * 741 * @param mixed $value Raw value. 742 * @return string 743 */ 744 public static function sanitize_dashboard_range( $value ) { 745 $value = is_string( $value ) ? $value : ''; 746 return in_array( $value, self::DASHBOARD_RANGES, true ) ? $value : (string) self::default_value( 'rybbit_dashboard_range' ); 747 } 748 749 /** 750 * Cache duration in minutes. The value is kept between the allowed limits. 751 * 752 * @param mixed $value Raw value. 753 * @return string 754 */ 755 public static function sanitize_cache_minutes( $value ) { 756 $value = trim( (string) $value ); 757 if ( '' === $value || ! preg_match( '/^\d+$/', $value ) ) { 758 return (string) self::default_value( 'rybbit_dashboard_cache' ); 759 } 760 761 return (string) min( self::CACHE_MINUTES_MAX, max( self::CACHE_MINUTES_MIN, absint( $value ) ) ); 762 } 763 764 /** 765 * Default range of the dashboard. 766 * 767 * @return string 768 */ 769 public static function get_dashboard_range() { 770 return self::sanitize_dashboard_range( self::get( 'rybbit_dashboard_range' ) ); 771 } 772 773 /** 774 * Cache duration of API responses in seconds. 775 * 776 * @return int 777 */ 778 public static function get_cache_seconds() { 779 return (int) self::sanitize_cache_minutes( self::get( 'rybbit_dashboard_cache' ) ) * MINUTE_IN_SECONDS; 780 } 781 782 /** 783 * Capability that is needed to see the dashboard. 784 * 785 * @return string 786 */ 787 public static function get_dashboard_capability() { 788 /** 789 * Filter the capability that is needed to see the analytics dashboard. 790 * 791 * The dashboard shows visitor data. Give this capability only to people 792 * who may see the analytics of the site. 793 * 794 * @param string $capability Capability. Default is "manage_options". 795 */ 796 $capability = apply_filters( 'integrate_rybbit_dashboard_capability', 'manage_options' ); 797 798 return is_string( $capability ) && '' !== $capability ? $capability : 'manage_options'; 799 } 800 801 /** 802 * The dashboard needs an API key and a site ID. 803 * 804 * @return bool 805 */ 806 public static function is_dashboard_enabled() { 807 return '' !== self::get_api_key() && '' !== trim( (string) self::get( 'rybbit_site_id' ) ); 426 808 } 427 809 -
integrate-rybbit/tags/1.8.0/integrate-rybbit.php
r3772488 r3772670 4 4 * Plugin URI: https://wordpress.org/plugins/integrate-rybbit/ 5 5 * Description: Add and manage the Rybbit Analytics tracking script. 6 * Version: 1. 7.06 * Version: 1.8.0 7 7 * Requires at least: 6.5 8 8 * Requires PHP: 7.4 … … 21 21 22 22 // The release workflow replaces this value with the tag version. 23 define( 'INTEGRATE_RYBBIT_VERSION', '1. 7.0' );23 define( 'INTEGRATE_RYBBIT_VERSION', '1.8.0' ); 24 24 define( 'INTEGRATE_RYBBIT_FILE', __FILE__ ); 25 25 define( 'INTEGRATE_RYBBIT_DIR', plugin_dir_path( __FILE__ ) ); … … 29 29 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-options.php'; 30 30 require_once INTEGRATE_RYBBIT_DIR . 'includes/functions.php'; 31 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-api.php'; 32 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-rest.php'; 33 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-optout.php'; 31 34 require_once INTEGRATE_RYBBIT_DIR . 'public/class-integrate-rybbit-public.php'; 32 35 33 36 if ( is_admin() ) { 34 37 require_once INTEGRATE_RYBBIT_DIR . 'admin/class-integrate-rybbit-admin.php'; 38 require_once INTEGRATE_RYBBIT_DIR . 'admin/class-integrate-rybbit-dashboard.php'; 35 39 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-admin-ajax.php'; 36 40 } … … 41 45 add_action( 'plugins_loaded', array( 'Integrate_Rybbit_Options', 'maybe_upgrade' ) ); 42 46 47 Integrate_Rybbit_Api::register_hooks(); 48 43 49 new Integrate_Rybbit_Public(); 50 new Integrate_Rybbit_Rest(); 51 new Integrate_Rybbit_Optout(); 44 52 45 53 if ( is_admin() ) { 46 54 new Integrate_Rybbit_Admin(); 55 new Integrate_Rybbit_Dashboard(); 47 56 new Integrate_Rybbit_Admin_Ajax(); 48 57 } -
integrate-rybbit/tags/1.8.0/public/class-integrate-rybbit-public.php
r3772488 r3772670 107 107 108 108 $identify = $this->get_identify_config(); 109 if ( ! $this->clear_user && null === $identify ) { 109 $events = $this->get_events_config(); 110 if ( ! $this->clear_user && null === $identify && empty( $events ) ) { 110 111 return; 111 112 } … … 125 126 'clearUser' => $this->clear_user, 126 127 'identify' => $identify, 128 'events' => $events, 127 129 ); 128 130 … … 132 134 'before' 133 135 ); 136 } 137 138 /** 139 * Custom event rules for the helper script. 140 * 141 * @return array<int, array{selector: string, event: string, props: object}> 142 */ 143 private function get_events_config() { 144 $events = array(); 145 146 foreach ( Integrate_Rybbit_Options::get_custom_events() as $rule ) { 147 $events[] = array( 148 'selector' => $rule['selector'], 149 'event' => $rule['event'], 150 // An object keeps numeric keys and an empty list as a JSON object. 151 'props' => (object) $rule['props'], 152 ); 153 } 154 155 return $events; 134 156 } 135 157 -
integrate-rybbit/tags/1.8.0/public/js/rybbit-helpers.js
r3772488 r3772670 3 3 * 4 4 * Calls clearUserId() after logout and identify() for logged-in users. 5 * Sends custom events when a visitor clicks an element that matches a rule. 5 6 * The configuration comes from window.integrateRybbitConfig. 6 7 */ … … 91 92 var attempts = 0; 92 93 94 function needsUserSync() { 95 return !! ( config.clearUser || ( config.identify && config.identify.userId ) ); 96 } 97 98 function sendEvent( rule, target ) { 99 var rybbit = window.rybbit; 100 if ( ! rybbit || typeof rybbit.event !== 'function' ) { 101 return; 102 } 103 104 var matches = false; 105 try { 106 matches = null !== target.closest( rule.selector ); 107 } catch ( e ) { 108 // An invalid selector must not break the other rules. 109 return; 110 } 111 112 if ( matches ) { 113 rybbit.event( rule.event, rule.props || {} ); 114 } 115 } 116 117 function trackEvents( rules ) { 118 // The capture phase runs first. Scripts of the theme cannot block it with stopPropagation(). 119 document.addEventListener( 120 'click', 121 function ( clickEvent ) { 122 var target = clickEvent.target; 123 if ( ! target || typeof target.closest !== 'function' ) { 124 return; 125 } 126 127 rules.forEach( function ( rule ) { 128 if ( rule && rule.selector && rule.event ) { 129 sendEvent( rule, target ); 130 } 131 } ); 132 }, 133 true 134 ); 135 } 136 137 if ( Array.isArray( config.events ) && config.events.length ) { 138 trackEvents( config.events ); 139 } 140 141 if ( ! needsUserSync() ) { 142 return; 143 } 144 93 145 ( function wait() { 94 146 var rybbit = window.rybbit; -
integrate-rybbit/tags/1.8.0/readme.txt
r3772488 r3772670 5 5 Tested up to: 7.1 6 6 Requires PHP: 7.4 7 Stable tag: 1. 7.07 Stable tag: 1.8.0 8 8 License: GPLv3 or later 9 9 License URI: https://github.com/maki-it/rybbit-wordpress-plugin/blob/main/LICENSE 10 10 11 Add the Rybbit Analytics tracking script to WordPress. Exclude roles, mask URLs, identify users and tune session replay privacy.11 Add Rybbit Analytics to WordPress. See your stats in wp-admin, exclude roles, mask URLs, identify users and tune session replay privacy. 12 12 13 13 == Description == … … 17 17 18 18 Enter your Site ID and the plugin does the rest. All other settings are optional. 19 You can also see your analytics inside WordPress. For this, add an API key in the Dashboard tab. 19 20 20 21 = Features = 21 22 22 23 * Works with Rybbit Cloud and with self-hosted Rybbit instances. 24 * Analytics dashboard in wp-admin: a widget on the WordPress dashboard and a page at Dashboard > Rybbit Analytics. 25 * Visitors, pageviews, bounce rate, visit duration and visitors online now. 26 * Chart of the visitors and pageviews for the last 24 hours, 7, 30 or 90 days. 27 * Top pages, top referrers, countries, devices and browsers. 28 * The data is cached. The API key stays on the server and is never sent to a browser. 23 29 * Do not track selected user roles. Administrators are excluded by default. 24 30 * Optional tracking inside wp-admin. It is off by default. … … 33 39 * User ID strategies: WordPress scoped ID, keyed hash (HMAC), user ID, login, email or a user meta field. 34 40 * Session replay privacy settings: block, ignore and mask elements, mask inputs, sampling and DOM slimming. 41 * Custom events: send an event to Rybbit when a visitor clicks an element. You set a CSS selector, an event name and optional properties on the Custom Events tab. You do not need to write JavaScript. 42 * Opt-out for visitors: add the shortcode `[rybbit_optout]` or the block "Rybbit Opt-out" to a page, for example your privacy policy. Visitors can turn the analytics off and on again. 35 43 * Debug tab with the effective settings and the generated script attributes. 36 44 * Accessible settings page with keyboard support for the tabs. 37 45 * Developer filters to change the behavior from code. 38 46 47 = Opt-out shortcode and block = 48 49 Add the shortcode to any page or post: 50 51 `[rybbit_optout]` 52 53 In the block editor, you can also use the block "Rybbit Opt-out". The block has a "Texts" panel in the sidebar. 54 55 The shortcode has these optional attributes: 56 57 * `optout_label`: text of the button that turns the analytics off. 58 * `optin_label`: text of the button that turns the analytics on again. 59 * `tracked_text`: status text while the analytics is on. 60 * `untracked_text`: status text while the analytics is off. 61 * `class`: extra CSS classes for the wrapper element. 62 63 Example: 64 65 `[rybbit_optout optout_label="Stop tracking me" tracked_text="We count your visit." class="my-style"]` 66 39 67 = Developer filters = 40 68 69 * `integrate_rybbit_optout_html` (string): Change the HTML of the opt-out shortcode and block. The second argument is the array of texts. 41 70 * `integrate_rybbit_should_track` (bool): Load the tracking script on the current request or not. 42 71 * `integrate_rybbit_script_attributes` (array): Change the `data-*` attributes of the script tag. Use it for Rybbit options without a setting, for example `data-namespace`. 43 72 * `integrate_rybbit_identify_user_id` (string): Change the user ID that is sent to Rybbit. 44 73 * `integrate_rybbit_identify_traits` (array): Change the user traits that are sent to Rybbit. 74 * `integrate_rybbit_custom_events` (array): Change the custom event rules. Each rule is an array with `selector` (string), `event` (string) and `props` (array of text values). The filter result is not saved. It does not appear in the settings. 75 * `integrate_rybbit_dashboard_capability` (string): Change the capability that is needed to see the analytics dashboard. The default is `manage_options`. 76 * `integrate_rybbit_api_http_args` (array): Change the HTTP arguments of the requests to the Rybbit API, for example the timeout. 45 77 46 78 Example: … … 58 90 4. Enter your Rybbit Site ID and save the settings. Tracking starts immediately. 59 91 5. If you host Rybbit yourself, change the Script URL to `https://your-rybbit-domain/api/script.js`. 92 6. Optional: to see your analytics in WordPress, create an API key in Rybbit and enter it on the Dashboard tab. 60 93 61 94 == Frequently Asked Questions == … … 69 102 Yes. Set the Script URL on the Tracking tab to the `script.js` URL of your instance, for example `https://analytics.example.com/api/script.js`. 70 103 104 = How do I see my analytics in WordPress? = 105 106 Create an API key in Rybbit (Organization settings, API keys). Enter it on the Dashboard tab of the plugin settings and save. Use "Test connection" to check the key. After this, a widget appears on the WordPress dashboard and a new page at Dashboard > Rybbit Analytics. 107 108 = Which Rybbit plan do I need for the dashboard? = 109 110 Rybbit Cloud offers API keys on the Standard plan and above. The Free and Basic plans have no API keys. Self-hosted instances have no such limit. The tracking works on every plan. Only the dashboard needs an API key. 111 112 = Is my API key safe? = 113 114 The plugin sends the key only from your server to the Rybbit API. It never sends the key to a browser, and it does not show the saved key again. For more safety, define the key in `wp-config.php`: `define( 'INTEGRATE_RYBBIT_API_KEY', 'your-key' );`. This key replaces the key from the settings. 115 116 = Why is the dashboard data not up to date? = 117 118 The plugin keeps the API answers for 10 minutes by default. This saves API requests, which matters on plans with request limits. Change the time on the Dashboard tab, or use "Clear cache". The count of visitors online is cached for one minute at most. 119 120 = Who can see the dashboard? = 121 122 Only users who can manage the plugin settings (`manage_options`). Use the `integrate_rybbit_dashboard_capability` filter to change this. 123 71 124 = Why do I not see my own visits? = 72 125 … … 81 134 User identification is off by default. If you turn it on, Rybbit receives a user ID for logged-in users. It also receives the roles, username and display name of the user. Full mode also sends the cleartext email. Make sure that you have a legal basis for this and update your privacy policy. The pseudonymized mode does not send the cleartext email, but username and display name are still personal data. To send less data, remove traits with the `integrate_rybbit_identify_traits` filter. The HMAC strategy gives a user ID that does not show the WordPress user ID. It uses the security keys of the site. If you change these keys, all users get a new ID in Rybbit. 82 135 136 = How do I send a custom event? = 137 138 Go to the Custom Events tab and click "Add event rule". Enter a CSS selector, for example `.buy-button`, and an event name, for example `buy_click`. Optionally add properties, one `key=value` pair per line. When a visitor clicks the element, or an element inside it, the plugin sends the event to Rybbit. Properties are sent as text. You can add up to 50 rules. Visitors with an excluded role do not send events. You can also use the `data-rybbit-event` and `data-rybbit-prop-*` attributes in your HTML. Rybbit reads them without this plugin. 139 140 = How can visitors turn the tracking off? = 141 142 Add the shortcode `[rybbit_optout]` or the block "Rybbit Opt-out" to a page, for example your privacy policy. The visitor sees a status text and a button. A click turns the analytics off for this browser. Another click turns it on again. The choice is saved in the local storage of the browser under the key `disable-rybbit`. It applies to this website and this browser only. It takes effect on the next page load. The shortcode needs a Site ID. Without a Site ID, only administrators see a notice. 143 144 = Does the opt-out work with every Rybbit script? = 145 146 The opt-out uses a feature of the Rybbit tracking script (version 1.1.0 or newer). Rybbit Cloud has this feature. Old self-hosted instances may not have it. Update your instance if the opt-out has no effect. If you set `data-namespace` with the `integrate_rybbit_script_attributes` filter, the plugin uses the same namespace for the storage key (`disable-<namespace>`). A visitor who clears the browser data also clears the opt-out. 147 83 148 = What happens to my settings when I delete the plugin? = 84 149 … … 87 152 = Does the plugin set cookies? = 88 153 89 The plugin sets one technical cookie (`rybbit_clear_user_id`) when a user logs out. The next page view clears the Rybbit user ID and deletes the cookie. If user identification is active, the plugin also stores a small value in the local storage of the browser. This prevents duplicate identify requests. For the data that the Rybbit script stores in the browser, see the [Rybbit documentation](https://rybbit.com/docs).154 The plugin sets one technical cookie (`rybbit_clear_user_id`) when a user logs out. The next page view clears the Rybbit user ID and deletes the cookie. If user identification is active, the plugin also stores a small value in the local storage of the browser. This prevents duplicate identify requests. If a visitor turns the analytics off with the opt-out button, the plugin stores the key `disable-rybbit` in the local storage of the browser. For the data that the Rybbit script stores in the browser, see the [Rybbit documentation](https://rybbit.com/docs). 90 155 91 156 == Screenshots == … … 95 160 3. Script attributes tab: skip patterns, mask patterns and debounce. 96 161 4. Session replay tab: privacy settings for session recordings. 162 5. Analytics page at Dashboard > Rybbit Analytics. 163 6. Analytics widget on the WordPress dashboard. 164 7. Dashboard tab: API key, API URL, time range and cache. 165 8. Opt-out block on a privacy policy page. 97 166 98 167 == Changelog == 168 169 = 1.8.0 = 170 - Analytics dashboard in wp-admin: a widget on the WordPress dashboard and a page at `Dashboard > Rybbit Analytics`. It shows visitors, pageviews, bounce rate, visit duration and visitors online. It also has a chart for the last 24 hours, 7, 30 or 90 days, and the top pages, referrers, countries, devices and browsers. 171 - New Dashboard tab with the API key, API URL, default time range, cache time, a connection test and a button to clear the cache. The dashboard is optional. The tracking works without it. 172 - Custom events: send an event to Rybbit when a visitor clicks an element. Set a CSS selector, an event name and optional properties on the new Custom Events tab. You do not need to write JavaScript. You can add up to 50 rules. 173 - Opt-out for visitors: the shortcode `[rybbit_optout]` and the block "Rybbit Opt-out" show a button. A visitor can turn the analytics off and on again, for example on your privacy policy page. The choice is saved in the browser and takes effect on the next page load. The Privacy tab shows how to add it. 174 - New developer filters: `integrate_rybbit_custom_events`, `integrate_rybbit_dashboard_capability`, `integrate_rybbit_api_http_args` and `integrate_rybbit_optout_html`. 175 - The API key stays on the server. The browser only calls a REST route of your site. You can also define the key in wp-config.php with `INTEGRATE_RYBBIT_API_KEY`. This key replaces the saved key. 176 - The plugin caches the answers of the Rybbit API (10 minutes by default). If Rybbit sends a rate limit error, the plugin waits for the time that Rybbit asks for. 177 - Only users with the capability manage_options can see the dashboard. Change it with the filter `integrate_rybbit_dashboard_capability`. 178 - The check for user identification runs only when it is needed. 179 - Uninstall also removes the new options and cached data. 180 - New and updated screenshots. 181 - Rybbit Cloud offers API keys on the Standard plan and above. Self-hosted instances have no such limit. The tracking works on every plan. 182 - If you enter an API key, the plugin reads statistics from the Rybbit API. It does not send visitor data. The readme describes this in the section "External services". 183 - The opt-out needs the Rybbit script v1.1.0 or newer. Old self-hosted instances may ignore it. The opt-out applies to one browser and one website only. 99 184 100 185 = 1.7.0 = … … 144 229 - refactor: rename plugin from Rybbit Analytics to Integrate Rybbit by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/31 145 230 146 = 1.5.1 =147 - fix: update image by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/25148 - fix: update image by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/26149 - ci: optimize changelogs generation in readme.txt by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/27150 - fix: improve changelog generation by handling multiline bodies safely by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/28151 - fix: reduce changelog limit to latest 10 versions by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/29152 153 231 You can find all releases at: https://github.com/maki-it/rybbit-wordpress-plugin/releases 154 232 … … 164 242 See the [Rybbit Data Processing Agreement](https://rybbit.com/dpa) to find out more about how Rybbit handles the tracking data. 165 243 244 If you enter an API key on the Dashboard tab, the plugin also reads statistics from the Rybbit API. 245 The plugin sends the API key, the Site ID and the chosen time range from your server to the Rybbit instance (by default `https://app.rybbit.io`). It does not send visitor data. 246 The requests start when a user with the needed capability opens the WordPress dashboard or the analytics page, and when you test the connection. 247 The plugin keeps the answers in a cache. The address of the instance is the origin of your Script URL, unless you set a different API URL. 248 166 249 By using this plugin, you agree to Rybbit's [terms of service](https://rybbit.com/terms-and-conditions) and [privacy policy](https://rybbit.com/privacy). 167 250 -
integrate-rybbit/tags/1.8.0/uninstall.php
r3772488 r3772670 16 16 17 17 /** 18 * Delete the cached API answers of the current site. 19 * 20 * The cache is temporary data. It is removed even if the site did not opt in. 21 */ 22 function integrate_rybbit_delete_api_cache() { 23 global $wpdb; 24 25 // With an external object cache, the entries are not in the database. They expire on their own. 26 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 27 $wpdb->query( 28 $wpdb->prepare( 29 "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", 30 $wpdb->esc_like( '_transient_rybbit_api_' ) . '%', 31 $wpdb->esc_like( '_transient_timeout_rybbit_api_' ) . '%' 32 ) 33 ); 34 } 35 36 /** 18 37 * Delete the plugin options of the current site if the site opted in. 19 38 * … … 21 40 */ 22 41 function integrate_rybbit_uninstall_site( $force ) { 42 integrate_rybbit_delete_api_cache(); 43 23 44 if ( ! $force && '1' !== get_option( 'rybbit_delete_data_on_uninstall', '0' ) ) { 24 45 return; -
integrate-rybbit/trunk/admin/class-integrate-rybbit-admin.php
r3772488 r3772670 82 82 'rybbit_debounce' => array( 'Integrate_Rybbit_Options', 'sanitize_debounce' ), 83 83 'rybbit_tag' => array( 'Integrate_Rybbit_Options', 'sanitize_tag' ), 84 'rybbit_custom_events' => array( $this, 'sanitize_custom_events' ), 84 85 'rybbit_identify_mode' => array( $this, 'sanitize_identify_mode' ), 85 86 'rybbit_identify_userid_strategy' => array( $this, 'sanitize_userid_strategy' ), … … 96 97 'rybbit_replay_sampling' => array( $this, 'sanitize_sampling' ), 97 98 'rybbit_replay_slim_dom_options' => array( $this, 'sanitize_slim_dom_options' ), 99 'rybbit_api_key' => array( $this, 'sanitize_api_key' ), 100 'rybbit_api_url' => array( $this, 'sanitize_api_url' ), 101 'rybbit_dashboard_cache' => array( 'Integrate_Rybbit_Options', 'sanitize_cache_minutes' ), 102 'rybbit_dashboard_range' => array( 'Integrate_Rybbit_Options', 'sanitize_dashboard_range' ), 98 103 'rybbit_delete_data_on_uninstall' => array( 'Integrate_Rybbit_Options', 'sanitize_checkbox' ), 99 104 ); … … 211 216 212 217 /** 218 * Sanitize the API key. 219 * 220 * The field never shows the saved key. An empty field keeps the saved key. 221 * The "Remove key" checkbox deletes it. A key from wp-config.php is not 222 * saved here. 223 * 224 * @param mixed $value Raw value. 225 * @return string 226 */ 227 public function sanitize_api_key( $value ) { 228 $old = (string) get_option( 'rybbit_api_key', '' ); 229 230 // WordPress checks the settings nonce in options.php before it calls this method. 231 // phpcs:ignore WordPress.Security.NonceVerification.Missing 232 if ( ! empty( $_POST['rybbit_api_key_remove'] ) ) { 233 return ''; 234 } 235 236 $value = is_string( $value ) ? trim( $value ) : ''; 237 if ( '' === $value ) { 238 return $old; 239 } 240 241 if ( 1 !== preg_match( '/^[A-Za-z0-9_\-.~+\/=]{8,512}$/', $value ) ) { 242 $this->add_error( 243 'rybbit_api_key', 244 'rybbit_api_key_invalid', 245 __( 'The API key has invalid characters or a wrong length. It was not saved.', 'integrate-rybbit' ) 246 ); 247 return $old; 248 } 249 250 return $value; 251 } 252 253 /** 254 * Sanitize the API URL. It must use HTTPS because the API key is sent to it. 255 * 256 * @param mixed $value Raw value. 257 * @return string 258 */ 259 public function sanitize_api_url( $value ) { 260 $value = trim( is_string( $value ) ? $value : '' ); 261 if ( '' === $value ) { 262 return ''; 263 } 264 265 $url = untrailingslashit( esc_url_raw( $value, array( 'https', 'http' ) ) ); 266 if ( '' === $url || ! Integrate_Rybbit_Options::is_allowed_api_url( $url ) ) { 267 $this->add_error( 268 'rybbit_api_url', 269 'rybbit_api_url_invalid', 270 __( 'The API URL must be a valid HTTPS URL. HTTP works only for local hosts. It was not saved.', 'integrate-rybbit' ) 271 ); 272 return (string) $this->old_value( 'rybbit_api_url' ); 273 } 274 275 return $url; 276 } 277 278 /** 213 279 * Sanitize the script loading strategy. 214 280 * … … 228 294 public function sanitize_identify_mode( $value ) { 229 295 return in_array( $value, Integrate_Rybbit_Options::IDENTIFY_MODES, true ) ? $value : 'disabled'; 296 } 297 298 /** 299 * Sanitize the custom event rules. 300 * 301 * WordPress passes null when the form has no rule rows. That clears the list. 302 * 303 * @param mixed $value Raw rules from the form. 304 * @return array<int, array<string, mixed>> 305 */ 306 public function sanitize_custom_events( $value ) { 307 $rejected = 0; 308 $rules = Integrate_Rybbit_Options::normalize_custom_events( $value, $rejected ); 309 310 if ( $rejected > 0 ) { 311 $this->add_error( 312 'rybbit_custom_events', 313 'rybbit_custom_events_rejected', 314 sprintf( 315 /* translators: 1: number of dropped rules, 2: maximum number of rules */ 316 _n( 317 '%1$d custom event rule was not saved. A rule needs a valid selector, an event name and properties as "key=value" lines. You can save at most %2$d rules.', 318 '%1$d custom event rules were not saved. A rule needs a valid selector, an event name and properties as "key=value" lines. You can save at most %2$d rules.', 319 $rejected, 320 'integrate-rybbit' 321 ), 322 $rejected, 323 Integrate_Rybbit_Options::CUSTOM_EVENTS_MAX 324 ) 325 ); 326 } 327 328 return $rules; 230 329 } 231 330 … … 371 470 'privacy' => __( 'Privacy', 'integrate-rybbit' ), 372 471 'script' => __( 'Script Attributes', 'integrate-rybbit' ), 472 'events' => __( 'Custom Events', 'integrate-rybbit' ), 373 473 'replay' => __( 'Session Replay', 'integrate-rybbit' ), 474 'dashboard' => __( 'Dashboard', 'integrate-rybbit' ), 374 475 'maintenance' => __( 'Maintenance', 'integrate-rybbit' ), 375 476 'debug' => __( 'Debug', 'integrate-rybbit' ), … … 738 839 <?php esc_html_e( 'Preview of the identify payload that would be sent for the current logged-in user.', 'integrate-rybbit' ); ?> 739 840 <a href="#" class="rybbit-refresh-payload" role="button"><?php esc_html_e( 'Refresh preview', 'integrate-rybbit' ); ?></a> 841 </p> 842 </td> 843 </tr> 844 <tr> 845 <th scope="row"><?php esc_html_e( 'Visitor opt-out', 'integrate-rybbit' ); ?></th> 846 <td> 847 <p> 848 <?php 849 printf( 850 /* translators: 1: Shortcode, 2: Block name. */ 851 esc_html__( 'Let visitors turn the tracking off. Add the shortcode %1$s or the block %2$s to a page, for example your privacy policy.', 'integrate-rybbit' ), 852 '<code>[' . esc_html( Integrate_Rybbit_Optout::SHORTCODE ) . ']</code>', 853 '<strong>' . esc_html__( 'Rybbit Opt-out', 'integrate-rybbit' ) . '</strong>' 854 ); 855 ?> 856 </p> 857 <p class="description rybbit-description-wide"> 858 <?php 859 printf( 860 /* translators: %s: Name of the storage entry, for example "disable-rybbit". */ 861 esc_html__( 'The choice is saved in the browser of the visitor under %s. It applies to this website and this browser only.', 'integrate-rybbit' ), 862 '<code>disable-' . esc_html( Integrate_Rybbit_Optout::get_namespace() ) . '</code>' 863 ); 864 ?> 740 865 </p> 741 866 </td> … … 880 1005 881 1006 /** 1007 * Print the "Custom Events" tab. 1008 */ 1009 private function render_tab_events() { 1010 $rules = Integrate_Rybbit_Options::normalize_custom_events( Integrate_Rybbit_Options::get( 'rybbit_custom_events' ) ); 1011 ?> 1012 <p class="description rybbit-description-wide"> 1013 <?php 1014 printf( 1015 /* translators: %s: Rybbit function name. */ 1016 esc_html__( 'Send a custom event to Rybbit when a visitor clicks an element. The plugin calls %s for you. You do not need to write JavaScript.', 'integrate-rybbit' ), 1017 '<code>rybbit.event()</code>' 1018 ); 1019 ?> 1020 </p> 1021 <div class="rybbit-event-rules" data-rybbit-event-rules data-next-index="<?php echo esc_attr( (string) count( $rules ) ); ?>" data-max="<?php echo esc_attr( (string) Integrate_Rybbit_Options::CUSTOM_EVENTS_MAX ); ?>"> 1022 <p class="description" data-rybbit-event-empty<?php echo empty( $rules ) ? '' : ' hidden'; ?>><?php esc_html_e( 'No event rules yet.', 'integrate-rybbit' ); ?></p> 1023 <div class="rybbit-event-rule-list" data-rybbit-event-list> 1024 <?php 1025 foreach ( $rules as $index => $rule ) { 1026 $this->render_event_rule( (string) $index, $rule ); 1027 } 1028 ?> 1029 </div> 1030 <p> 1031 <button type="button" class="button" data-rybbit-event-add><?php esc_html_e( 'Add event rule', 'integrate-rybbit' ); ?></button> 1032 </p> 1033 <template data-rybbit-event-template> 1034 <?php $this->render_event_rule( '__INDEX__', array() ); ?> 1035 </template> 1036 </div> 1037 <div class="description rybbit-description-wide"> 1038 <p> 1039 <?php 1040 printf( 1041 /* translators: %d: Maximum number of rules. */ 1042 esc_html__( 'You can add up to %d rules. A rule also matches when the visitor clicks inside a matching element, for example on an icon in a button. Visitors with an excluded role do not send events.', 'integrate-rybbit' ), 1043 (int) Integrate_Rybbit_Options::CUSTOM_EVENTS_MAX 1044 ); 1045 ?> 1046 </p> 1047 <p> 1048 <?php 1049 printf( 1050 /* translators: 1: HTML attribute name, 2: HTML attribute name. */ 1051 esc_html__( 'You can also mark elements in your HTML with the %1$s and %2$s attributes. Rybbit reads them without this plugin.', 'integrate-rybbit' ), 1052 '<code>data-rybbit-event</code>', 1053 '<code>data-rybbit-prop-*</code>' 1054 ); 1055 ?> 1056 </p> 1057 </div> 1058 <?php 1059 } 1060 1061 /** 1062 * Print one custom event rule. 1063 * 1064 * The template for new rules uses the same markup with the placeholder index. 1065 * 1066 * @param string $index Row index. "__INDEX__" for the template. 1067 * @param array<string, mixed> $rule Stored rule. 1068 */ 1069 private function render_event_rule( $index, array $rule ) { 1070 $rule = wp_parse_args( 1071 $rule, 1072 array( 1073 'selector' => '', 1074 'event' => '', 1075 'props' => array(), 1076 ) 1077 ); 1078 1079 $base = 'rybbit_custom_events[' . $index . ']'; 1080 $id = 'rybbit_custom_events_' . $index; 1081 ?> 1082 <div class="rybbit-event-rule" data-rybbit-event-rule> 1083 <div class="rybbit-event-rule-fields"> 1084 <p> 1085 <label for="<?php echo esc_attr( $id . '_selector' ); ?>"><strong><?php esc_html_e( 'CSS selector', 'integrate-rybbit' ); ?></strong></label><br /> 1086 <input type="text" class="regular-text code rybbit-input-wide" id="<?php echo esc_attr( $id . '_selector' ); ?>" name="<?php echo esc_attr( $base . '[selector]' ); ?>" value="<?php echo esc_attr( (string) $rule['selector'] ); ?>" maxlength="<?php echo esc_attr( (string) Integrate_Rybbit_Options::EVENT_SELECTOR_MAX_LENGTH ); ?>" placeholder="<?php echo esc_attr( '.buy-button, #signup-form button' ); ?>" data-rybbit-event-selector /> 1087 </p> 1088 <p> 1089 <label for="<?php echo esc_attr( $id . '_event' ); ?>"><strong><?php esc_html_e( 'Event name', 'integrate-rybbit' ); ?></strong></label><br /> 1090 <input type="text" class="regular-text rybbit-input-wide" id="<?php echo esc_attr( $id . '_event' ); ?>" name="<?php echo esc_attr( $base . '[event]' ); ?>" value="<?php echo esc_attr( (string) $rule['event'] ); ?>" maxlength="<?php echo esc_attr( (string) Integrate_Rybbit_Options::EVENT_NAME_MAX_LENGTH ); ?>" placeholder="<?php echo esc_attr( 'buy_click' ); ?>" data-rybbit-event-name /> 1091 </p> 1092 <p> 1093 <label for="<?php echo esc_attr( $id . '_props' ); ?>"><strong><?php esc_html_e( 'Properties (optional)', 'integrate-rybbit' ); ?></strong></label><br /> 1094 <textarea class="large-text code" rows="3" id="<?php echo esc_attr( $id . '_props' ); ?>" name="<?php echo esc_attr( $base . '[props]' ); ?>" placeholder="<?php echo esc_attr( "plan=pro\nsource=header" ); ?>" aria-describedby="<?php echo esc_attr( $id . '_props_description' ); ?>" data-rybbit-event-props><?php echo esc_textarea( Integrate_Rybbit_Options::format_event_props( $rule['props'] ) ); ?></textarea> 1095 <span class="description" id="<?php echo esc_attr( $id . '_props_description' ); ?>"><?php esc_html_e( 'One key=value pair per line. Values are sent as text. Maximum 2 KB in total.', 'integrate-rybbit' ); ?></span> 1096 </p> 1097 </div> 1098 <button type="button" class="button-link button-link-delete rybbit-event-remove" data-rybbit-event-remove><?php esc_html_e( 'Remove rule', 'integrate-rybbit' ); ?></button> 1099 </div> 1100 <?php 1101 } 1102 1103 /** 882 1104 * Print the "Session Replay" tab. 883 1105 */ … … 1026 1248 1027 1249 /** 1250 * Print the "Dashboard" tab. 1251 */ 1252 private function render_tab_dashboard() { 1253 $source = Integrate_Rybbit_Options::api_key_source(); 1254 $base_url = Integrate_Rybbit_Options::get_api_base_url(); 1255 $ranges = array( 1256 '24h' => __( 'Last 24 hours', 'integrate-rybbit' ), 1257 '7d' => __( 'Last 7 days', 'integrate-rybbit' ), 1258 '30d' => __( 'Last 30 days', 'integrate-rybbit' ), 1259 '90d' => __( 'Last 90 days', 'integrate-rybbit' ), 1260 ); 1261 $range = Integrate_Rybbit_Options::get_dashboard_range(); 1262 ?> 1263 <p class="description rybbit-description-wide"> 1264 <?php esc_html_e( 'Show your Rybbit analytics in the WordPress dashboard. The plugin reads the numbers from the Rybbit API with an API key. The browser of a visitor never sees the key.', 'integrate-rybbit' ); ?> 1265 <?php esc_html_e( 'Rybbit Cloud offers API keys on the Standard plan and above. Self-hosted instances have no such limit.', 'integrate-rybbit' ); ?> 1266 </p> 1267 <table class="form-table" role="presentation"> 1268 <tr> 1269 <th scope="row"><label for="rybbit_api_key"><?php esc_html_e( 'API key', 'integrate-rybbit' ); ?></label></th> 1270 <td> 1271 <?php if ( 'constant' === $source ) : ?> 1272 <div class="notice notice-info inline"><p> 1273 <?php 1274 printf( 1275 /* translators: %s: PHP constant name. */ 1276 esc_html__( 'The API key is set with the constant %s in wp-config.php. This key is used instead of the field below.', 'integrate-rybbit' ), 1277 '<code>' . esc_html( Integrate_Rybbit_Options::API_KEY_CONSTANT ) . '</code>' 1278 ); 1279 ?> 1280 </p></div> 1281 <?php endif; ?> 1282 <input type="password" id="rybbit_api_key" name="rybbit_api_key" value="" class="regular-text rybbit-input-wide" autocomplete="new-password" spellcheck="false" aria-describedby="rybbit_api_key_description" 1283 placeholder="<?php echo 'option' === $source ? esc_attr__( 'A key is saved. Enter a new key to replace it.', 'integrate-rybbit' ) : ''; ?>" /> 1284 <p class="description" id="rybbit_api_key_description"><?php esc_html_e( 'Create the key in Rybbit under Organization settings, API keys. The plugin only needs read access. The saved key is never shown again.', 'integrate-rybbit' ); ?></p> 1285 <?php if ( '' !== (string) get_option( 'rybbit_api_key', '' ) ) : ?> 1286 <p> 1287 <label for="rybbit_api_key_remove"> 1288 <input type="checkbox" id="rybbit_api_key_remove" name="rybbit_api_key_remove" value="1" /> 1289 <?php esc_html_e( 'Remove the saved API key', 'integrate-rybbit' ); ?> 1290 </label> 1291 </p> 1292 <?php endif; ?> 1293 <p class="description"><?php esc_html_e( 'For more safety, you can define the key in wp-config.php instead.', 'integrate-rybbit' ); ?> <code>define( 'INTEGRATE_RYBBIT_API_KEY', '…' );</code></p> 1294 </td> 1295 </tr> 1296 <tr> 1297 <th scope="row"><label for="rybbit_api_url"><?php esc_html_e( 'API URL', 'integrate-rybbit' ); ?></label></th> 1298 <td> 1299 <?php 1300 $this->render_input( 1301 'rybbit_api_url', 1302 array( 1303 'type' => 'url', 1304 'class' => 'regular-text rybbit-input-url', 1305 'placeholder' => '' !== $base_url ? $base_url : 'https://app.rybbit.io', 1306 'describedby' => 'rybbit_api_url_description', 1307 ) 1308 ); 1309 ?> 1310 <p class="description" id="rybbit_api_url_description"> 1311 <?php 1312 if ( '' !== $base_url ) { 1313 printf( 1314 /* translators: %s: URL. */ 1315 esc_html__( 'Leave this empty to use the address of your Script URL. Now used: %s', 'integrate-rybbit' ), 1316 '<code>' . esc_html( $base_url ) . '</code>' 1317 ); 1318 } else { 1319 esc_html_e( 'Leave this empty to use the address of your Script URL. Set it only if the API runs on another address.', 'integrate-rybbit' ); 1320 } 1321 ?> 1322 </p> 1323 </td> 1324 </tr> 1325 <tr> 1326 <th scope="row"><label for="rybbit_dashboard_range"><?php esc_html_e( 'Default time range', 'integrate-rybbit' ); ?></label></th> 1327 <td> 1328 <select id="rybbit_dashboard_range" name="rybbit_dashboard_range"> 1329 <?php foreach ( $ranges as $value => $label ) : ?> 1330 <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $range, $value ); ?>><?php echo esc_html( $label ); ?></option> 1331 <?php endforeach; ?> 1332 </select> 1333 </td> 1334 </tr> 1335 <tr> 1336 <th scope="row"><label for="rybbit_dashboard_cache"><?php esc_html_e( 'Cache time (minutes)', 'integrate-rybbit' ); ?></label></th> 1337 <td> 1338 <?php 1339 $this->render_input( 1340 'rybbit_dashboard_cache', 1341 array( 1342 'type' => 'number', 1343 'class' => 'small-text', 1344 'min' => Integrate_Rybbit_Options::CACHE_MINUTES_MIN, 1345 'describedby' => 'rybbit_dashboard_cache_description', 1346 ) 1347 ); 1348 ?> 1349 <p class="description" id="rybbit_dashboard_cache_description"><?php esc_html_e( 'The plugin keeps API answers for this time. A longer time saves API requests. This matters on plans with request limits.', 'integrate-rybbit' ); ?></p> 1350 </td> 1351 </tr> 1352 <tr> 1353 <th scope="row"><?php esc_html_e( 'Connection', 'integrate-rybbit' ); ?></th> 1354 <td> 1355 <div class="rybbit-button-row"> 1356 <button type="button" class="button" id="rybbit-test-api"><?php esc_html_e( 'Test connection', 'integrate-rybbit' ); ?></button> 1357 <button type="button" class="button" id="rybbit-clear-api-cache"><?php esc_html_e( 'Clear cache', 'integrate-rybbit' ); ?></button> 1358 </div> 1359 <p class="rybbit-api-result" id="rybbit-api-result" role="status" aria-live="polite"></p> 1360 <p class="description"><?php esc_html_e( 'The test uses the saved settings. Save your changes first.', 'integrate-rybbit' ); ?></p> 1361 <?php if ( Integrate_Rybbit_Options::is_dashboard_enabled() && current_user_can( Integrate_Rybbit_Options::get_dashboard_capability() ) ) : ?> 1362 <p><a href="<?php echo esc_url( admin_url( 'index.php?page=' . Integrate_Rybbit_Dashboard::PAGE_SLUG ) ); ?>"><?php esc_html_e( 'Open the analytics page', 'integrate-rybbit' ); ?></a></p> 1363 <?php endif; ?> 1364 </td> 1365 </tr> 1366 </table> 1367 <?php 1368 } 1369 1370 /** 1028 1371 * Print the "Maintenance" tab. 1029 1372 */ … … 1050 1393 $settings[ $name ] = Integrate_Rybbit_Options::get( $name ); 1051 1394 } 1395 // The debug output must never show the secret key. It shows where the key comes from. 1396 $settings['rybbit_api_key'] = Integrate_Rybbit_Options::api_key_source(); 1052 1397 1053 1398 $user = wp_get_current_user(); -
integrate-rybbit/trunk/admin/css/settings.css
r3772488 r3772670 192 192 display: none; 193 193 } 194 195 /* Custom event rules */ 196 .settings_page_integrate-rybbit .rybbit-event-rule-list { 197 counter-reset: rybbit-rule; 198 max-width: 780px; 199 } 200 201 .settings_page_integrate-rybbit .rybbit-event-rule { 202 counter-increment: rybbit-rule; 203 position: relative; 204 margin: 0 0 12px; 205 padding: 12px 16px; 206 border: 1px solid #dcdcde; 207 border-radius: 6px; 208 background: #fff; 209 } 210 211 .settings_page_integrate-rybbit .rybbit-event-rule::before { 212 content: counter(rybbit-rule); 213 position: absolute; 214 top: 12px; 215 right: 16px; 216 color: #646970; 217 font-weight: 600; 218 } 219 220 .settings_page_integrate-rybbit .rybbit-event-rule-fields p { 221 margin: 0 0 12px; 222 } 223 224 .settings_page_integrate-rybbit .rybbit-event-rule-fields .description { 225 display: block; 226 margin-top: 4px; 227 } 228 229 .settings_page_integrate-rybbit .rybbit-event-remove { 230 cursor: pointer; 231 } 232 233 .settings_page_integrate-rybbit .rybbit-event-rules p[hidden] { 234 display: none; 235 } 236 237 /* Dashboard tab */ 238 .settings_page_integrate-rybbit .rybbit-api-result { 239 margin: 4px 0 8px; 240 min-height: 1.4em; 241 } 242 243 .settings_page_integrate-rybbit .rybbit-api-result--ok { 244 color: #007017; 245 } 246 247 .settings_page_integrate-rybbit .rybbit-api-result--error { 248 color: #b32d2e; 249 } 250 251 .settings_page_integrate-rybbit .notice.inline { 252 margin: 0 0 10px; 253 max-width: 720px; 254 } -
integrate-rybbit/trunk/admin/js/settings.js
r3772488 r3772670 234 234 } 235 235 236 /* 237 * Buttons of the Dashboard tab. They call the saved API settings. 238 * The text of the answer goes in with textContent. 239 */ 240 function initApiTools() { 241 var result = document.getElementById('rybbit-api-result'); 242 var config = window.rybbitAdmin || {}; 243 var buttons = [ 244 { id: 'rybbit-test-api', action: 'rybbit_test_api_connection', busy: __('Testing…') }, 245 { id: 'rybbit-clear-api-cache', action: 'rybbit_clear_api_cache', busy: __('Clearing…') } 246 ]; 247 248 if (!result) { 249 return; 250 } 251 252 function show(text, isError) { 253 result.textContent = text; 254 result.classList.toggle('rybbit-api-result--error', !!isError); 255 result.classList.toggle('rybbit-api-result--ok', !isError); 256 } 257 258 buttons.forEach(function (item) { 259 var button = document.getElementById(item.id); 260 if (!button) { 261 return; 262 } 263 264 button.addEventListener('click', function () { 265 if (!config.ajaxUrl || !config.nonce || !window.fetch || !window.FormData) { 266 show(__('This action is not available.'), true); 267 return; 268 } 269 270 var body = new FormData(); 271 body.append('action', item.action); 272 body.append('nonce', config.nonce); 273 274 button.disabled = true; 275 show(item.busy, false); 276 277 window 278 .fetch(config.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body }) 279 .then(function (res) { 280 return res.json().catch(function () { 281 throw new Error('HTTP ' + res.status); 282 }); 283 }) 284 .then(function (json) { 285 var message = json && json.data && json.data.message ? String(json.data.message) : __('Unknown error'); 286 show(message, !json || json.success !== true); 287 }) 288 .catch(function (err) { 289 show(err && err.message ? err.message : __('Unknown error'), true); 290 }) 291 .then(function () { 292 button.disabled = false; 293 }); 294 }); 295 }); 296 } 297 236 298 function decodeBase64Utf8(b64) { 237 299 try { … … 372 434 } 373 435 436 /* 437 * Custom event rules. The limits match the PHP limits in Integrate_Rybbit_Options. 438 * The server checks them again when it saves the form. 439 */ 440 function initEventRules() { 441 var wrap = document.querySelector('[data-rybbit-event-rules]'); 442 var form = document.querySelector('.rybbit-settings-card form'); 443 if (!wrap || !form) { 444 return; 445 } 446 447 var list = wrap.querySelector('[data-rybbit-event-list]'); 448 var template = wrap.querySelector('[data-rybbit-event-template]'); 449 var addButton = wrap.querySelector('[data-rybbit-event-add]'); 450 var emptyHint = wrap.querySelector('[data-rybbit-event-empty]'); 451 if (!list || !template || !addButton) { 452 return; 453 } 454 455 var MAX_PROP_KEY_LENGTH = 128; 456 var MAX_PROPS_BYTES = 2048; 457 var maxRules = parseInt(wrap.getAttribute('data-max'), 10) || 50; 458 var nextIndex = parseInt(wrap.getAttribute('data-next-index'), 10) || 0; 459 460 function rules() { 461 return list.querySelectorAll('[data-rybbit-event-rule]'); 462 } 463 464 function fieldOf(rule, name) { 465 return rule.querySelector('[data-rybbit-event-' + name + ']'); 466 } 467 468 function byteLength(text) { 469 return window.TextEncoder ? new window.TextEncoder().encode(text).length : text.length; 470 } 471 472 function errorElement(field) { 473 var id = field.id + '-error'; 474 var el = document.getElementById(id); 475 if (el) { 476 return el; 477 } 478 479 el = document.createElement('p'); 480 el.id = id; 481 el.className = 'description rybbit-json-error'; 482 el.hidden = true; 483 field.parentNode.insertAdjacentElement('afterend', el); 484 485 var describedBy = field.getAttribute('aria-describedby'); 486 field.setAttribute('aria-describedby', describedBy ? describedBy + ' ' + id : id); 487 return el; 488 } 489 490 function setError(field, message) { 491 var el = errorElement(field); 492 el.textContent = message; 493 el.hidden = !message; 494 field.classList.toggle('rybbit-json-invalid', !!message); 495 if (message) { 496 field.setAttribute('aria-invalid', 'true'); 497 } else { 498 field.removeAttribute('aria-invalid'); 499 } 500 return !message; 501 } 502 503 function propsError(text) { 504 var props = {}; 505 var lines = text.split(/\r\n|\r|\n/); 506 var message = __('Use one key=value pair per line. A key can have up to 128 characters.'); 507 508 for (var i = 0; i < lines.length; i++) { 509 var line = lines[i].trim(); 510 if (!line) { 511 continue; 512 } 513 514 var pos = line.indexOf('='); 515 var key = pos > 0 ? line.slice(0, pos).trim() : ''; 516 if (!key || key.length > MAX_PROP_KEY_LENGTH) { 517 return message; 518 } 519 props[key] = line.slice(pos + 1).trim(); 520 } 521 522 if (byteLength(JSON.stringify(props)) > MAX_PROPS_BYTES) { 523 return __('The properties are larger than 2 KB.'); 524 } 525 526 return ''; 527 } 528 529 function isBlank(rule) { 530 return ['selector', 'name', 'props'].every(function (name) { 531 var field = fieldOf(rule, name); 532 return !field || !field.value.trim(); 533 }); 534 } 535 536 // strict also reports empty required fields. Without it, only wrong values are reported. 537 function validateField(field, strict) { 538 var rule = field.closest('[data-rybbit-event-rule]'); 539 var value = field.value.trim(); 540 541 if (!rule || isBlank(rule)) { 542 return setError(field, ''); 543 } 544 545 if (field.hasAttribute('data-rybbit-event-selector')) { 546 if (!value) { 547 return setError(field, strict ? __('Enter a CSS selector.') : ''); 548 } 549 try { 550 document.querySelector(value); 551 } catch (e) { 552 return setError(field, __('This CSS selector is not valid.')); 553 } 554 return setError(field, ''); 555 } 556 557 if (field.hasAttribute('data-rybbit-event-name')) { 558 return setError(field, !value && strict ? __('Enter an event name.') : ''); 559 } 560 561 return setError(field, propsError(value)); 562 } 563 564 function validateRule(rule, strict) { 565 var firstInvalid = null; 566 ['selector', 'name', 'props'].forEach(function (name) { 567 var field = fieldOf(rule, name); 568 if (field && !validateField(field, strict) && !firstInvalid) { 569 firstInvalid = field; 570 } 571 }); 572 return firstInvalid; 573 } 574 575 function update() { 576 var count = rules().length; 577 if (emptyHint) { 578 emptyHint.hidden = count > 0; 579 } 580 addButton.disabled = count >= maxRules; 581 } 582 583 addButton.addEventListener('click', function () { 584 if (rules().length >= maxRules) { 585 return; 586 } 587 588 var holder = document.createElement('div'); 589 holder.innerHTML = template.innerHTML.replace(/__INDEX__/g, String(nextIndex)); 590 nextIndex++; 591 592 var rule = holder.querySelector('[data-rybbit-event-rule]'); 593 if (!rule) { 594 return; 595 } 596 597 list.appendChild(rule); 598 update(); 599 600 var selector = fieldOf(rule, 'selector'); 601 if (selector) { 602 selector.focus(); 603 } 604 }); 605 606 list.addEventListener('click', function (e) { 607 var button = e.target.closest ? e.target.closest('[data-rybbit-event-remove]') : null; 608 var rule = button ? button.closest('[data-rybbit-event-rule]') : null; 609 if (!rule) { 610 return; 611 } 612 613 // Keep the focus inside the editor after the row is gone. 614 var neighbour = rule.nextElementSibling || rule.previousElementSibling; 615 var focusTarget = neighbour ? fieldOf(neighbour, 'selector') : null; 616 617 rule.parentNode.removeChild(rule); 618 update(); 619 (focusTarget || addButton).focus(); 620 }); 621 622 list.addEventListener('input', function (e) { 623 var rule = e.target.closest ? e.target.closest('[data-rybbit-event-rule]') : null; 624 if (!rule) { 625 return; 626 } 627 628 // Clear old errors while the user types. New errors appear when the field loses focus. 629 forEach(rule.querySelectorAll('[aria-invalid]'), function (field) { 630 validateField(field, true); 631 }); 632 }); 633 634 list.addEventListener('focusout', function (e) { 635 if (e.target.matches && e.target.matches('input, textarea')) { 636 validateField(e.target, false); 637 } 638 }); 639 640 form.addEventListener('submit', function (e) { 641 var firstInvalid = null; 642 forEach(rules(), function (rule) { 643 var invalid = validateRule(rule, true); 644 if (invalid && !firstInvalid) { 645 firstInvalid = invalid; 646 } 647 }); 648 649 if (firstInvalid) { 650 e.preventDefault(); 651 var panel = firstInvalid.closest('.rybbit-tab-panel'); 652 var tab = panel ? document.getElementById(panel.getAttribute('aria-labelledby')) : null; 653 if (tab && panel.hidden) { 654 tab.click(); 655 } 656 firstInvalid.focus(); 657 } 658 }); 659 660 update(); 661 } 662 374 663 ready(function () { 375 664 initTabs(); 376 665 initUserMetaKeyToggle(); 377 666 initIdentifyPreview(); 667 initApiTools(); 378 668 initResetButtons(); 379 669 initJsonValidation(); 670 initEventRules(); 380 671 }); 381 672 })(); -
integrate-rybbit/trunk/includes/class-integrate-rybbit-admin-ajax.php
r3772488 r3772670 11 11 12 12 /** 13 * Preview of the identify payload onthe settings page.13 * AJAX handlers of the settings page. 14 14 */ 15 15 final class Integrate_Rybbit_Admin_Ajax { … … 20 20 public function __construct() { 21 21 add_action( 'wp_ajax_rybbit_preview_identify_payload', array( $this, 'preview_identify_payload' ) ); 22 add_action( 'wp_ajax_rybbit_test_api_connection', array( $this, 'test_api_connection' ) ); 23 add_action( 'wp_ajax_rybbit_clear_api_cache', array( $this, 'clear_api_cache' ) ); 24 } 25 26 /** 27 * Stop the request unless the user may change the settings and the nonce is valid. 28 */ 29 private function authorize() { 30 if ( ! current_user_can( 'manage_options' ) ) { 31 wp_send_json_error( array( 'message' => __( 'You are not allowed to do this.', 'integrate-rybbit' ) ), 403 ); 32 } 33 34 if ( ! check_ajax_referer( 'rybbit_admin_settings', 'nonce', false ) ) { 35 wp_send_json_error( array( 'message' => __( 'Invalid security token. Please reload the page.', 'integrate-rybbit' ) ), 403 ); 36 } 22 37 } 23 38 … … 71 86 ); 72 87 } 88 89 /** 90 * Check the saved API settings with a request to the Rybbit API. 91 */ 92 public function test_api_connection() { 93 $this->authorize(); 94 95 $result = Integrate_Rybbit_Api::test_connection(); 96 if ( is_wp_error( $result ) ) { 97 wp_send_json_error( array( 'message' => $result->get_error_message() ) ); 98 } 99 100 wp_send_json_success( 101 array( 102 'message' => $result['has_data'] 103 ? __( 'Connection works. The site has data.', 'integrate-rybbit' ) 104 : __( 'Connection works. The site has no data yet.', 'integrate-rybbit' ), 105 ) 106 ); 107 } 108 109 /** 110 * Delete the cached API answers. 111 */ 112 public function clear_api_cache() { 113 $this->authorize(); 114 115 Integrate_Rybbit_Api::clear_cache(); 116 117 wp_send_json_success( array( 'message' => __( 'The cache is cleared.', 'integrate-rybbit' ) ) ); 118 } 73 119 } -
integrate-rybbit/trunk/includes/class-integrate-rybbit-options.php
r3772488 r3772670 44 44 45 45 /** 46 * Limits of the custom event rules. The name and property limits come from Rybbit. 47 */ 48 const CUSTOM_EVENTS_MAX = 50; 49 const EVENT_NAME_MAX_LENGTH = 256; 50 const EVENT_SELECTOR_MAX_LENGTH = 500; 51 const EVENT_PROP_KEY_MAX_LENGTH = 128; 52 const EVENT_PROPS_MAX_BYTES = 2048; 53 54 /** 46 55 * Allowed values for the identify mode. 47 56 */ … … 57 66 */ 58 67 const LEGACY_OPTIONS = array( 'rybbit_do_not_track_admins' ); 68 69 /** 70 * Name of the constant that can hold the API key (wp-config.php). 71 */ 72 const API_KEY_CONSTANT = 'INTEGRATE_RYBBIT_API_KEY'; 73 74 /** 75 * Internal counter. A new value makes all cached API responses invalid. 76 */ 77 const API_CACHE_VERSION_OPTION = 'rybbit_api_cache_version'; 78 79 /** 80 * Time ranges of the dashboard. 81 */ 82 const DASHBOARD_RANGES = array( '24h', '7d', '30d', '90d' ); 83 84 /** 85 * Allowed cache duration of API responses in minutes. 86 */ 87 const CACHE_MINUTES_MIN = 1; 88 const CACHE_MINUTES_MAX = 1440; 59 89 60 90 /** … … 119 149 'rybbit_debounce' => '500', 120 150 'rybbit_tag' => '', 151 'rybbit_custom_events' => array(), 121 152 'rybbit_identify_mode' => 'disabled', 122 153 'rybbit_identify_userid_strategy' => 'wp_scoped', … … 133 164 'rybbit_replay_sampling' => self::encode_json( $json['rybbit_replay_sampling'] ), 134 165 'rybbit_replay_slim_dom_options' => self::encode_json( $json['rybbit_replay_slim_dom_options'] ), 166 'rybbit_api_key' => '', 167 'rybbit_api_url' => '', 168 'rybbit_dashboard_cache' => '10', 169 'rybbit_dashboard_range' => '7d', 135 170 'rybbit_delete_data_on_uninstall' => '0', 136 171 ); … … 167 202 array_keys( self::defaults() ), 168 203 self::LEGACY_OPTIONS, 169 array( self::DB_VERSION_OPTION )204 array( self::DB_VERSION_OPTION, self::API_CACHE_VERSION_OPTION ) 170 205 ); 171 206 } … … 365 400 366 401 /** 402 * Normalize a list of custom event rules. 403 * 404 * A rule has a CSS selector, an event name and optional properties. 405 * Rows without any content are ignored. Invalid rows and rows over the 406 * limit are dropped and counted. 407 * 408 * @param mixed $value Raw list of rules. 409 * @param int|null $rejected Receives the number of dropped rows. 410 * @return array<int, array{selector: string, event: string, props: array<string, string>}> 411 */ 412 public static function normalize_custom_events( $value, &$rejected = null ) { 413 $rejected = 0; 414 415 if ( ! is_array( $value ) ) { 416 return array(); 417 } 418 419 $rules = array(); 420 foreach ( $value as $rule ) { 421 if ( ! is_array( $rule ) || self::is_blank_event_rule( $rule ) ) { 422 continue; 423 } 424 425 $clean = self::normalize_custom_event( $rule ); 426 if ( null === $clean || count( $rules ) >= self::CUSTOM_EVENTS_MAX ) { 427 ++$rejected; 428 continue; 429 } 430 431 $rules[] = $clean; 432 } 433 434 return $rules; 435 } 436 437 /** 438 * Check if a rule row has no content at all. 439 * 440 * @param array<string, mixed> $rule Raw rule. 441 * @return bool 442 */ 443 private static function is_blank_event_rule( array $rule ) { 444 $props = isset( $rule['props'] ) ? $rule['props'] : ''; 445 446 return '' === self::event_field( $rule, 'selector' ) 447 && '' === self::event_field( $rule, 'event' ) 448 && ( is_array( $props ) ? empty( $props ) : '' === trim( (string) $props ) ); 449 } 450 451 /** 452 * Trimmed string value of a rule field. 453 * 454 * @param array<string, mixed> $rule Raw rule. 455 * @param string $key Field name. 456 * @return string 457 */ 458 private static function event_field( array $rule, $key ) { 459 return isset( $rule[ $key ] ) && is_scalar( $rule[ $key ] ) ? trim( (string) $rule[ $key ] ) : ''; 460 } 461 462 /** 463 * Normalize one custom event rule. 464 * 465 * @param array<string, mixed> $rule Raw rule. 466 * @return array{selector: string, event: string, props: array<string, string>}|null Null if the rule is invalid. 467 */ 468 private static function normalize_custom_event( array $rule ) { 469 $selector = self::sanitize_css_selector( self::event_field( $rule, 'selector' ) ); 470 $selector = trim( (string) preg_replace( '/[\x00-\x1F\x7F]/', '', wp_check_invalid_utf8( $selector ) ) ); 471 $event = sanitize_text_field( self::event_field( $rule, 'event' ) ); 472 473 if ( '' === $selector || '' === $event || self::string_length( $selector ) > self::EVENT_SELECTOR_MAX_LENGTH ) { 474 return null; 475 } 476 477 if ( self::string_length( $event ) > self::EVENT_NAME_MAX_LENGTH ) { 478 return null; 479 } 480 481 $props = self::parse_event_props( isset( $rule['props'] ) ? $rule['props'] : '' ); 482 if ( null === $props || strlen( self::encode_json( (object) $props ) ) > self::EVENT_PROPS_MAX_BYTES ) { 483 return null; 484 } 485 486 return array( 487 'selector' => $selector, 488 'event' => $event, 489 'props' => $props, 490 ); 491 } 492 493 /** 494 * Parse event properties. 495 * 496 * Text format: one "key=value" pair per line. The first "=" splits key and 497 * value. An array of key => value pairs is accepted too. 498 * 499 * @param mixed $value Raw properties. 500 * @return array<string, string>|null Null if a pair is invalid. 501 */ 502 public static function parse_event_props( $value ) { 503 $pairs = array(); 504 505 if ( is_array( $value ) ) { 506 foreach ( $value as $key => $item ) { 507 $pairs[] = array( (string) $key, $item ); 508 } 509 } else { 510 foreach ( preg_split( '/\r\n|\r|\n/', (string) $value ) as $line ) { 511 $line = trim( $line ); 512 if ( '' === $line ) { 513 continue; 514 } 515 516 $pos = strpos( $line, '=' ); 517 if ( false === $pos ) { 518 return null; 519 } 520 521 $pairs[] = array( substr( $line, 0, $pos ), substr( $line, $pos + 1 ) ); 522 } 523 } 524 525 $props = array(); 526 foreach ( $pairs as $pair ) { 527 list( $key, $item ) = $pair; 528 529 if ( ! is_scalar( $item ) ) { 530 return null; 531 } 532 533 $key = sanitize_text_field( $key ); 534 if ( '' === $key || self::string_length( $key ) > self::EVENT_PROP_KEY_MAX_LENGTH ) { 535 return null; 536 } 537 538 $props[ $key ] = sanitize_text_field( (string) $item ); 539 } 540 541 return $props; 542 } 543 544 /** 545 * Convert event properties to the "key=value" text format. 546 * 547 * @param mixed $props Property map. 548 * @return string 549 */ 550 public static function format_event_props( $props ) { 551 $lines = array(); 552 foreach ( (array) $props as $key => $item ) { 553 $lines[] = $key . '=' . ( is_scalar( $item ) ? $item : '' ); 554 } 555 556 return implode( "\n", $lines ); 557 } 558 559 /** 560 * Custom event rules for the frontend. 561 * 562 * @return array<int, array{selector: string, event: string, props: array<string, string>}> 563 */ 564 public static function get_custom_events() { 565 $rules = self::normalize_custom_events( self::get( 'rybbit_custom_events' ) ); 566 567 /** 568 * Filter the custom event rules that the plugin sends to the browser. 569 * 570 * Each rule is an array with "selector" (CSS selector), "event" (event 571 * name) and "props" (map of string keys and values). Invalid rules are 572 * removed after the filter ran. 573 * 574 * @param array $rules Event rules from the settings. 575 */ 576 $filtered = apply_filters( 'integrate_rybbit_custom_events', $rules ); 577 578 return is_array( $filtered ) ? self::normalize_custom_events( $filtered ) : $rules; 579 } 580 581 /** 582 * Length of a string in characters. 583 * 584 * @param string $value String. 585 * @return int 586 */ 587 private static function string_length( $value ) { 588 return function_exists( 'mb_strlen' ) ? mb_strlen( $value ) : strlen( $value ); 589 } 590 591 /** 367 592 * Normalize a role list to existing role slugs. 368 593 * … … 424 649 return '' !== trim( (string) self::get( 'rybbit_site_id' ) ) 425 650 && '' !== trim( (string) self::get( 'rybbit_script_url' ) ); 651 } 652 653 /** 654 * Where the API key comes from: "constant", "option" or "none". 655 * 656 * @return string 657 */ 658 public static function api_key_source() { 659 if ( defined( self::API_KEY_CONSTANT ) && '' !== trim( (string) constant( self::API_KEY_CONSTANT ) ) ) { 660 return 'constant'; 661 } 662 663 return '' !== trim( (string) get_option( 'rybbit_api_key', '' ) ) ? 'option' : 'none'; 664 } 665 666 /** 667 * API key for the Rybbit Stats API. The constant wins over the option. 668 * 669 * Never print this value. It stays on the server. 670 * 671 * @return string Empty string if no key is set. 672 */ 673 public static function get_api_key() { 674 if ( 'constant' === self::api_key_source() ) { 675 return trim( (string) constant( self::API_KEY_CONSTANT ) ); 676 } 677 678 return trim( (string) get_option( 'rybbit_api_key', '' ) ); 679 } 680 681 /** 682 * Check if an API URL may be used. 683 * 684 * The API key is sent to this URL. So it must use HTTPS. HTTP is allowed 685 * only for local hosts and for host names without a dot (for example 686 * Docker service names). 687 * 688 * @param string $url URL to check. 689 * @return bool 690 */ 691 public static function is_allowed_api_url( $url ) { 692 $scheme = wp_parse_url( (string) $url, PHP_URL_SCHEME ); 693 $host = wp_parse_url( (string) $url, PHP_URL_HOST ); 694 695 if ( ! is_string( $scheme ) || ! is_string( $host ) || '' === $host ) { 696 return false; 697 } 698 699 if ( 'https' === $scheme ) { 700 return true; 701 } 702 703 if ( 'http' !== $scheme ) { 704 return false; 705 } 706 707 $host = strtolower( trim( $host, '[]' ) ); 708 return in_array( $host, array( 'localhost', '127.0.0.1', '::1' ), true ) || false === strpos( $host, '.' ); 709 } 710 711 /** 712 * Base URL of the Rybbit instance without a trailing slash. 713 * 714 * Uses the API URL option. If it is empty, the origin of the script URL is used. 715 * 716 * @return string Empty string if no valid URL is available. 717 */ 718 public static function get_api_base_url() { 719 $url = trim( (string) self::get( 'rybbit_api_url' ) ); 720 721 if ( '' === $url ) { 722 $script = trim( (string) self::get( 'rybbit_script_url' ) ); 723 $scheme = wp_parse_url( $script, PHP_URL_SCHEME ); 724 $host = wp_parse_url( $script, PHP_URL_HOST ); 725 $port = wp_parse_url( $script, PHP_URL_PORT ); 726 727 if ( ! is_string( $scheme ) || ! is_string( $host ) || '' === $host ) { 728 return ''; 729 } 730 731 $url = $scheme . '://' . $host . ( $port ? ':' . (int) $port : '' ); 732 } 733 734 $url = untrailingslashit( $url ); 735 return self::is_allowed_api_url( $url ) ? $url : ''; 736 } 737 738 /** 739 * Time range of the dashboard. Invalid values fall back to the default. 740 * 741 * @param mixed $value Raw value. 742 * @return string 743 */ 744 public static function sanitize_dashboard_range( $value ) { 745 $value = is_string( $value ) ? $value : ''; 746 return in_array( $value, self::DASHBOARD_RANGES, true ) ? $value : (string) self::default_value( 'rybbit_dashboard_range' ); 747 } 748 749 /** 750 * Cache duration in minutes. The value is kept between the allowed limits. 751 * 752 * @param mixed $value Raw value. 753 * @return string 754 */ 755 public static function sanitize_cache_minutes( $value ) { 756 $value = trim( (string) $value ); 757 if ( '' === $value || ! preg_match( '/^\d+$/', $value ) ) { 758 return (string) self::default_value( 'rybbit_dashboard_cache' ); 759 } 760 761 return (string) min( self::CACHE_MINUTES_MAX, max( self::CACHE_MINUTES_MIN, absint( $value ) ) ); 762 } 763 764 /** 765 * Default range of the dashboard. 766 * 767 * @return string 768 */ 769 public static function get_dashboard_range() { 770 return self::sanitize_dashboard_range( self::get( 'rybbit_dashboard_range' ) ); 771 } 772 773 /** 774 * Cache duration of API responses in seconds. 775 * 776 * @return int 777 */ 778 public static function get_cache_seconds() { 779 return (int) self::sanitize_cache_minutes( self::get( 'rybbit_dashboard_cache' ) ) * MINUTE_IN_SECONDS; 780 } 781 782 /** 783 * Capability that is needed to see the dashboard. 784 * 785 * @return string 786 */ 787 public static function get_dashboard_capability() { 788 /** 789 * Filter the capability that is needed to see the analytics dashboard. 790 * 791 * The dashboard shows visitor data. Give this capability only to people 792 * who may see the analytics of the site. 793 * 794 * @param string $capability Capability. Default is "manage_options". 795 */ 796 $capability = apply_filters( 'integrate_rybbit_dashboard_capability', 'manage_options' ); 797 798 return is_string( $capability ) && '' !== $capability ? $capability : 'manage_options'; 799 } 800 801 /** 802 * The dashboard needs an API key and a site ID. 803 * 804 * @return bool 805 */ 806 public static function is_dashboard_enabled() { 807 return '' !== self::get_api_key() && '' !== trim( (string) self::get( 'rybbit_site_id' ) ); 426 808 } 427 809 -
integrate-rybbit/trunk/integrate-rybbit.php
r3772488 r3772670 4 4 * Plugin URI: https://wordpress.org/plugins/integrate-rybbit/ 5 5 * Description: Add and manage the Rybbit Analytics tracking script. 6 * Version: 1. 7.06 * Version: 1.8.0 7 7 * Requires at least: 6.5 8 8 * Requires PHP: 7.4 … … 21 21 22 22 // The release workflow replaces this value with the tag version. 23 define( 'INTEGRATE_RYBBIT_VERSION', '1. 7.0' );23 define( 'INTEGRATE_RYBBIT_VERSION', '1.8.0' ); 24 24 define( 'INTEGRATE_RYBBIT_FILE', __FILE__ ); 25 25 define( 'INTEGRATE_RYBBIT_DIR', plugin_dir_path( __FILE__ ) ); … … 29 29 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-options.php'; 30 30 require_once INTEGRATE_RYBBIT_DIR . 'includes/functions.php'; 31 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-api.php'; 32 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-rest.php'; 33 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-optout.php'; 31 34 require_once INTEGRATE_RYBBIT_DIR . 'public/class-integrate-rybbit-public.php'; 32 35 33 36 if ( is_admin() ) { 34 37 require_once INTEGRATE_RYBBIT_DIR . 'admin/class-integrate-rybbit-admin.php'; 38 require_once INTEGRATE_RYBBIT_DIR . 'admin/class-integrate-rybbit-dashboard.php'; 35 39 require_once INTEGRATE_RYBBIT_DIR . 'includes/class-integrate-rybbit-admin-ajax.php'; 36 40 } … … 41 45 add_action( 'plugins_loaded', array( 'Integrate_Rybbit_Options', 'maybe_upgrade' ) ); 42 46 47 Integrate_Rybbit_Api::register_hooks(); 48 43 49 new Integrate_Rybbit_Public(); 50 new Integrate_Rybbit_Rest(); 51 new Integrate_Rybbit_Optout(); 44 52 45 53 if ( is_admin() ) { 46 54 new Integrate_Rybbit_Admin(); 55 new Integrate_Rybbit_Dashboard(); 47 56 new Integrate_Rybbit_Admin_Ajax(); 48 57 } -
integrate-rybbit/trunk/public/class-integrate-rybbit-public.php
r3772488 r3772670 107 107 108 108 $identify = $this->get_identify_config(); 109 if ( ! $this->clear_user && null === $identify ) { 109 $events = $this->get_events_config(); 110 if ( ! $this->clear_user && null === $identify && empty( $events ) ) { 110 111 return; 111 112 } … … 125 126 'clearUser' => $this->clear_user, 126 127 'identify' => $identify, 128 'events' => $events, 127 129 ); 128 130 … … 132 134 'before' 133 135 ); 136 } 137 138 /** 139 * Custom event rules for the helper script. 140 * 141 * @return array<int, array{selector: string, event: string, props: object}> 142 */ 143 private function get_events_config() { 144 $events = array(); 145 146 foreach ( Integrate_Rybbit_Options::get_custom_events() as $rule ) { 147 $events[] = array( 148 'selector' => $rule['selector'], 149 'event' => $rule['event'], 150 // An object keeps numeric keys and an empty list as a JSON object. 151 'props' => (object) $rule['props'], 152 ); 153 } 154 155 return $events; 134 156 } 135 157 -
integrate-rybbit/trunk/public/js/rybbit-helpers.js
r3772488 r3772670 3 3 * 4 4 * Calls clearUserId() after logout and identify() for logged-in users. 5 * Sends custom events when a visitor clicks an element that matches a rule. 5 6 * The configuration comes from window.integrateRybbitConfig. 6 7 */ … … 91 92 var attempts = 0; 92 93 94 function needsUserSync() { 95 return !! ( config.clearUser || ( config.identify && config.identify.userId ) ); 96 } 97 98 function sendEvent( rule, target ) { 99 var rybbit = window.rybbit; 100 if ( ! rybbit || typeof rybbit.event !== 'function' ) { 101 return; 102 } 103 104 var matches = false; 105 try { 106 matches = null !== target.closest( rule.selector ); 107 } catch ( e ) { 108 // An invalid selector must not break the other rules. 109 return; 110 } 111 112 if ( matches ) { 113 rybbit.event( rule.event, rule.props || {} ); 114 } 115 } 116 117 function trackEvents( rules ) { 118 // The capture phase runs first. Scripts of the theme cannot block it with stopPropagation(). 119 document.addEventListener( 120 'click', 121 function ( clickEvent ) { 122 var target = clickEvent.target; 123 if ( ! target || typeof target.closest !== 'function' ) { 124 return; 125 } 126 127 rules.forEach( function ( rule ) { 128 if ( rule && rule.selector && rule.event ) { 129 sendEvent( rule, target ); 130 } 131 } ); 132 }, 133 true 134 ); 135 } 136 137 if ( Array.isArray( config.events ) && config.events.length ) { 138 trackEvents( config.events ); 139 } 140 141 if ( ! needsUserSync() ) { 142 return; 143 } 144 93 145 ( function wait() { 94 146 var rybbit = window.rybbit; -
integrate-rybbit/trunk/readme.txt
r3772488 r3772670 5 5 Tested up to: 7.1 6 6 Requires PHP: 7.4 7 Stable tag: 1. 7.07 Stable tag: 1.8.0 8 8 License: GPLv3 or later 9 9 License URI: https://github.com/maki-it/rybbit-wordpress-plugin/blob/main/LICENSE 10 10 11 Add the Rybbit Analytics tracking script to WordPress. Exclude roles, mask URLs, identify users and tune session replay privacy.11 Add Rybbit Analytics to WordPress. See your stats in wp-admin, exclude roles, mask URLs, identify users and tune session replay privacy. 12 12 13 13 == Description == … … 17 17 18 18 Enter your Site ID and the plugin does the rest. All other settings are optional. 19 You can also see your analytics inside WordPress. For this, add an API key in the Dashboard tab. 19 20 20 21 = Features = 21 22 22 23 * Works with Rybbit Cloud and with self-hosted Rybbit instances. 24 * Analytics dashboard in wp-admin: a widget on the WordPress dashboard and a page at Dashboard > Rybbit Analytics. 25 * Visitors, pageviews, bounce rate, visit duration and visitors online now. 26 * Chart of the visitors and pageviews for the last 24 hours, 7, 30 or 90 days. 27 * Top pages, top referrers, countries, devices and browsers. 28 * The data is cached. The API key stays on the server and is never sent to a browser. 23 29 * Do not track selected user roles. Administrators are excluded by default. 24 30 * Optional tracking inside wp-admin. It is off by default. … … 33 39 * User ID strategies: WordPress scoped ID, keyed hash (HMAC), user ID, login, email or a user meta field. 34 40 * Session replay privacy settings: block, ignore and mask elements, mask inputs, sampling and DOM slimming. 41 * Custom events: send an event to Rybbit when a visitor clicks an element. You set a CSS selector, an event name and optional properties on the Custom Events tab. You do not need to write JavaScript. 42 * Opt-out for visitors: add the shortcode `[rybbit_optout]` or the block "Rybbit Opt-out" to a page, for example your privacy policy. Visitors can turn the analytics off and on again. 35 43 * Debug tab with the effective settings and the generated script attributes. 36 44 * Accessible settings page with keyboard support for the tabs. 37 45 * Developer filters to change the behavior from code. 38 46 47 = Opt-out shortcode and block = 48 49 Add the shortcode to any page or post: 50 51 `[rybbit_optout]` 52 53 In the block editor, you can also use the block "Rybbit Opt-out". The block has a "Texts" panel in the sidebar. 54 55 The shortcode has these optional attributes: 56 57 * `optout_label`: text of the button that turns the analytics off. 58 * `optin_label`: text of the button that turns the analytics on again. 59 * `tracked_text`: status text while the analytics is on. 60 * `untracked_text`: status text while the analytics is off. 61 * `class`: extra CSS classes for the wrapper element. 62 63 Example: 64 65 `[rybbit_optout optout_label="Stop tracking me" tracked_text="We count your visit." class="my-style"]` 66 39 67 = Developer filters = 40 68 69 * `integrate_rybbit_optout_html` (string): Change the HTML of the opt-out shortcode and block. The second argument is the array of texts. 41 70 * `integrate_rybbit_should_track` (bool): Load the tracking script on the current request or not. 42 71 * `integrate_rybbit_script_attributes` (array): Change the `data-*` attributes of the script tag. Use it for Rybbit options without a setting, for example `data-namespace`. 43 72 * `integrate_rybbit_identify_user_id` (string): Change the user ID that is sent to Rybbit. 44 73 * `integrate_rybbit_identify_traits` (array): Change the user traits that are sent to Rybbit. 74 * `integrate_rybbit_custom_events` (array): Change the custom event rules. Each rule is an array with `selector` (string), `event` (string) and `props` (array of text values). The filter result is not saved. It does not appear in the settings. 75 * `integrate_rybbit_dashboard_capability` (string): Change the capability that is needed to see the analytics dashboard. The default is `manage_options`. 76 * `integrate_rybbit_api_http_args` (array): Change the HTTP arguments of the requests to the Rybbit API, for example the timeout. 45 77 46 78 Example: … … 58 90 4. Enter your Rybbit Site ID and save the settings. Tracking starts immediately. 59 91 5. If you host Rybbit yourself, change the Script URL to `https://your-rybbit-domain/api/script.js`. 92 6. Optional: to see your analytics in WordPress, create an API key in Rybbit and enter it on the Dashboard tab. 60 93 61 94 == Frequently Asked Questions == … … 69 102 Yes. Set the Script URL on the Tracking tab to the `script.js` URL of your instance, for example `https://analytics.example.com/api/script.js`. 70 103 104 = How do I see my analytics in WordPress? = 105 106 Create an API key in Rybbit (Organization settings, API keys). Enter it on the Dashboard tab of the plugin settings and save. Use "Test connection" to check the key. After this, a widget appears on the WordPress dashboard and a new page at Dashboard > Rybbit Analytics. 107 108 = Which Rybbit plan do I need for the dashboard? = 109 110 Rybbit Cloud offers API keys on the Standard plan and above. The Free and Basic plans have no API keys. Self-hosted instances have no such limit. The tracking works on every plan. Only the dashboard needs an API key. 111 112 = Is my API key safe? = 113 114 The plugin sends the key only from your server to the Rybbit API. It never sends the key to a browser, and it does not show the saved key again. For more safety, define the key in `wp-config.php`: `define( 'INTEGRATE_RYBBIT_API_KEY', 'your-key' );`. This key replaces the key from the settings. 115 116 = Why is the dashboard data not up to date? = 117 118 The plugin keeps the API answers for 10 minutes by default. This saves API requests, which matters on plans with request limits. Change the time on the Dashboard tab, or use "Clear cache". The count of visitors online is cached for one minute at most. 119 120 = Who can see the dashboard? = 121 122 Only users who can manage the plugin settings (`manage_options`). Use the `integrate_rybbit_dashboard_capability` filter to change this. 123 71 124 = Why do I not see my own visits? = 72 125 … … 81 134 User identification is off by default. If you turn it on, Rybbit receives a user ID for logged-in users. It also receives the roles, username and display name of the user. Full mode also sends the cleartext email. Make sure that you have a legal basis for this and update your privacy policy. The pseudonymized mode does not send the cleartext email, but username and display name are still personal data. To send less data, remove traits with the `integrate_rybbit_identify_traits` filter. The HMAC strategy gives a user ID that does not show the WordPress user ID. It uses the security keys of the site. If you change these keys, all users get a new ID in Rybbit. 82 135 136 = How do I send a custom event? = 137 138 Go to the Custom Events tab and click "Add event rule". Enter a CSS selector, for example `.buy-button`, and an event name, for example `buy_click`. Optionally add properties, one `key=value` pair per line. When a visitor clicks the element, or an element inside it, the plugin sends the event to Rybbit. Properties are sent as text. You can add up to 50 rules. Visitors with an excluded role do not send events. You can also use the `data-rybbit-event` and `data-rybbit-prop-*` attributes in your HTML. Rybbit reads them without this plugin. 139 140 = How can visitors turn the tracking off? = 141 142 Add the shortcode `[rybbit_optout]` or the block "Rybbit Opt-out" to a page, for example your privacy policy. The visitor sees a status text and a button. A click turns the analytics off for this browser. Another click turns it on again. The choice is saved in the local storage of the browser under the key `disable-rybbit`. It applies to this website and this browser only. It takes effect on the next page load. The shortcode needs a Site ID. Without a Site ID, only administrators see a notice. 143 144 = Does the opt-out work with every Rybbit script? = 145 146 The opt-out uses a feature of the Rybbit tracking script (version 1.1.0 or newer). Rybbit Cloud has this feature. Old self-hosted instances may not have it. Update your instance if the opt-out has no effect. If you set `data-namespace` with the `integrate_rybbit_script_attributes` filter, the plugin uses the same namespace for the storage key (`disable-<namespace>`). A visitor who clears the browser data also clears the opt-out. 147 83 148 = What happens to my settings when I delete the plugin? = 84 149 … … 87 152 = Does the plugin set cookies? = 88 153 89 The plugin sets one technical cookie (`rybbit_clear_user_id`) when a user logs out. The next page view clears the Rybbit user ID and deletes the cookie. If user identification is active, the plugin also stores a small value in the local storage of the browser. This prevents duplicate identify requests. For the data that the Rybbit script stores in the browser, see the [Rybbit documentation](https://rybbit.com/docs).154 The plugin sets one technical cookie (`rybbit_clear_user_id`) when a user logs out. The next page view clears the Rybbit user ID and deletes the cookie. If user identification is active, the plugin also stores a small value in the local storage of the browser. This prevents duplicate identify requests. If a visitor turns the analytics off with the opt-out button, the plugin stores the key `disable-rybbit` in the local storage of the browser. For the data that the Rybbit script stores in the browser, see the [Rybbit documentation](https://rybbit.com/docs). 90 155 91 156 == Screenshots == … … 95 160 3. Script attributes tab: skip patterns, mask patterns and debounce. 96 161 4. Session replay tab: privacy settings for session recordings. 162 5. Analytics page at Dashboard > Rybbit Analytics. 163 6. Analytics widget on the WordPress dashboard. 164 7. Dashboard tab: API key, API URL, time range and cache. 165 8. Opt-out block on a privacy policy page. 97 166 98 167 == Changelog == 168 169 = 1.8.0 = 170 - Analytics dashboard in wp-admin: a widget on the WordPress dashboard and a page at `Dashboard > Rybbit Analytics`. It shows visitors, pageviews, bounce rate, visit duration and visitors online. It also has a chart for the last 24 hours, 7, 30 or 90 days, and the top pages, referrers, countries, devices and browsers. 171 - New Dashboard tab with the API key, API URL, default time range, cache time, a connection test and a button to clear the cache. The dashboard is optional. The tracking works without it. 172 - Custom events: send an event to Rybbit when a visitor clicks an element. Set a CSS selector, an event name and optional properties on the new Custom Events tab. You do not need to write JavaScript. You can add up to 50 rules. 173 - Opt-out for visitors: the shortcode `[rybbit_optout]` and the block "Rybbit Opt-out" show a button. A visitor can turn the analytics off and on again, for example on your privacy policy page. The choice is saved in the browser and takes effect on the next page load. The Privacy tab shows how to add it. 174 - New developer filters: `integrate_rybbit_custom_events`, `integrate_rybbit_dashboard_capability`, `integrate_rybbit_api_http_args` and `integrate_rybbit_optout_html`. 175 - The API key stays on the server. The browser only calls a REST route of your site. You can also define the key in wp-config.php with `INTEGRATE_RYBBIT_API_KEY`. This key replaces the saved key. 176 - The plugin caches the answers of the Rybbit API (10 minutes by default). If Rybbit sends a rate limit error, the plugin waits for the time that Rybbit asks for. 177 - Only users with the capability manage_options can see the dashboard. Change it with the filter `integrate_rybbit_dashboard_capability`. 178 - The check for user identification runs only when it is needed. 179 - Uninstall also removes the new options and cached data. 180 - New and updated screenshots. 181 - Rybbit Cloud offers API keys on the Standard plan and above. Self-hosted instances have no such limit. The tracking works on every plan. 182 - If you enter an API key, the plugin reads statistics from the Rybbit API. It does not send visitor data. The readme describes this in the section "External services". 183 - The opt-out needs the Rybbit script v1.1.0 or newer. Old self-hosted instances may ignore it. The opt-out applies to one browser and one website only. 99 184 100 185 = 1.7.0 = … … 144 229 - refactor: rename plugin from Rybbit Analytics to Integrate Rybbit by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/31 145 230 146 = 1.5.1 =147 - fix: update image by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/25148 - fix: update image by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/26149 - ci: optimize changelogs generation in readme.txt by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/27150 - fix: improve changelog generation by handling multiline bodies safely by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/28151 - fix: reduce changelog limit to latest 10 versions by @kimdre in https://github.com/maki-it/rybbit-wordpress-plugin/pull/29152 153 231 You can find all releases at: https://github.com/maki-it/rybbit-wordpress-plugin/releases 154 232 … … 164 242 See the [Rybbit Data Processing Agreement](https://rybbit.com/dpa) to find out more about how Rybbit handles the tracking data. 165 243 244 If you enter an API key on the Dashboard tab, the plugin also reads statistics from the Rybbit API. 245 The plugin sends the API key, the Site ID and the chosen time range from your server to the Rybbit instance (by default `https://app.rybbit.io`). It does not send visitor data. 246 The requests start when a user with the needed capability opens the WordPress dashboard or the analytics page, and when you test the connection. 247 The plugin keeps the answers in a cache. The address of the instance is the origin of your Script URL, unless you set a different API URL. 248 166 249 By using this plugin, you agree to Rybbit's [terms of service](https://rybbit.com/terms-and-conditions) and [privacy policy](https://rybbit.com/privacy). 167 250 -
integrate-rybbit/trunk/uninstall.php
r3772488 r3772670 16 16 17 17 /** 18 * Delete the cached API answers of the current site. 19 * 20 * The cache is temporary data. It is removed even if the site did not opt in. 21 */ 22 function integrate_rybbit_delete_api_cache() { 23 global $wpdb; 24 25 // With an external object cache, the entries are not in the database. They expire on their own. 26 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching 27 $wpdb->query( 28 $wpdb->prepare( 29 "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", 30 $wpdb->esc_like( '_transient_rybbit_api_' ) . '%', 31 $wpdb->esc_like( '_transient_timeout_rybbit_api_' ) . '%' 32 ) 33 ); 34 } 35 36 /** 18 37 * Delete the plugin options of the current site if the site opted in. 19 38 * … … 21 40 */ 22 41 function integrate_rybbit_uninstall_site( $force ) { 42 integrate_rybbit_delete_api_cache(); 43 23 44 if ( ! $force && '1' !== get_option( 'rybbit_delete_data_on_uninstall', '0' ) ) { 24 45 return;
Note:
See TracChangeset
for help on using the changeset viewer.