-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproperf-wordpress-adapter.php
More file actions
601 lines (537 loc) · 16.2 KB
/
properf-wordpress-adapter.php
File metadata and controls
601 lines (537 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
<?php
/**
* Plugin Name: ProPerf WordPress Adapter
* Plugin URI: https://coloredcow.com
* Description: Collects and displays database health metrics (autoloaded options)
* Version: 1.0.1
* Author: ColoredCow
* License: GPL v2 or later
*
* @package ProPerf
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'PROPERF_DIR', plugin_dir_path( __FILE__ ) );
define( 'PROPERF_URL', plugin_dir_url( __FILE__ ) );
define( 'PROPERF_VERSION', '1.0.0' );
require_once PROPERF_DIR . 'includes/class-data-collector.php';
/**
* Plugin activation: ensure cron is scheduled.
*/
function properf_activate_plugin() {
properf_schedule_metrics_collection();
}
register_activation_hook( __FILE__, 'properf_activate_plugin' );
/**
* Plugin deactivation: clean up cron.
*/
function properf_deactivate_plugin() {
$timestamp = wp_next_scheduled( 'properf_collect_metrics' );
if ( $timestamp ) {
wp_unschedule_event( $timestamp, 'properf_collect_metrics' );
}
}
register_deactivation_hook( __FILE__, 'properf_deactivate_plugin' );
/**
* Initialize plugin.
*/
function properf_init() {
add_action( 'admin_menu', 'properf_add_admin_menu' );
add_action( 'admin_init', 'properf_register_settings', 20 );
}
add_action( 'plugins_loaded', 'properf_init' );
/**
* Handle BigQuery push on admin init.
*/
function properf_handle_bigquery_push() {
if ( isset( $_POST['properf_push_to_bq'] ) && check_admin_referer( 'properf_push_action', 'properf_push_nonce' ) ) {
require_once PROPERF_DIR . 'includes/class-bigquery-client.php';
$collector = new ProPerf_Data_Collector();
$bq_client = new ProPerf_BigQuery_Client();
$success = $bq_client->push_metrics( $collector->get_data() );
// Persist execution info (shared with cron)
update_option( 'properf_bq_last_sync', time(), false );
update_option( 'properf_bq_last_sync_status', $success ? 'success' : 'error', false );
if ( $success ) {
delete_option( 'properf_bq_last_sync_error' );
add_settings_error(
'properf_messages',
'properf_msg',
'Data successfully pushed to BigQuery!',
'updated'
);
} else {
$error_message = $bq_client->get_last_error();
update_option( 'properf_bq_last_sync_error', $error_message, false );
add_settings_error(
'properf_messages',
'properf_msg',
'Failed: ' . $error_message,
'error'
);
}
}
// Show success message when settings are saved.
if (
isset( $_GET['settings-updated'] ) &&
isset( $_GET['page'] ) &&
'properf-settings' === $_GET['page']
) {
add_settings_error(
'properf_messages',
'properf_settings_saved',
__( 'Settings saved successfully.', 'properf' ),
'updated'
);
}
}
add_action( 'admin_init', 'properf_handle_bigquery_push' );
/**
* Schedule metrics collection if not already scheduled.
*/
function properf_schedule_metrics_collection() {
if ( false === wp_next_scheduled( 'properf_collect_metrics' ) ) {
$time = properf_get_next_midnight();
wp_schedule_event( $time, 'daily', 'properf_collect_metrics' );
}
}
add_action( 'wp', 'properf_schedule_metrics_collection' );
/**
* Handle scheduled metrics collection and push to BigQuery.
*/
function properf_collect_and_push_metrics() {
require_once PROPERF_DIR . 'includes/class-bigquery-client.php';
$collector = new ProPerf_Data_Collector();
$bq_client = new ProPerf_BigQuery_Client();
$success = $bq_client->push_metrics( $collector->get_data() );
// Persist cron execution info.
update_option( 'properf_bq_last_sync', time(), false );
update_option( 'properf_bq_last_sync_status', $success ? 'success' : 'error', false );
if ( $success ) {
delete_option( 'properf_bq_last_sync_error' );
error_log(
'ProPerf: Metrics successfully pushed to BigQuery at ' . gmdate( 'Y-m-d H:i:s' )
);
} else {
$error_message = $bq_client->get_last_error();
update_option( 'properf_bq_last_sync_error', $error_message, false );
error_log(
'ProPerf Error: Failed to push metrics to BigQuery - ' . $error_message
);
}
}
add_action( 'properf_collect_metrics', 'properf_collect_and_push_metrics' );
/**
* Get next midnight timestamp in site timezone.
*
* @return int Timestamp for next midnight (00:00:00).
*/
function properf_get_next_midnight() {
$tz = get_option( 'timezone_string' );
$tz = $tz ? $tz : 'UTC';
if ( empty( $tz ) ) {
$gmt_offset = get_option( 'gmt_offset' );
$tz = timezone_name_from_abbr( '', $gmt_offset * 3600, false );
if ( false === $tz ) {
$tz = 'UTC';
}
}
$target_tz = new DateTimeZone( $tz );
$now = new DateTime( 'now', $target_tz );
$today_midnight = new DateTime( '00:00:00', $target_tz );
if ( $today_midnight <= $now ) {
$today_midnight->add( new DateInterval( 'P1D' ) );
}
return $today_midnight->getTimestamp();
}
/**
* Add admin menu items.
*/
function properf_add_admin_menu() {
// Add top-level menu.
add_menu_page(
__( 'ProPerf Dashboard', 'properf' ),
'ProPerf',
'manage_options',
'properf',
'properf_render_dashboard',
'dashicons-chart-line',
30
);
// Add Dashboard submenu (first submenu item replaces the parent menu title).
add_submenu_page(
'properf',
__( 'ProPerf Dashboard', 'properf' ),
__( 'Dashboard', 'properf' ),
'manage_options',
'properf',
'properf_render_dashboard'
);
// Add Settings submenu.
add_submenu_page(
'properf',
__( 'ProPerf Settings', 'properf' ),
__( 'Settings', 'properf' ),
'manage_options',
'properf-settings',
'properf_render_settings'
);
}
/**
* Render Dashboard page.
*/
function properf_render_dashboard() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Unauthorized' );
}
$metrics = properf_get_live_data();
$autoloaded_data_metrics = $metrics['autoloaded_option'];
$count = $autoloaded_data_metrics['count'];
$size_bytes = $autoloaded_data_metrics['size_bytes'];
$top_size_keys = $autoloaded_data_metrics['top_size_keys'];
$last_sync = get_option( 'properf_bq_last_sync' );
if ( $last_sync ) {
$format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
$sync_time = wp_date( $format, $last_sync );
$tz_string = get_option( 'timezone_string' );
if ( $tz_string ) {
$tz_display = $tz_string;
} else {
$gmt_offset = get_option( 'gmt_offset' );
$sign = ( $gmt_offset < 0 ) ? '-' : '+';
$hours = (int) abs( $gmt_offset );
$minutes = ( abs( $gmt_offset ) * 60 ) % 60;
if ( 0 === $minutes ) {
$tz_display = sprintf( 'UTC%s%d', $sign, $hours );
} else {
$tz_display = sprintf( 'UTC%s%d:%02d', $sign, $hours, $minutes );
}
}
$last_pushed_display = $sync_time . ' (' . $tz_display . ')';
} else {
$last_pushed_display = 'Never';
}
?>
<div class="wrap">
<h1><?php esc_html_e( 'ProPerf WordPress Metrics', 'properf' ); ?></h1>
<p><strong>Last pushed to BigQuery:</strong> <?php echo esc_html( $last_pushed_display ); ?></p>
<?php settings_errors( 'properf_messages' ); ?>
<form method="post" style="margin-bottom: 20px;">
<?php wp_nonce_field( 'properf_push_action', 'properf_push_nonce' ); ?>
<input type="submit" name="properf_push_to_bq" class="button button-primary" value="Push to BigQuery">
</form>
<h2><?php esc_html_e( 'Summary Metrics', 'properf' ); ?></h2>
<table class="widefat striped">
<thead>
<tr>
<th><?php esc_html_e( 'Metric', 'properf' ); ?></th>
<th><?php esc_html_e( 'Value', 'properf' ); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong><?php esc_html_e( 'Autoloaded Option Count', 'properf' ); ?></strong></td>
<td><?php echo esc_html( number_format( $count ) ); ?></td>
</tr>
<tr>
<td><strong><?php esc_html_e( 'Autoloaded Option Size', 'properf' ); ?></strong></td>
<td><?php printf( '%.2f KB', $size_bytes / 1024 ); ?></td>
</tr>
</tbody>
</table>
<h2 style="margin-top: 30px;"><?php esc_html_e( 'Top 10 Autoloaded Options by Size', 'properf' ); ?></h2>
<?php if ( ! empty( $top_size_keys ) ) : ?>
<table class="widefat striped">
<thead>
<tr>
<th><strong><?php esc_html_e( 'Option Name', 'properf' ); ?></strong></th>
<th><strong><?php esc_html_e( 'Size', 'properf' ); ?></strong></th>
</tr>
</thead>
<tbody>
<?php foreach ( $top_size_keys as $key => $size ) : ?>
<tr>
<td><?php echo esc_html( $key ); ?></td>
<td><?php printf( '%.2f KB', $size / 1024 ); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else : ?>
<p><?php esc_html_e( 'No autoloaded option keys found or an error occurred.', 'properf' ); ?></p>
<?php endif; ?>
</div>
<?php
}
/**
* Register plugin settings.
*/
function properf_register_settings() {
register_setting(
'properf_bigquery_settings',
'properf_bigquery_project_id',
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
)
);
register_setting(
'properf_bigquery_settings',
'properf_bigquery_dataset_id',
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
)
);
register_setting(
'properf_bigquery_settings',
'properf_bigquery_table_id',
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
)
);
register_setting(
'properf_bigquery_settings',
'properf_bigquery_client_email',
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_email',
'default' => '',
)
);
register_setting(
'properf_bigquery_settings',
'properf_bigquery_private_key',
array(
'type' => 'string',
'sanitize_callback' => 'properf_sanitize_private_key',
'default' => '',
)
);
add_settings_section(
'properf_bigquery_section',
__( 'BigQuery Configuration', 'properf' ),
'properf_bigquery_section_callback',
'properf-settings'
);
add_settings_field(
'properf_bigquery_project_id',
__( 'Project ID', 'properf' ),
'properf_bigquery_project_id_field',
'properf-settings',
'properf_bigquery_section'
);
add_settings_field(
'properf_bigquery_dataset_id',
__( 'Dataset ID', 'properf' ),
'properf_bigquery_dataset_id_field',
'properf-settings',
'properf_bigquery_section'
);
add_settings_field(
'properf_bigquery_table_id',
__( 'Table ID', 'properf' ),
'properf_bigquery_table_id_field',
'properf-settings',
'properf_bigquery_section'
);
add_settings_field(
'properf_bigquery_client_email',
__( 'Client Email', 'properf' ),
'properf_bigquery_client_email_field',
'properf-settings',
'properf_bigquery_section'
);
add_settings_field(
'properf_bigquery_private_key',
__( 'Private Key', 'properf' ),
'properf_bigquery_private_key_field',
'properf-settings',
'properf_bigquery_section'
);
}
/**
* Sanitize private key field.
*
* @param string $value Private key value.
* @return string Sanitized private key.
*/
function properf_sanitize_private_key( $value ) {
// Remove any potential malicious content but preserve the key structure.
return wp_strip_all_tags( $value );
}
/**
* BigQuery section callback.
*/
function properf_bigquery_section_callback() {
echo '<p>' . esc_html__( 'Configure your Google Cloud BigQuery credentials. These settings are required for pushing metrics to BigQuery.', 'properf' ) . '</p>';
}
/**
* Project ID field.
*/
function properf_bigquery_project_id_field() {
$value = get_option( 'properf_bigquery_project_id', '' );
?>
<input type="text" name="properf_bigquery_project_id" value="<?php echo esc_attr( $value ); ?>" class="regular-text" />
<p class="description"><?php esc_html_e( 'Your Google Cloud Project ID.', 'properf' ); ?></p>
<?php
}
/**
* Dataset ID field.
*/
function properf_bigquery_dataset_id_field() {
$value = get_option( 'properf_bigquery_dataset_id', '' );
?>
<input type="text" name="properf_bigquery_dataset_id" value="<?php echo esc_attr( $value ); ?>" class="regular-text" />
<p class="description"><?php esc_html_e( 'The BigQuery dataset ID where metrics will be stored.', 'properf' ); ?></p>
<?php
}
/**
* Table ID field.
*/
function properf_bigquery_table_id_field() {
$value = get_option( 'properf_bigquery_table_id', '' );
?>
<input type="text" name="properf_bigquery_table_id" value="<?php echo esc_attr( $value ); ?>" class="regular-text" />
<p class="description"><?php esc_html_e( 'The BigQuery table ID where metrics will be stored.', 'properf' ); ?></p>
<?php
}
/**
* Client Email field.
*/
function properf_bigquery_client_email_field() {
$value = get_option( 'properf_bigquery_client_email', '' );
?>
<input type="email" name="properf_bigquery_client_email" value="<?php echo esc_attr( $value ); ?>" class="regular-text" />
<p class="description"><?php esc_html_e( 'The service account email address from your Google Cloud service account JSON key.', 'properf' ); ?></p>
<?php
}
/**
* Private Key field.
*/
function properf_bigquery_private_key_field() {
$value = get_option( 'properf_bigquery_private_key', '' );
?>
<textarea name="properf_bigquery_private_key" rows="5" class="large-text code"><?php echo esc_textarea( $value ); ?></textarea>
<p class="description"><?php esc_html_e( 'The private key from your Google Cloud service account JSON key file. Include the full key including BEGIN and END markers.', 'properf' ); ?></p>
<?php
}
/**
* Render Settings page.
*/
function properf_render_settings() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Unauthorized' );
}
// Ensure settings are registered.
global $wp_settings_sections;
if ( ! isset( $wp_settings_sections['properf-settings'] ) ) {
properf_register_settings();
}
?>
<div class="wrap">
<h1><?php esc_html_e( 'ProPerf Settings', 'properf' ); ?></h1>
<?php settings_errors( 'properf_messages' ); ?>
<form method="post" action="options.php">
<?php
settings_fields( 'properf_bigquery_settings' );
?>
<?php properf_bigquery_section_callback(); ?>
<table class="form-table" role="presentation">
<tbody>
<tr>
<th scope="row">
<label for="properf_bigquery_project_id"><?php esc_html_e( 'Project ID', 'properf' ); ?></label>
</th>
<td>
<?php properf_bigquery_project_id_field(); ?>
</td>
</tr>
<tr>
<th scope="row">
<label for="properf_bigquery_dataset_id"><?php esc_html_e( 'Dataset ID', 'properf' ); ?></label>
</th>
<td>
<?php properf_bigquery_dataset_id_field(); ?>
</td>
</tr>
<tr>
<th scope="row">
<label for="properf_bigquery_table_id"><?php esc_html_e( 'Table ID', 'properf' ); ?></label>
</th>
<td>
<?php properf_bigquery_table_id_field(); ?>
</td>
</tr>
<tr>
<th scope="row">
<label for="properf_bigquery_client_email"><?php esc_html_e( 'Client Email', 'properf' ); ?></label>
</th>
<td>
<?php properf_bigquery_client_email_field(); ?>
</td>
</tr>
<tr>
<th scope="row">
<label for="properf_bigquery_private_key"><?php esc_html_e( 'Private Key', 'properf' ); ?></label>
</th>
<td>
<?php properf_bigquery_private_key_field(); ?>
</td>
</tr>
</tbody>
</table>
<?php
submit_button( __( 'Save Settings', 'properf' ) );
?>
</form>
</div>
<?php
}
/**
* Add page parameter to settings form redirect.
*
* @param string $location Redirect location.
* @return string Modified redirect location.
*/
function properf_settings_redirect( $location ) {
if ( isset( $_POST['option_page'] ) && 'properf_bigquery_settings' === $_POST['option_page'] ) {
$location = add_query_arg( 'page', 'properf-settings', $location );
}
return $location;
}
add_filter( 'wp_redirect', 'properf_settings_redirect' );
/**
* Get live data from collector.
*
* @return array Metrics data.
*/
function properf_get_live_data() {
if ( ! class_exists( 'ProPerf_Data_Collector' ) ) {
return array(
'autoloaded_option' => array(
'count' => 'Error: Collector Class Missing',
'size_bytes' => 0,
'top_size_keys' => array(),
),
);
}
try {
$collector = new ProPerf_Data_Collector();
return $collector->get_data();
} catch ( Exception $e ) {
error_log( 'ProPerf Error: ' . $e->getMessage() );
return array(
'autoloaded_option' => array(
'count' => 'Error: ' . $e->getMessage(),
'size_bytes' => 0,
'top_size_keys' => array(),
),
);
}
}