-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjetpack-migration.php
More file actions
538 lines (478 loc) · 20.3 KB
/
jetpack-migration.php
File metadata and controls
538 lines (478 loc) · 20.3 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
<?php
/**
* CloudScale Analytics - Jetpack Migration v2.0.0
*
* Migrates historical post view counts from Jetpack into CloudScale.
*
* HOW JETPACK STORES STATS
* ------------------------
* Modern Jetpack stores all stats on WordPress.com servers. The plugin
* exposes two ways to retrieve them from your own PHP code:
*
* 1. stats_get_csv( 'postviews', 'days=-1&limit=500' )
* A Jetpack-provided wrapper that fetches all-time post view totals
* from the WP.com Stats API using the existing Jetpack site connection.
* No separate OAuth or API key needed — Jetpack handles auth.
* Returns: array of [ 'post_id' => N, 'views' => N ] rows.
*
* 2. Automattic\Jetpack\Stats\WPCOM_Stats (Jetpack >= 11.5)
* Object-oriented wrapper around the same API.
*
* 3. Local post meta (_jetpack_post_views, jetpack_post_stats)
* Only present on very old Jetpack installs (pre-2018).
*
* This migration tries all three methods in order.
*
* DOUBLE-MIGRATION PROTECTION
* After a successful run a lock is stored. Reset it via "Reset Lock" if
* you need to re-run after a database restore.
*
* @package CloudScale_Free_Analytics
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'wp_ajax_cspv_jetpack_preflight', 'cspv_ajax_jetpack_preflight' );
add_action( 'wp_ajax_cspv_jetpack_migrate', 'cspv_ajax_jetpack_migrate' );
add_action( 'wp_ajax_cspv_migration_reset_lock', 'cspv_ajax_migration_reset_lock' );
add_action( 'wp_ajax_cspv_delete_jetpack_data', 'cspv_ajax_delete_jetpack_data' );
add_action( 'wp_ajax_cspv_manual_import', 'cspv_ajax_manual_import' );
// -------------------------------------------------------------------------
// Lock helpers
// -------------------------------------------------------------------------
/**
* Check whether a migration lock is set (i.e. migration has already run).
*
* @since 1.0.0
* @return bool True if migration is locked.
*/
function cspv_migration_is_locked() {
return (bool) get_option( 'cspv_migration_complete', false );
}
/**
* Persist the migration lock with result data.
*
* @since 1.0.0
* @param mixed $data Data to store alongside the lock (e.g. stats array).
* @return void
*/
function cspv_migration_set_lock( $data ) {
update_option( 'cspv_migration_complete', $data, false );
}
/**
* Remove the migration lock so the migration can be re-run.
*
* @since 1.0.0
* @return void
*/
function cspv_migration_clear_lock() {
delete_option( 'cspv_migration_complete' );
}
// -------------------------------------------------------------------------
// Pre-flight — detect Jetpack and preview what will be imported
// -------------------------------------------------------------------------
/**
* AJAX handler: detect Jetpack and preview how many views would be imported.
*
* @since 1.0.0
* @return void Sends JSON response with preflight data.
*/
function cspv_ajax_jetpack_preflight() {
if ( ! check_ajax_referer( 'cspv_migrate', 'nonce', false ) ) {
wp_send_json_error( array( 'message' => 'Security check failed.' ), 403 );
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => 'Insufficient permissions.' ), 403 );
return;
}
$lock = get_option( 'cspv_migration_complete', false );
$result = cspv_get_jetpack_data();
$result['already_migrated'] = (bool) $lock;
$result['lock_info'] = $lock ?: null;
wp_send_json_success( $result );
}
// -------------------------------------------------------------------------
// Migration
// -------------------------------------------------------------------------
/**
* AJAX handler: execute the Jetpack stats migration.
*
* Imports historical view counts from Jetpack into CloudScale post meta
* and the V2 log table. Sets a lock on completion to prevent double-import.
*
* @since 1.0.0
* @return void Sends JSON response with migration results.
*/
function cspv_ajax_jetpack_migrate() {
if ( ! check_ajax_referer( 'cspv_migrate', 'nonce', false ) ) {
wp_send_json_error( array( 'message' => 'Security check failed.' ), 403 );
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => 'Insufficient permissions.' ), 403 );
return;
}
$lock = get_option( 'cspv_migration_complete', false );
if ( $lock ) {
wp_send_json_error( array(
'message' => 'Migration has already been run and is locked to prevent double-counting.',
'locked_at' => is_array( $lock ) ? ( $lock['date'] ?? '—' ) : '—',
'already_locked' => true,
), 409 );
return;
}
$mode = isset( $_POST['mode'] ) ? sanitize_text_field( wp_unslash( $_POST['mode'] ) ) : 'additive';
if ( ! in_array( $mode, array( 'additive', 'replace' ), true ) ) {
$mode = 'additive';
}
global $wpdb;
$table = $wpdb->prefix . 'cspv_views_v2';
$hour_bucket = current_time( 'Y-m-d H' ) . ':00:00';
$data = cspv_get_jetpack_data();
$posts = $data['posts'];
$migrated = 0;
$skipped = 0;
$total_imported = 0;
$import_time = current_time( 'mysql' );
foreach ( $posts as $item ) {
$post_id = (int) $item['post_id'];
$jp_views = (int) $item['jetpack_views'];
if ( $jp_views <= 0 ) { $skipped++; continue; }
$current_cs = (int) get_post_meta( $post_id, CSPV_META_KEY, true );
if ( $mode === 'replace' ) {
update_post_meta( $post_id, CSPV_META_KEY, $jp_views );
$to_insert = $jp_views;
} else {
$diff = max( 0, $jp_views - $current_cs );
if ( $diff <= 0 ) { $skipped++; continue; }
update_post_meta( $post_id, CSPV_META_KEY, $current_cs + $diff );
$to_insert = $diff;
}
// Upsert a single imported bucket row in V2
$wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted internal table name/expression
"INSERT INTO `{$table}` (post_id, viewed_at, view_count, source)
VALUES (%d, %s, %d, 'imported')
ON DUPLICATE KEY UPDATE view_count = %d",
$post_id, $hour_bucket, $to_insert, $to_insert
) );
$migrated++;
$total_imported += $to_insert;
}
$lock_data = array(
'date' => $import_time,
'posts_migrated' => $migrated,
'views_imported' => $total_imported,
'mode' => $mode,
'source' => $data['method'],
);
cspv_migration_set_lock( $lock_data );
$log = (array) get_option( 'cspv_migration_log', array() );
array_unshift( $log, array_merge( $lock_data, array( 'posts_skipped' => $skipped ) ) );
update_option( 'cspv_migration_log', array_slice( $log, 0, 10 ), false );
wp_send_json_success( array(
'migrated' => $migrated,
'skipped' => $skipped,
'views_imported' => $total_imported,
'mode' => $mode,
'source' => $data['method'],
) );
}
// -------------------------------------------------------------------------
// Manual CSV import — fallback for sites where API fetch fails
// One line per post: post-slug-or-id, view_count
// -------------------------------------------------------------------------
/**
* AJAX handler: manually import a CSV of post IDs and view counts.
*
* @since 1.0.0
* @return void Sends JSON response with import results.
*/
function cspv_ajax_manual_import() {
if ( ! check_ajax_referer( 'cspv_migrate', 'nonce', false ) ) {
wp_send_json_error( array( 'message' => 'Security check failed.' ), 403 );
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => 'Insufficient permissions.' ), 403 );
return;
}
$lock = get_option( 'cspv_migration_complete', false );
if ( $lock ) {
wp_send_json_error( array( 'message' => 'Migration already completed. Reset the lock to re-import.', 'already_locked' => true ), 409 );
return;
}
$raw = isset( $_POST['csv_data'] ) ? sanitize_textarea_field( wp_unslash( $_POST['csv_data'] ) ) : '';
if ( empty( $raw ) ) {
wp_send_json_error( array( 'message' => 'No CSV data provided.' ) );
return;
}
global $wpdb;
$table = $wpdb->prefix . 'cspv_views_v2';
$hour_bucket = current_time( 'Y-m-d H' ) . ':00:00';
$migrated = 0;
$skipped = 0;
$errors = array();
$import_time = current_time( 'mysql' );
$total_views = 0;
$url_cache = array();
foreach ( array_filter( array_map( 'trim', explode( "\n", $raw ) ) ) as $line ) {
if ( strpos( $line, ',' ) === false ) { $skipped++; continue; }
$parts = array_map( 'trim', explode( ',', $line, 2 ) );
$id_or_url = $parts[0];
$views = (int) $parts[1];
if ( $views <= 0 ) { $skipped++; continue; }
$post_id = 0;
if ( is_numeric( $id_or_url ) ) {
$post_id = (int) $id_or_url;
} else {
if ( isset( $url_cache[ $id_or_url ] ) ) {
$post_id = $url_cache[ $id_or_url ];
} else {
$post_id = url_to_postid( $id_or_url );
if ( ! $post_id ) {
$p = get_page_by_path( basename( rtrim( $id_or_url, '/' ) ), OBJECT, 'post' );
if ( $p ) { $post_id = $p->ID; }
}
$url_cache[ $id_or_url ] = $post_id;
}
}
if ( ! $post_id ) {
$errors[] = substr( $id_or_url, 0, 60 );
$skipped++;
continue;
}
$current = (int) get_post_meta( $post_id, CSPV_META_KEY, true );
update_post_meta( $post_id, CSPV_META_KEY, $current + $views );
// Upsert a single imported bucket row in V2
$wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted internal table name/expression
"INSERT INTO `{$table}` (post_id, viewed_at, view_count, source)
VALUES (%d, %s, %d, 'imported')
ON DUPLICATE KEY UPDATE view_count = view_count + %d",
$post_id, $hour_bucket, $views, $views
) );
$migrated++;
$total_views += $views;
}
$lock_data = array(
'date' => $import_time,
'posts_migrated' => $migrated,
'views_imported' => $total_views,
'mode' => 'manual_csv',
'source' => 'manual_import',
);
cspv_migration_set_lock( $lock_data );
$log = (array) get_option( 'cspv_migration_log', array() );
array_unshift( $log, array_merge( $lock_data, array( 'posts_skipped' => $skipped ) ) );
update_option( 'cspv_migration_log', array_slice( $log, 0, 10 ), false );
wp_send_json_success( array(
'migrated' => $migrated,
'skipped' => $skipped,
'views_imported' => $total_views,
'errors' => array_slice( $errors, 0, 10 ),
) );
}
// -------------------------------------------------------------------------
// Reset lock
// -------------------------------------------------------------------------
/**
* AJAX handler: clear the migration lock so the migration can be re-run.
*
* @since 1.0.0
* @return void Sends JSON response.
*/
function cspv_ajax_migration_reset_lock() {
if ( ! check_ajax_referer( 'cspv_migrate', 'nonce', false ) ) {
wp_send_json_error( array( 'message' => 'Security check failed.' ), 403 );
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => 'Insufficient permissions.' ), 403 );
return;
}
cspv_migration_clear_lock();
wp_send_json_success( array( 'message' => 'Lock cleared.' ) );
}
// -------------------------------------------------------------------------
// Delete Jetpack imported rows from cspv_views_v2 table
// -------------------------------------------------------------------------
/**
* AJAX handler: delete all Jetpack post_stats meta from every post.
*
* @since 1.0.0
* @return void Sends JSON response.
*/
function cspv_ajax_delete_jetpack_data() {
if ( ! check_ajax_referer( 'cspv_migrate', 'nonce', false ) ) {
wp_send_json_error( array( 'message' => 'Security check failed.' ), 403 );
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => 'Insufficient permissions.' ), 403 );
return;
}
global $wpdb;
$table = $wpdb->prefix . 'cspv_views_v2';
$deleted = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared -- no user input; table and value are hardcoded internal constants
"DELETE FROM `{$table}` WHERE source = 'imported'"
);
// Also clear the migration lock and log so the section resets cleanly.
cspv_migration_clear_lock();
delete_option( 'cspv_migration_log' );
wp_send_json_success( array(
'deleted' => (int) $deleted,
'message' => sprintf( '%d imported row(s) deleted. Migration lock and log cleared.', (int) $deleted ),
) );
}
// -------------------------------------------------------------------------
// Core: fetch Jetpack data — tries all available methods
// -------------------------------------------------------------------------
/**
* Retrieve all Jetpack post view data using available methods.
*
* Tries stats_get_csv(), then the WPCOM_Stats class, then local post meta
* in order of reliability. Returns an array keyed by post ID.
*
* @since 1.0.0
* @return array Post view data with post_id and views keys per entry.
*/
function cspv_get_jetpack_data() {
$posts = array();
$method = 'none';
$note = '';
// ── Method A: stats_get_csv() — Jetpack's own API wrapper ────────────
// This is the recommended way. It uses the existing Jetpack site
// connection (no separate auth) and fetches ALL-TIME post view totals
// from WordPress.com Stats. days=-1 means all time, limit=500 = max.
if ( function_exists( 'stats_get_csv' ) ) {
// Suppress errors — the function can return false on API failure
$rows = @stats_get_csv( 'postviews', 'days=-1&limit=500' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( is_array( $rows ) && ! empty( $rows ) ) {
foreach ( $rows as $row ) {
$pid = isset( $row['post_id'] ) ? (int) $row['post_id'] : 0;
$jv = isset( $row['views'] ) ? (int) $row['views'] : 0;
if ( $pid > 0 && $jv > 0 ) {
cspv_add_jp_post( $posts, $pid, $jv );
}
}
if ( ! empty( $posts ) ) {
$method = 'stats_get_csv';
$note = 'Fetched live from WordPress.com Stats API via stats_get_csv()';
}
}
if ( empty( $posts ) && function_exists( 'stats_get_csv' ) ) {
// Function exists but returned nothing — API likely OK but no data yet
$note = 'stats_get_csv() returned no data — your site may have very few views or the API is temporarily unavailable';
}
}
// ── Method B: Automattic\Jetpack\Stats\WPCOM_Stats (Jetpack >= 11.5) ─
if ( empty( $posts ) && class_exists( 'Automattic\\Jetpack\\Stats\\WPCOM_Stats' ) ) {
try {
$wpcom = new Automattic\Jetpack\Stats\WPCOM_Stats();
$data = $wpcom->get_top_posts( array( 'max' => 500, 'summarize' => 1 ) );
if ( ! empty( $data->summary->postviews ) ) {
foreach ( $data->summary->postviews as $row ) {
$pid = isset( $row->id ) ? (int) $row->id : 0;
$jv = isset( $row->views ) ? (int) $row->views : 0;
if ( $pid > 0 && $jv > 0 ) {
cspv_add_jp_post( $posts, $pid, $jv );
}
}
if ( ! empty( $posts ) ) {
$method = 'WPCOM_Stats';
$note = 'Fetched via Automattic\Jetpack\Stats\WPCOM_Stats class';
}
}
} catch ( Exception $e ) {
$note = 'WPCOM_Stats error: ' . $e->getMessage();
}
}
// ── Method C: Legacy local post meta (Jetpack < 2018) ─────────────────
if ( empty( $posts ) ) {
global $wpdb;
$rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared -- no user input; fully hardcoded query using core $wpdb->postmeta table name
"SELECT post_id, meta_value FROM {$wpdb->postmeta}
WHERE meta_key = '_jetpack_post_views' AND meta_value > 0
ORDER BY CAST(meta_value AS UNSIGNED) DESC LIMIT 500"
);
if ( ! empty( $rows ) ) {
foreach ( $rows as $row ) {
cspv_add_jp_post( $posts, (int) $row->post_id, (int) $row->meta_value );
}
if ( ! empty( $posts ) ) {
$method = 'post_meta_legacy';
$note = 'Found via _jetpack_post_views post meta (older Jetpack install)';
}
}
}
if ( empty( $posts ) ) {
global $wpdb;
$rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.NotPrepared -- no user input; fully hardcoded query
"SELECT post_id, meta_value FROM {$wpdb->postmeta}
WHERE meta_key = 'jetpack_post_stats' LIMIT 500"
);
if ( ! empty( $rows ) ) {
foreach ( $rows as $row ) {
$stats = maybe_unserialize( $row->meta_value );
$jv = isset( $stats['views'] ) ? (int) $stats['views'] : 0;
if ( $jv > 0 ) { cspv_add_jp_post( $posts, (int) $row->post_id, $jv ); }
}
if ( ! empty( $posts ) ) {
$method = 'post_meta_stats';
$note = 'Found via jetpack_post_stats post meta';
}
}
}
// ── Detect Jetpack presence so we can report useful status ────────────
$jetpack_active = function_exists( 'stats_get_csv' )
|| class_exists( 'Automattic\\Jetpack\\Stats\\WPCOM_Stats' )
|| defined( 'JETPACK__VERSION' )
|| is_plugin_active( 'jetpack/jetpack.php' );
if ( ! $jetpack_active ) {
$note = 'Jetpack plugin does not appear to be active on this site';
} elseif ( empty( $posts ) && empty( $note ) ) {
$note = 'Jetpack is active but returned no view data. The stats_get_csv() function may need a few seconds — try again, or check that the Stats module is enabled in Jetpack settings.';
}
$total_jp = 0;
$total_cs = 0;
foreach ( $posts as $p ) {
$total_jp += $p['jetpack_views'];
$total_cs += $p['cs_views'];
}
return array(
'jetpack_active' => $jetpack_active,
'method' => $method,
'note' => $note,
'cloud_only' => ( $jetpack_active && empty( $posts ) && function_exists( 'stats_get_csv' ) ),
'posts_found' => count( $posts ),
'total_jp_views' => $total_jp,
'total_cs_views' => $total_cs,
'posts' => array_values( $posts ),
);
}
// -------------------------------------------------------------------------
// Helper: resolve a post ID and add it to the working array
// -------------------------------------------------------------------------
/**
* Resolve a post ID and add it to the migration working array if valid.
*
* @since 1.0.0
* @param array $posts Working array of posts to migrate, passed by reference.
* @param int $post_id Post ID to add.
* @param int $jp_views Jetpack view count for this post.
* @return void
*/
function cspv_add_jp_post( &$posts, $post_id, $jp_views ) {
$post = get_post( $post_id );
if ( ! $post || ! in_array( $post->post_status, array( 'publish', 'private' ), true ) ) {
return;
}
$cv = (int) get_post_meta( $post->ID, CSPV_META_KEY, true );
$posts[ $post->ID ] = array(
'post_id' => $post->ID,
'title' => $post->post_title,
'jetpack_views' => $jp_views,
'cs_views' => $cv,
'will_add' => max( 0, $jp_views - $cv ),
);
}