Repository navigation
Expand file tree
/
Copy pathclockwork-offloader.php
More file actions
1049 lines (899 loc) · 34 KB
/
Copy pathclockwork-offloader.php
File metadata and controls
1049 lines (899 loc) · 34 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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Clockwork Offloader
* Plugin URI: https://clockworkplugins.com/plugins/clockwork-offloader
* Description: High-performance cloud storage offloader for WordPress. Automatically offload media uploads to Amazon S3, Cloudflare R2, DigitalOcean Spaces, Wasabi, or Backblaze B2 with seamless URL delivery and local storage space reclamation.
* Version: 1.1.2
* Author: Aaron Reimann
* Author URI: https://aaronreimann.com
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: clockwork-offloader
* Domain Path: /languages
* Requires at least: 5.0
* Requires PHP: 8.2
* Tested up to: 7.1
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Define plugin constants
if ( ! defined( 'CLOCKWORK_OFFLOADER_VERSION' ) ) {
define( 'CLOCKWORK_OFFLOADER_VERSION', '1.1.2' );
}
if ( ! defined( 'CLOCKWORK_OFFLOADER_PLUGIN_DIR' ) ) {
define( 'CLOCKWORK_OFFLOADER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'CLOCKWORK_OFFLOADER_PLUGIN_URL' ) ) {
define( 'CLOCKWORK_OFFLOADER_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'CLOCKWORK_OFFLOADER_PLUGIN_BASENAME' ) ) {
define( 'CLOCKWORK_OFFLOADER_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
}
/**
* Check if Clockwork Offloader Pro is active (or network-active).
*
* @return bool
*/
function clockwork_offloader_is_pro_active() {
if ( class_exists( 'Clockwork_Offloader_Pro' ) ) {
return true;
}
if ( function_exists( 'get_option' ) ) {
$active_plugins = (array) get_option( 'active_plugins', array() );
if ( in_array( 'clockwork-offloader-pro/clockwork-offloader-pro.php', $active_plugins, true ) ) {
return true;
}
if ( function_exists( 'is_multisite' ) && is_multisite() && function_exists( 'get_site_option' ) ) {
$network_plugins = (array) get_site_option( 'active_sitewide_plugins', array() );
if ( isset( $network_plugins['clockwork-offloader-pro/clockwork-offloader-pro.php'] ) ) {
return true;
}
}
}
return false;
}
// Activation hook guard: prevent co-activation if Pro is active
register_activation_hook( __FILE__, function( $network_wide = false ) {
if ( clockwork_offloader_is_pro_active() ) {
wp_die( esc_html__( 'Clockwork Offloader Pro is already active. Clockwork Offloader Lite cannot be activated alongside Pro.', 'clockwork-offloader' ) );
}
if ( class_exists( 'Clockwork_Offloader' ) ) {
Clockwork_Offloader::activate( $network_wide );
}
} );
// If Pro is active, yield immediately — do not define classes or wire runtime hooks
if ( clockwork_offloader_is_pro_active() ) {
return;
}
/**
* Main plugin class
*/
class Clockwork_Offloader {
/**
* Instance of this class
*
* @var Clockwork_Offloader
*/
private static $instance = null;
/**
* Get instance of this class
*
* @return Clockwork_Offloader
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct() {
$this->load_dependencies();
$this->init_hooks();
}
/**
* Load required files
*/
private function load_dependencies() {
// Load Composer autoloader if it exists
if ( file_exists( CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'vendor/autoload.php' ) ) {
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'vendor/autoload.php';
}
// Load plugin classes
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-settings-helper.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-offload-tracker.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-s3-service.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-url-rewriter.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-lite-restrictions.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-admin.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-media-library.php';
}
/**
* Initialize hooks
*/
private function init_hooks() {
// Activation and deactivation hooks
register_activation_hook( __FILE__, array( 'Clockwork_Offloader', 'activate' ) );
register_deactivation_hook( __FILE__, array( 'Clockwork_Offloader', 'deactivate' ) );
// Load plugin text domain for i18n
add_action( 'init', array( $this, 'load_textdomain' ) );
// Multisite: Create tables when new site is created. wp_initialize_site replaced the
// deprecated wpmu_new_blog in WP 5.1; priority 200 runs after core has populated the
// new site's tables.
if ( is_multisite() ) {
add_action( 'wp_initialize_site', array( 'Clockwork_Offloader', 'activate_new_site' ), 200 );
}
// Migrate R2/GCS settings to AWS (backward compatibility)
add_action( 'admin_init', array( $this, 'migrate_unsupported_providers' ) );
// Upgrade the offloads table schema for existing installs. Runs here (not just on
// register_activation_hook) because WordPress never fires the activation hook when
// plugin files are updated in place without an explicit deactivate/reactivate.
add_action( 'admin_init', array( 'Clockwork_Offloader_Tracker', 'maybe_upgrade_table' ) );
// Everything that depends on whether Pro is present is wired on plugins_loaded, after
// every plugin file has been included. Doing it at include time made the result depend
// on plugin load order (alphabetical by directory), so Pro's AJAX handlers and queue
// cron silently never registered when Lite's directory sorted before Pro's.
add_action( 'plugins_loaded', array( $this, 'init_runtime' ), 20 );
// Initialize auto-offload hooks
add_action( 'add_attachment', array( $this, 'handle_new_attachment' ), 10, 1 );
add_filter( 'wp_generate_attachment_metadata', array( $this, 'handle_attachment_metadata' ), 10, 2 );
// Clear statistics cache when attachments are deleted
add_action( 'delete_attachment', array( $this, 'handle_delete_attachment' ), 10, 1 );
}
/**
* Wire up admin, URL rewriting and (when Pro is active) queue processing.
* Runs on plugins_loaded priority 20 — see init_hooks().
*/
public function init_runtime() {
// Initialize admin
if ( is_admin() ) {
new Clockwork_Offloader_Admin();
new Clockwork_Offloader_Media_Library();
}
// Initialize URL rewriter
Clockwork_Offloader_URL_Rewriter::get_instance();
// Initialize queue processing (Pro-only)
if ( class_exists( 'Clockwork_Offloader_Pro' ) ) {
$this->init_queue();
}
/**
* Fires once Lite (and Pro, if present) have finished wiring their hooks.
*/
do_action( 'clockwork_offloader_loaded', $this );
}
/**
* Plugin activation
*
* @param bool $network_wide True when network-activated on a multisite.
*/
public static function activate( $network_wide = false ) {
// Yield to Pro if already active
if ( class_exists( 'Clockwork_Offloader_Pro' ) || ( function_exists( 'is_plugin_active' ) && is_plugin_active( 'clockwork-offloader-pro/clockwork-offloader-pro.php' ) ) ) {
wp_die( esc_html__( 'Clockwork Offloader Pro is already active. The Lite version is not needed and cannot be activated alongside Pro.', 'clockwork-offloader' ) );
}
// Run migration from old plugin name if needed
self::migrate_from_cloudbound();
// Load tracker class and settings helper
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-settings-helper.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-offload-tracker.php';
if ( is_multisite() && $network_wide ) {
// Tables are per-site ($wpdb->prefix), so create them on every existing site now
// rather than lazily on each site's first admin visit.
$site_ids = get_sites( array( 'fields' => 'ids', 'number' => 0 ) );
foreach ( $site_ids as $site_id ) {
switch_to_blog( $site_id );
self::activate_site();
restore_current_blog();
}
} else {
self::activate_site();
}
// Flush rewrite rules
flush_rewrite_rules();
}
/**
* Per-site activation: create tables and default options for the current blog.
*/
private static function activate_site() {
// Create tables for current site
Clockwork_Offloader_Tracker::create_table();
// The queue table belongs to Pro. Only Pro ships class-queue.php, so never require it
// from here — just create the table if Pro is already loaded.
if ( class_exists( 'Clockwork_Offloader_Queue' ) ) {
Clockwork_Offloader_Queue::create_table();
}
// Track installation date for Lite auto-offload restriction
if ( ! get_option( 'clockwork_offloader_installed_date' ) ) {
add_option( 'clockwork_offloader_installed_date', time() );
}
// Set default site options (only if not already set from migration)
// In multisite, each site gets its own settings unless network mode is enabled
$existing_settings = get_option( 'clockwork_offloader_settings' );
if ( ! $existing_settings ) {
$defaults = array(
'provider' => 'aws', // Default to AWS for backward compatibility
'auto_offload' => false,
'delete_after_upload' => false,
'rewrite_urls' => false,
's3_region' => 'us-east-1',
's3_base_path' => '',
'queue_batch_size' => 10,
'enable_throttle' => false,
'throttle_rate' => 100,
'show_media_library_status' => true, // Default to ON
'development_mode' => false,
);
add_option( 'clockwork_offloader_settings', $defaults );
} else {
// Ensure existing installations have provider set to 'aws' for backward compatibility
$settings = $existing_settings;
if ( ! isset( $settings['provider'] ) ) {
$settings['provider'] = 'aws';
update_option( 'clockwork_offloader_settings', $settings );
}
}
}
/**
* Create tables for a new site in multisite.
* Hooked to wp_initialize_site.
*
* @param WP_Site|int $site New site object (or a blog ID, for callers using the old hook).
*/
public static function activate_new_site( $site ) {
if ( ! is_multisite() ) {
return;
}
$blog_id = ( $site instanceof WP_Site ) ? (int) $site->blog_id : (int) $site;
if ( ! $blog_id ) {
return;
}
// Load required classes
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-settings-helper.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-offload-tracker.php';
// Switch to new site and create tables
switch_to_blog( $blog_id );
self::activate_site();
restore_current_blog();
}
/**
* Plugin deactivation
*/
public static function deactivate() {
// Clear any transients
delete_transient( 'clockwork_offloader_s3_connection_test' );
}
/**
* Handle new attachment upload
*
* @param int $attachment_id Attachment ID
*/
public function handle_new_attachment( $attachment_id ) {
$settings = Clockwork_Offloader_Settings_Helper::get_settings();
// Only auto-offload if enabled
if ( empty( $settings['auto_offload'] ) ) {
return;
}
// Check if S3 is configured
if ( ! $this->is_s3_configured() ) {
return;
}
// Lite restriction: Only offload files uploaded after plugin installation
// Pro can offload all files
if ( ! class_exists( 'Clockwork_Offloader_Pro' ) ) {
$installed_date = get_option( 'clockwork_offloader_installed_date' );
if ( $installed_date ) {
$attachment_date = get_post_time( 'U', false, $attachment_id );
if ( $attachment_date && $attachment_date < $installed_date ) {
// File was uploaded before plugin installation - don't auto-offload in Lite
return;
}
}
}
// Offload the original file. Never delete it here: add_attachment fires inside
// wp_insert_attachment(), BEFORE WordPress generates thumbnails / the -scaled copy from
// this file. Local deletion (if enabled) happens in handle_attachment_metadata().
$this->offload_attachment_file( $attachment_id, get_attached_file( $attachment_id ) );
}
/**
* Handle attachment metadata generation (image sizes)
*
* Runs after WordPress has generated every intermediate size, so this is the one place
* where it is safe to offload the whole set and, if delete-after-upload is on, remove
* the local copies.
*
* @param array $metadata Attachment metadata
* @param int $attachment_id Attachment ID
* @return array
*/
public function handle_attachment_metadata( $metadata, $attachment_id ) {
$settings = Clockwork_Offloader_Settings_Helper::get_settings();
// Only auto-offload if enabled
if ( empty( $settings['auto_offload'] ) ) {
return $metadata;
}
// Check if S3 is configured
if ( ! $this->is_s3_configured() ) {
return $metadata;
}
$tracker = new Clockwork_Offloader_Tracker();
$files = self::get_attachment_files( $attachment_id, $metadata );
// Offload original (if add_attachment didn't already), every size, and the full-res
// original behind a -scaled image.
foreach ( $files as $size_name => $file_path ) {
if ( file_exists( $file_path ) && ! $tracker->is_offloaded( $attachment_id, $size_name ) ) {
$this->offload_attachment_file( $attachment_id, $file_path, $size_name );
}
}
// Delete local copies only once everything above is confirmed offloaded.
if ( ! empty( $settings['delete_after_upload'] ) ) {
foreach ( $files as $size_name => $file_path ) {
if ( file_exists( $file_path ) && $tracker->is_offloaded( $attachment_id, $size_name ) ) {
self::delete_local_file( $file_path );
}
}
}
return $metadata;
}
/**
* Every local file that belongs to an attachment, keyed by the size_name the tracker
* uses for it: '' for the attached file, each intermediate size by name, and
* 'original_image' for the full-resolution original behind a -scaled image.
*
* @param int $attachment_id Attachment ID
* @param array|null $metadata Attachment metadata (fetched if null)
* @return array<string, string> size_name => absolute path
*/
public static function get_attachment_files( $attachment_id, $metadata = null ) {
$files = array();
$file_path = get_attached_file( $attachment_id );
if ( ! $file_path ) {
return $files;
}
$files[''] = $file_path;
if ( null === $metadata ) {
$metadata = wp_get_attachment_metadata( $attachment_id );
}
if ( ! is_array( $metadata ) ) {
return $files;
}
$file_dir = dirname( $file_path );
if ( ! empty( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
foreach ( $metadata['sizes'] as $size_name => $size_data ) {
if ( ! empty( $size_data['file'] ) ) {
// Guard against directory traversal in crafted metadata
$clean_filename = function_exists( 'wp_basename' ) ? wp_basename( $size_data['file'] ) : basename( $size_data['file'] );
if ( $clean_filename === $size_data['file'] ) {
$files[ $size_name ] = $file_dir . '/' . $clean_filename;
}
}
}
}
if ( ! empty( $metadata['original_image'] ) ) {
$clean_original = function_exists( 'wp_basename' ) ? wp_basename( $metadata['original_image'] ) : basename( $metadata['original_image'] );
if ( $clean_original === $metadata['original_image'] ) {
$files['original_image'] = $file_dir . '/' . $clean_original;
}
}
return $files;
}
/**
* Check if a file path is safely confined within this site's uploads directory.
* Prevents directory traversal and sibling directory attacks (e.g. uploads-evil).
*
* @param string $file_path Absolute file path.
* @return bool True if inside uploads directory, false otherwise.
*/
public static function is_valid_upload_path( $file_path ) {
if ( empty( $file_path ) ) {
return false;
}
$upload_dir = wp_upload_dir();
if ( empty( $upload_dir['basedir'] ) ) {
return false;
}
$real_upload_dir = realpath( $upload_dir['basedir'] );
if ( false === $real_upload_dir ) {
return false;
}
// Ensure trailing separator so sibling directories (e.g. uploads-evil) never match
$real_upload_dir = rtrim( $real_upload_dir, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR;
// If target file or directory doesn't exist yet, resolve the nearest existing parent
$test_dir = dirname( $file_path );
while ( ! empty( $test_dir ) && '.' !== $test_dir && '/' !== $test_dir && ! file_exists( $test_dir ) ) {
$parent = dirname( $test_dir );
if ( $parent === $test_dir ) {
break;
}
$test_dir = $parent;
}
$real_dir = realpath( $test_dir );
if ( false === $real_dir ) {
return false;
}
$real_dir = rtrim( $real_dir, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR;
return 0 === strpos( $real_dir, $real_upload_dir );
}
/**
* Delete a local file, but only if it lives inside this site's uploads directory.
*
* @param string $file_path Absolute path
* @return bool
*/
public static function delete_local_file( $file_path ) {
if ( ! self::is_valid_upload_path( $file_path ) ) {
return false;
}
return wp_delete_file( $file_path );
}
/**
* Handle attachment deletion
*
* This hook fires when an attachment is deleted from the media library.
* It ensures that:
* 1. Files are deleted from S3
* 2. Database records are removed
* 3. Statistics cache is cleared
*
* Note: wp_delete_attachment() already handles deleting local files from the server.
*
* @param int $attachment_id Attachment ID
* @param WP_Post $post Post object (optional, WordPress 5.5+)
*/
public function handle_delete_attachment( $attachment_id, $post = null ) {
// Ensure we have a valid attachment ID
if ( empty( $attachment_id ) || ! is_numeric( $attachment_id ) ) {
return;
}
// Verify it's actually an attachment
if ( $post && 'attachment' !== $post->post_type ) {
return;
}
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-offload-tracker.php';
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-s3-service.php';
$tracker = new Clockwork_Offloader_Tracker();
$s3_service = new Clockwork_Offloader_S3_Service();
// Get all offload records for this attachment (all sizes)
// This includes all image sizes that were offloaded
$offloads = $tracker->get_attachment_offloads( $attachment_id );
// Delete each file from S3
if ( ! empty( $offloads ) ) {
foreach ( $offloads as $offload ) {
if ( empty( $offload->s3_key ) ) {
continue;
}
$delete_result = $s3_service->delete_file( $offload->s3_key );
if ( is_wp_error( $delete_result ) ) {
// Log error for debugging (only if WP_DEBUG is enabled)
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( sprintf(
'Clockwork Offloader: Failed to delete %s from S3: %s',
$offload->s3_key,
$delete_result->get_error_message()
) );
}
// Continue trying to delete other files even if one fails
continue;
}
// Delete database record if S3 deletion was successful
$tracker->delete_record( $attachment_id, $offload->size_name );
}
}
// Clear statistics cache when attachments are deleted
$tracker->clear_statistics_cache();
}
/**
* Offload a single file for an attachment
*
* @param int $attachment_id Attachment ID
* @param string $file_path Local file path
* @param string $size_name Image size name (optional)
*/
private function offload_attachment_file( $attachment_id, $file_path, $size_name = '' ) {
if ( ! file_exists( $file_path ) ) {
return;
}
// Check if already offloaded
$tracker = new Clockwork_Offloader_Tracker();
if ( $tracker->is_offloaded( $attachment_id, $size_name ) ) {
return;
}
$s3_service = new Clockwork_Offloader_S3_Service();
// Upload to S3
$result = $s3_service->upload_file( $file_path, $attachment_id, $size_name );
if ( is_wp_error( $result ) ) {
// Log error using WordPress debug log
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
error_log( 'Clockwork Offloader: Failed to upload ' . esc_html( $file_path ) . ' - ' . esc_html( $result->get_error_message() ) );
}
return;
}
// Track in database
$tracker->record_offload(
$attachment_id,
$result['bucket'],
$result['s3_key'],
$file_path,
filesize( $file_path ),
$size_name
);
// Local deletion is deliberately NOT done here — see handle_attachment_metadata().
}
/**
* Load plugin textdomain for translations.
*/
public function load_textdomain() {
load_plugin_textdomain( 'clockwork-offloader', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
/**
* Offload an attachment and all its intermediate sizes to cloud storage.
*
* @param int $attachment_id Attachment ID.
* @return array{files_offloaded: int, errors: array<string>}
*/
public function offload_attachment( $attachment_id ) {
if ( ! $this->is_s3_configured() ) {
return array(
'files_offloaded' => 0,
'errors' => array( __( 'Cloud storage is not configured.', 'clockwork-offloader' ) ),
);
}
$tracker = new Clockwork_Offloader_Tracker();
$files = self::get_attachment_files( $attachment_id );
$offloaded = 0;
$errors = array();
if ( empty( $files ) ) {
return array(
'files_offloaded' => 0,
'errors' => array( __( 'No files found for this attachment.', 'clockwork-offloader' ) ),
);
}
foreach ( $files as $size_name => $file_path ) {
if ( ! file_exists( $file_path ) ) {
continue;
}
// Security check: confine file strictly within this site's uploads directory
if ( ! self::is_valid_upload_path( $file_path ) ) {
$errors[] = sprintf(
/* translators: %s: file path */
__( 'Security check failed: File path is outside the uploads directory (%s).', 'clockwork-offloader' ),
basename( $file_path )
);
continue;
}
if ( $tracker->is_offloaded( $attachment_id, $size_name ) ) {
$offloaded++;
continue;
}
$s3_service = new Clockwork_Offloader_S3_Service();
$result = $s3_service->upload_file( $file_path, $attachment_id, $size_name );
if ( is_wp_error( $result ) ) {
$errors[] = sprintf(
/* translators: 1: file name, 2: error message */
__( 'Failed to upload %1$s: %2$s', 'clockwork-offloader' ),
basename( $file_path ),
$result->get_error_message()
);
} else {
$tracker->record_offload(
$attachment_id,
$result['bucket'],
$result['s3_key'],
$file_path,
filesize( $file_path ),
$size_name
);
$offloaded++;
}
}
// If nothing was on disk and nothing was uploaded, return an error
if ( 0 === $offloaded && empty( $errors ) ) {
$errors[] = __( 'No local files were found on disk to upload.', 'clockwork-offloader' );
}
$settings = Clockwork_Offloader_Settings_Helper::get_settings();
if ( ! empty( $settings['delete_after_upload'] ) ) {
foreach ( $files as $size_name => $file_path ) {
if ( file_exists( $file_path ) && $tracker->is_offloaded( $attachment_id, $size_name ) ) {
self::delete_local_file( $file_path );
}
}
}
return array(
'files_offloaded' => $offloaded,
'errors' => $errors,
);
}
/**
* Restore an attachment from cloud storage back to the local server.
*
* @param int $attachment_id Attachment ID.
* @return array{files_restored: int, errors: array<string>}
*/
public function restore_attachment( $attachment_id ) {
$tracker = new Clockwork_Offloader_Tracker();
$offloads = $tracker->get_attachment_offloads( $attachment_id );
if ( empty( $offloads ) ) {
return array(
'files_restored' => 0,
'errors' => array( __( 'Attachment is not offloaded to Cloud.', 'clockwork-offloader' ) ),
);
}
$s3_service = new Clockwork_Offloader_S3_Service();
$restored = 0;
$errors = array();
foreach ( $offloads as $offload ) {
$local_path = $offload->file_path;
// Security check: confine restore destination strictly within this site's uploads directory
if ( ! self::is_valid_upload_path( $local_path ) ) {
$errors[] = sprintf(
/* translators: %s: file path */
__( 'Security check failed: Destination path is outside the uploads directory (%s).', 'clockwork-offloader' ),
basename( $local_path )
);
continue;
}
if ( file_exists( $local_path ) ) {
$restored++;
continue;
}
// Ensure target directory exists safely
$dir = dirname( $local_path );
if ( ! file_exists( $dir ) ) {
wp_mkdir_p( $dir );
}
$result = $s3_service->download_file( $offload->s3_key, $local_path );
if ( is_wp_error( $result ) ) {
$errors[] = sprintf(
/* translators: 1: file name, 2: error message */
__( 'Failed to restore %1$s: %2$s', 'clockwork-offloader' ),
basename( $local_path ),
$result->get_error_message()
);
} else {
$restored++;
}
}
if ( 0 === $restored && empty( $errors ) ) {
$errors[] = __( 'No files were restored from Cloud.', 'clockwork-offloader' );
}
return array(
'files_restored' => $restored,
'errors' => $errors,
);
}
/**
* Check if S3 is properly configured
*
* @return bool
*/
private function is_s3_configured() {
$settings = Clockwork_Offloader_Settings_Helper::get_settings();
// Check if credentials exist (either in wp-config or database)
$has_credentials = false;
$wp_config_creds = Clockwork_Offloader_Settings_Helper::get_wp_config_credentials();
if ( $wp_config_creds && ! empty( $wp_config_creds['access-key-id'] ) && ! empty( $wp_config_creds['secret-access-key'] ) ) {
$has_credentials = true;
} else {
// Check database settings
$has_credentials = ! empty( $settings['s3_access_key'] ) && ! empty( $settings['s3_secret_key'] );
}
// Bucket and region are always from database settings
return $has_credentials &&
! empty( $settings['s3_bucket'] ) &&
! empty( $settings['s3_region'] );
}
/**
* Initialize queue processing
*/
private function init_queue() {
// Add custom cron interval
add_filter( 'cron_schedules', array( $this, 'add_queue_cron_interval' ) );
// Register queue processing hook
add_action( 'clockwork_offloader_process_queue', array( $this, 'process_queue_cron' ) );
}
/**
* Add custom cron interval for queue processing
*
* @param array $schedules Existing schedules
* @return array
*/
public function add_queue_cron_interval( $schedules ) {
$schedules['clockwork_offloader_queue_interval'] = array(
'interval' => 60, // Every minute
'display' => __( 'Every Minute (Clockwork Offloader Queue)', 'clockwork-offloader' ),
);
return $schedules;
}
/**
* Process queue via cron
*
* Uses adaptive batch sizing for smooth processing of large queues (10,000+ items)
*/
public function process_queue_cron() {
$queue = new Clockwork_Offloader_Queue();
// Get queue statistics to determine optimal batch size
$queue_stats = $queue->get_statistics();
$pending_count = $queue_stats['pending'];
// Adaptive batch sizing based on queue size
// For very large queues, process more items per batch to make faster progress
if ( $pending_count > 10000 ) {
// Very large queue: process 50 items per batch
$batch_size = 50;
} elseif ( $pending_count > 5000 ) {
// Large queue: process 30 items per batch
$batch_size = 30;
} elseif ( $pending_count > 1000 ) {
// Medium queue: process 20 items per batch
$batch_size = 20;
} else {
// Small queue: use settings or default
$settings = Clockwork_Offloader_Settings_Helper::get_settings();
$batch_size = ! empty( $settings['queue_batch_size'] ) ? absint( $settings['queue_batch_size'] ) : 10;
}
// Process batch
$stats = $queue->process_batch( $batch_size );
// Update last processing time
update_option( 'clockwork_offloader_last_queue_process', time() );
// If no more items, unschedule
$queue_stats = $queue->get_statistics();
if ( $queue_stats['pending'] === 0 && $queue_stats['processing'] === 0 ) {
$timestamp = wp_next_scheduled( 'clockwork_offloader_process_queue' );
if ( $timestamp ) {
wp_unschedule_event( $timestamp, 'clockwork_offloader_process_queue' );
}
}
}
/**
* Migrate data from old CloudBound Offloader plugin
*/
private static function migrate_from_cloudbound() {
global $wpdb;
// Migrate database tables
$old_table_offloads = $wpdb->prefix . 'cloudbound_offloads';
$new_table_offloads = $wpdb->prefix . 'clockwork_offloads';
$old_table_queue = $wpdb->prefix . 'cloudbound_offload_queue';
$new_table_queue = $wpdb->prefix . 'clockwork_offload_queue';
// Check if old tables exist and new ones don't
// Note: SHOW TABLES LIKE doesn't work with $wpdb->prepare(), so we use esc_sql() instead
$old_table_offloads_escaped = esc_sql( $old_table_offloads );
$new_table_offloads_escaped = esc_sql( $new_table_offloads );
$old_table_queue_escaped = esc_sql( $old_table_queue );
$new_table_queue_escaped = esc_sql( $new_table_queue );
$old_offloads_exists = $wpdb->get_var( "SHOW TABLES LIKE '{$old_table_offloads_escaped}'" ) === $old_table_offloads;
$new_offloads_exists = $wpdb->get_var( "SHOW TABLES LIKE '{$new_table_offloads_escaped}'" ) === $new_table_offloads;
if ( $old_offloads_exists && ! $new_offloads_exists ) {
$wpdb->query( "RENAME TABLE `{$old_table_offloads_escaped}` TO `{$new_table_offloads_escaped}`" );
}
$old_queue_exists = $wpdb->get_var( "SHOW TABLES LIKE '{$old_table_queue_escaped}'" ) === $old_table_queue;
$new_queue_exists = $wpdb->get_var( "SHOW TABLES LIKE '{$new_table_queue_escaped}'" ) === $new_table_queue;
if ( $old_queue_exists && ! $new_queue_exists ) {
$wpdb->query( "RENAME TABLE `{$old_table_queue_escaped}` TO `{$new_table_queue_escaped}`" );
}
// Migrate options
$old_settings = get_option( 'cloudbound_offloader_settings' );
$current_settings = get_option( 'clockwork_offloader_settings' );
if ( $old_settings !== false && $current_settings === false ) {
update_option( 'clockwork_offloader_settings', $old_settings );
delete_option( 'cloudbound_offloader_settings' );
}
$old_last_process = get_option( 'cloudbound_offloader_last_queue_process' );
if ( $old_last_process !== false && get_option( 'clockwork_offloader_last_queue_process' ) === false ) {
update_option( 'clockwork_offloader_last_queue_process', $old_last_process );
delete_option( 'cloudbound_offloader_last_queue_process' );
}
// Migrate transients
$old_transient = get_transient( 'cloudbound_offloader_s3_connection_test' );
if ( $old_transient !== false ) {
set_transient( 'clockwork_offloader_s3_connection_test', $old_transient, 3600 );
delete_transient( 'cloudbound_offloader_s3_connection_test' );
}
$old_stats = get_transient( 'cloudbound_offloader_stats' );
if ( $old_stats !== false ) {
set_transient( 'clockwork_offloader_stats', $old_stats, 3600 );
delete_transient( 'cloudbound_offloader_stats' );
}
// Migrate postmeta
$wpdb->query( $wpdb->prepare(
"UPDATE {$wpdb->postmeta} SET meta_key = %s WHERE meta_key = %s",
'_clockwork_dev_file',
'_cloudbound_dev_file'
) );
// Migrate dev attachment IDs option
$old_dev_ids = get_option( 'cloudbound_dev_attachment_ids' );
if ( $old_dev_ids !== false && get_option( 'clockwork_dev_attachment_ids' ) === false ) {
update_option( 'clockwork_dev_attachment_ids', $old_dev_ids );
delete_option( 'cloudbound_dev_attachment_ids' );
}
// Migrate cron jobs
$old_cron_hook = 'cloudbound_offloader_process_queue';
$new_cron_hook = 'clockwork_offloader_process_queue';
$crons = _get_cron_array();
if ( $crons ) {
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[ $old_cron_hook ] ) ) {
$cron[ $new_cron_hook ] = $cron[ $old_cron_hook ];
unset( $cron[ $old_cron_hook ] );
$crons[ $timestamp ] = $cron;
}
}
_set_cron_array( $crons );
}
}
/**
* Migrate unsupported providers (R2/GCS) to AWS
* Called on admin_init for backward compatibility
*/
public function migrate_unsupported_providers() {
// Only run once per user
$migration_done = get_user_meta( get_current_user_id(), 'clockwork_provider_migration_done', true );
if ( $migration_done ) {
return;
}
// Load settings helper
require_once CLOCKWORK_OFFLOADER_PLUGIN_DIR . 'includes/class-settings-helper.php';
$settings = Clockwork_Offloader_Settings_Helper::get_settings();
$provider = isset( $settings['provider'] ) ? $settings['provider'] : 'aws';
// Check if provider is unsupported (R2 or GCS)
if ( $provider === 'cloudflare' || $provider === 'gcp' ) {
// Store original provider for notice
$original_provider = $provider;
// Convert to AWS
$settings['provider'] = 'aws';
// Store original provider temporarily for notice
$settings['_original_provider'] = $original_provider;
// Remove R2 account ID if present
if ( isset( $settings['r2_account_id'] ) ) {
unset( $settings['r2_account_id'] );
}
// Save updated settings
Clockwork_Offloader_Settings_Helper::update_settings( $settings );
// Store original provider in transient for notice
set_transient( 'clockwork_provider_migration_notice', $original_provider, DAY_IN_SECONDS );
// Show admin notice
add_action( 'admin_notices', array( $this, 'show_provider_migration_notice' ) );