-
Notifications
You must be signed in to change notification settings - Fork 15
/
s3-media-storage.php
500 lines (425 loc) · 15.4 KB
/
s3-media-storage.php
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
<?php
/**
* @package S3 Media Storage
*/
/*
Plugin Name: S3 Media Storage
Description: Store media library contents onto S3 directly without the need for temporarily storing files on the filesystem/cron jobs. This is more ideal for multiple web server environemnts.
Version: 1.0.3
Author: Anthony Gentile
Author URI: http://agentile.com
*/
/* Copyright 2013 Anthony Gentile (email : [email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Don't expose any info if called directly
if ( !function_exists( 'add_action' ) ) {
echo 'S3 Media Storage WordPress Plugin';
exit;
}
define('S3MS_PLUGIN_VERSION', '1.0.3');
define('S3MS_PLUGIN_URL', plugin_dir_url( __FILE__ ));
register_activation_hook(__FILE__, array('S3MS', 'install'));
register_uninstall_hook(__FILE__, array('S3MS', 'uninstall'));
if ( is_admin() ) {
require_once dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'admin.php';
}
/**
* S3MS
*
* @category S3MS
* @package S3 Media Storage
*
* @author Anthony Gentile <[email protected]>
*/
class S3MS {
/**
* Static settings
*/
public static $settings = null;
/**
* Hook for plugin install
*/
public static function install()
{
}
/**
* Hook for plugin uninstall
*/
public static function uninstall()
{
}
public static function getSettings()
{
if (!self::$settings) {
self::$settings = json_decode(get_option('S3MS_settings'), true);
}
return self::$settings;
}
public static function attachmentUrl($url, $post_id)
{
$custom_fields = get_post_custom($post_id);
$bucket = isset($custom_fields['S3MS_bucket']) ? $custom_fields['S3MS_bucket'][0] : null;
$bucket_path = isset($custom_fields['S3MS_bucket_path']) ? $custom_fields['S3MS_bucket_path'][0] : null;
// Was this a file we even uploaded to S3? If not bail.
if (!$bucket || trim($bucket) == '') {
return $url;
}
$upload_dir = wp_upload_dir();
$file = str_replace($upload_dir['baseurl'], '', $url);
if (substr($file, 0, 1) == '/') {
$file = substr($file, 1);
}
// $file = isset($custom_fields['S3MS_file']) ? $custom_fields['S3MS_file'][0] : null;
$cloudfront = isset($custom_fields['S3MS_cloudfront']) ? $custom_fields['S3MS_cloudfront'][0] : null;
$settings = self::getSettings();
// Determine protocol to serve from
if ($settings['s3_protocol'] == 'http') {
$protocol = 'http://';
} elseif ($settings['s3_protocol'] == 'https') {
$protocol = 'https://';
} elseif ($settings['s3_protocol'] == 'relative') {
$protocol = 'http://';
if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] === '443') {
$protocol = 'https://';
}
} else {
$protocol = 'https://';
}
// Should serve with respective protocol
if ($cloudfront && trim($cloudfront) != '') {
if ($bucket_path) {
$url = $protocol . $cloudfront . '/' . $bucket_path . '/' . $file;
} else {
$url = $protocol . $cloudfront . '/' . $file;
}
} else {
if ($bucket_path) {
$url = $protocol . $bucket . '.s3.amazonaws.com/' . $bucket_path . '/' . $file;
} else {
$url = $protocol . $bucket . '.s3.amazonaws.com/' . $file;
}
}
return $url;
}
public static function deleteAttachment($url)
{
$settings = self::getSettings();
// Check our settings to see if we even want to delete from S3.
if (!isset($settings['s3_delete']) || (int) $settings['s3_delete'] == 0) {
return true;
}
$file = self::getS3PathFromAttachmentPath($url, $settings);
if (isset($settings['valid']) && (int) $settings['valid']) {
$s3 = S3MS_Transfer::getTransferClass($settings);
return $s3->delete($file);
}
}
public static function imageMakeIntermediateSize($attachment_path)
{
$settings = self::getSettings();
$s3_path = self::getS3PathFromAttachmentPath($attachment_path, $settings);
if (isset($settings['valid']) && (int) $settings['valid']) {
$s3 = S3MS_Transfer::getTransferClass($settings);
$s3->upload($attachment_path, $s3_path, false, null);
}
return $s3_path;
}
public static function updateAttachmentMetadata($data, $attachment_id)
{
$attachment_path = get_attached_file($attachment_id); // Gets path to attachment
$settings = self::getSettings();
$s3_path = self::getS3PathFromAttachmentPath($attachment_path, $settings);
if (isset($settings['valid']) && (int) $settings['valid']) {
$s3 = S3MS_Transfer::getTransferClass($settings);
$s3->upload($attachment_path, $s3_path, $attachment_id, $data);
}
return $data;
}
public static function getS3PathFromAttachmentPath($attachment_path, $settings)
{
$upload_dir = wp_upload_dir();
$s3_path = str_replace($upload_dir['basedir'], '', $attachment_path);
if (substr($s3_path, 0, 1) == DIRECTORY_SEPARATOR) {
$s3_path = substr($s3_path, 1);
}
if (isset($settings['s3_bucket_path']) && $settings['s3_bucket_path']) {
$s3_path = $settings['s3_bucket_path'] . '/' . $s3_path;
}
return $s3_path;
}
public static function paginationUrl()
{
parse_str($_SERVER['QUERY_STRING'], $out);
unset($out['s3ms_page']);
$out = http_build_query($out);
if ($out) {
return '?' . $out . '&s3ms_page=';
}
return '?s3ms_page=';
}
public static function pagination($total, $per_page, $page, $page_action, $group = 10, $offset = 0, $classes = array())
{
if ($total <= $per_page) {
return;
}
$classes = implode(' ', $classes);
$str = '';
$start = floor($page / $group) * $group;
$total_pages = ceil($total / $per_page);
if ($start == 0) {
$start = 1;
}
// do some adjustment if someone is nearing the
// end of the group, shift the stack back
$end_of_group = ($start + $group) - 1;
if ($end_of_group > $total_pages) {
$end_of_group = $total_pages;
}
if ($page == $end_of_group && $page != $total_pages) {
$start = $end_of_group;
$end_of_group = ($start + $group) - 1;
} elseif ($page > ($end_of_group - 2) && $end_of_group < $total_pages) {
$start += 1;
$end_of_group = ($start + $group) - 1;
}
if ($page == 1) {
$prev = 1 - $offset;
} elseif ($page == 0) {
$prev = 0;
} else {
$prev = $page - 1;
}
if ($page + 1 > ($total_pages - $offset)) {
$next = ($total_pages - $offset);
} else {
$next = $page + 1;
}
if ($next == 0) {
$next = 1;
}
$end = $total_pages - $offset;
if ($end == 0) {
$end = 1;
}
$str .= '<a href="' . $page_action . (1 - $offset) . '">Start</a> ';
$str .= '<a href="' . $page_action . $prev . '">Prev</a> ';
for ($i = $start; $i <= $end_of_group; $i++) {
if ($i > $total_pages) {
break;
}
if (($i - $offset) == $page) {
$str .= ' <a href="#">' . $i . '</a> ';
} else {
$str .= ' <a href="' . $page_action . ($i - $offset). '">' . $i . '</a> ';
}
}
$str .= ' <a href="' . $page_action . $next . '">Next</a> ';
$str .= ' <a href="' . $page_action . $end . '">End</a> ';
return $str;
}
}
/**
*
* S3MS Tranfer Dispatcher
*
* @category S3MS
* @package S3 Media Storage
*
* @author Anthony Gentile <[email protected]>
*
*/
class S3MS_Transfer {
public static $transfer_class = null;
public static function getTransferClass($settings)
{
$transfer_class = isset($settings['s3_transfer_method']) ? $settings['s3_transfer_method'] : 's3class';
if ($transfer_class == 's3class') {
self::$transfer_class = new S3MS_Transfer_Adapter_S3Class($settings);
} elseif ($transfer_class == 's3cmd') {
self::$transfer_class = new S3MS_Transfer_Adapter_S3Cmd($settings);
} elseif ($transfer_class == 'awscli') {
self::$transfer_class = new S3MS_Transfer_Adapter_AwsCli($settings);
} elseif ($transfer_class == 'background') {
self::$transfer_class = new S3MS_Transfer_Adapter_Background($settings);
} else {
throw new S3MS_Transfer_Exception('Invalid Transfer Class.');
return;
}
return self::$transfer_class;
}
}
/**
*
* S3MS Tranfer Exception
*
* @category S3MS
* @package S3 Media Storage
*
* @author Anthony Gentile <[email protected]>
*
*/
class S3MS_Transfer_Exception extends Exception {
public function __construct($message = null)
{
parent::__construct($message);
}
}
/**
*
* Abstract base class for specific Transfer Adapters
*
* @category S3MS
* @package S3 Media Storage
*
* @author Anthony Gentile <[email protected]>
*
*/
abstract class S3MS_Transfer_Adapter {
abstract public function delete($file);
abstract public function upload($attachment_path, $s3_path, $attachment_id = false, $data = null);
}
/**
*
* S3 Class Transfer Adapter
*
* @category S3MS_Transfer_Adapter
* @package S3 Media Storage
*
* @author Anthony Gentile <[email protected]>
*
*/
class S3MS_Transfer_Adapter_S3Class {
public $s3 = null;
public $settings = array();
public function __construct($settings)
{
if (!class_exists('S3')) {
require_once dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'S3.php';
}
$this->settings = $settings;
$this->s3 = new S3($settings['s3_access_key'], $settings['s3_secret_key']);
$this->s3->setSSL((bool) $this->settings['s3_ssl']);
$this->s3->setExceptions(true);
}
public function delete($file)
{
try {
$this->s3->deleteObject($this->settings['s3_bucket'], $file);
return true;
} catch (Exception $e) {}
}
public function upload($attachment_path, $s3_path, $attachment_id = false, $data = null)
{
$meta_headers = array();
// Allow for far reaching expires
$request_headers = array();
if (trim($this->settings['s3_expires']) != '') {
$request_headers = array(
"Cache-Control" => "max-age=315360000",
"Expires" => gmdate("D, d M Y H:i:s T", strtotime(trim($this->settings['s3_expires'])))
);
}
try {
$this->s3->putObjectFile($attachment_path, $this->settings['s3_bucket'], $s3_path, S3::ACL_PUBLIC_READ, $meta_headers, $request_headers);
if ($attachment_id) {
// We store per file instead of always just referencing the settings, as if settings change we don't want to break previously
// uploaded files that refer to different buckets/cloudfront/etc.
update_post_meta($attachment_id, "S3MS_bucket", $this->settings['s3_bucket']);
update_post_meta($attachment_id, "S3MS_bucket_path", $this->settings['s3_bucket_path']);
update_post_meta($attachment_id, "S3MS_file", $s3_path);
update_post_meta($attachment_id, "S3MS_cloudfront", $this->settings['s3_cloudfront']);
if ((isset($data['S3MS_move']) && $data['S3MS_move']) || (isset($this->settings['s3_delete_local']) && $this->settings['s3_delete_local'])) {
@unlink($attachment_path);
}
// If we are copy or moving we need to grab any thumbnails as well.
if (isset($data['S3MS_move'])) {
$c = wp_get_attachment_metadata($attachment_id);
if (isset($c['sizes']) && is_array($c['sizes'])) {
foreach ($c['sizes'] as $size) {
// Do a cheap check for - and x to know that we are talking about a resized image
// e.g. Photo0537.jpg turns into Photo0537-150x150.jpg
if (isset($size['file']) && strpos($size['file'], '-') && strpos($size['file'], 'x')) {
$parts = pathinfo($attachment_path);
$new_attachment_path = $parts['dirname'] . DIRECTORY_SEPARATOR . $size['file'];
S3MS::imageMakeIntermediateSize($new_attachment_path);
}
}
}
}
} else {
if (isset($this->settings['s3_delete_local']) && $this->settings['s3_delete_local']) {
@unlink($attachment_path);
}
}
} catch (Exception $e) {}
}
}
/**
*
* s3cmd Transfer Adapter
*
* @category S3MS_Transfer_Adapter
* @package S3 Media Storage
*
* @author Anthony Gentile <[email protected]>
*
*/
class S3MS_Transfer_Adapter_S3Cmd {
}
/**
*
* s3cmd AWS CLI Adapter
*
* @category S3MS_Transfer_Adapter
* @package S3 Media Storage
*
* @author Anthony Gentile <[email protected]>
*
*/
class S3MS_Transfer_Adapter_AwsCli {
}
/**
*
* s3cmd Background Adapter
*
* @category S3MS_Transfer_Adapter
* @package S3 Media Storage
*
* @author Anthony Gentile <[email protected]>
*
*/
class S3MS_Transfer_Adapter_Background {
}
/**
*
* Response Object
*
*/
class S3MS_Transfer_Adapter_Background_Response {
}
/**
* Register hooks/filters
*/
// Handle original image uploads and edits for that image
add_filter('wp_update_attachment_metadata', array('S3MS', 'updateAttachmentMetadata'), 9, 2);
// Handle thumbs that are created for that image
add_filter('image_make_intermediate_size', array('S3MS', 'imageMakeIntermediateSize'));
// Handle when image urls are requested.
add_action("wp_get_attachment_url", array('S3MS', 'attachmentUrl'), 9, 2);
add_action("wp_get_attachment_thumb_url", array('S3MS', 'attachmentUrl'), 9, 2);
// Handle when images are deleted.
add_action("wp_delete_file", array('S3MS', 'deleteAttachment'));
// We can't hook into add_attachment/edit_attachment actions as these occur too early in the chain as at that point in time,
// metadata for the attachment has not been associated. So we want to wait, so we can handle both and then delete the local uploaded file.
// add_action("add_attachment", 's3_update_attachment');
// add_action("edit_attachment", 's3_update_attachment');