· 6 years ago · Oct 01, 2019, 06:04 AM
1<?php
2
3namespace App;
4
5/**
6* Redistribution and use in source and binary forms, with or without
7* modification, are permitted provided that the following conditions are met:
8*
9* - Redistributions of source code must retain the above copyright notice,
10* this list of conditions and the following disclaimer.
11* - Redistributions in binary form must reproduce the above copyright
12* notice, this list of conditions and the following disclaimer in the
13* documentation and/or other materials provided with the distribution.
14*
15* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25* POSSIBILITY OF SUCH DAMAGE.
26*/
27/**
28* Kilat Storage S3 PHP class
29*
30* Version: 0.1.3
31*
32* This code is a fork of the following:
33* @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
34* @version 0.2.3
35*
36**/
37class S3 {
38 // ACL flags
39 const ACL_PRIVATE = 'private';
40 const ACL_PUBLIC_READ = 'public-read';
41 const ACL_PUBLIC_READ_WRITE = 'public-read-write';
42 const STORAGE_CLASS_STANDARD = 'STANDARD';
43 const STORAGE_CLASS_RRS = 'REDUCED_REDUNDANCY';
44 private static $__accessKey; // Kilat Storage Access key
45 private static $__secretKey; // Kilat Storage Secret key
46 public static $__region;
47 /**
48 * Constructor, used if you're not calling the class statically
49 *
50 * @param string $accessKey Access key
51 * @param string $secretKey Secret key
52 * @return void
53 */
54 public function __construct($accessKey = null, $secretKey = null) {
55 if ($accessKey !== null && $secretKey !== null) {
56 self::setAuth($accessKey, $secretKey);
57 } else {
58 self::setAuth(env("AWS_ACCESS_KEY_ID"), env("AWS_SECRET_ACCESS_KEY"));
59 }
60 self::$__region = "s3-".env("AWS_DEFAULT_REGION", "id-jkt-1");
61 }
62 /**
63 * Set access information
64 *
65 * @param string $accessKey Access key
66 * @param string $secretKey Secret key
67 * @return void
68 */
69 public static function setAuth($accessKey, $secretKey) {
70 self::$__accessKey = $accessKey;
71 self::$__secretKey = $secretKey;
72 }
73 /**
74 * Get a list of buckets
75 *
76 * @return array | false
77 */
78 public static function listBuckets() {
79 $rest = new S3Request('GET', '', '');
80 $rest = $rest->getResponse();
81 if ($rest->error === false && $rest->code !== 200)
82 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
83 if ($rest->error !== false) {
84 trigger_error(sprintf("S3::listBuckets(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
85 return false;
86 }
87 $results = array();
88 $contents = simplexml_load_string($rest->body);
89 if (isset($contents->Buckets)) {
90 foreach($contents->Buckets->Bucket as $bucket) {
91 $results[] = array(
92 'name' => (string)$bucket->Name,
93 'time' => strtotime((string)$bucket->CreationDate),
94 );
95 }
96 }
97 return $results;
98 }
99 /**
100 * Get contents for a bucket
101 *
102 * @param string $bucket Bucket name
103 * @return array | false
104 */
105 public static function getBucket($bucket) {
106 $rest = new S3Request('GET', $bucket, '');
107 $response = $rest->getResponse();
108 if ($response->error === false && $response->code !== 200)
109 $response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
110 if ($response->error !== false) {
111 trigger_error(sprintf("S3::getBucket(): [%s] %s", $response->error['code'], $response->error['message']), E_USER_WARNING);
112 return false;
113 }
114 $results = array();
115 $contents = simplexml_load_string($response->body);
116 if (isset($contents->Contents)) {
117 foreach ($contents->Contents as $c) {
118 $results[] = array(
119 'name' => (string)$c->Key,
120 'time' => strToTime((string)$c->LastModified),
121 'size' => (int)$c->Size,
122 'hash' => substr((string)$c->ETag, 1, -1)
123 );
124 }
125 }
126
127 return $results;
128 }
129 /**
130 * Put a bucket
131 *
132 * @param string $bucket Bucket name
133 * @param constant $acl ACL flag
134 * @return boolean
135 */
136 public function putBucket($bucket, $acl = self::ACL_PRIVATE) {
137 $rest = new S3Request('PUT', $bucket, '');
138 $rest->setAmzHeader('x-amz-acl', $acl);
139 $rest = $rest->getResponse();
140 if ($rest->error === false && $rest->code !== 200)
141 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
142 if ($rest->error !== false) {
143 trigger_error(sprintf("S3::putBucket({$bucket}): [%s] %s",
144 $rest->error['code'], $rest->error['message']), E_USER_WARNING);
145 return false;
146 }
147 return true;
148 }
149 /**
150 * Delete an empty bucket
151 *
152 * @param string $bucket Bucket name
153 * @return boolean
154 */
155 public function deleteBucket($bucket = '') {
156 $rest = new S3Request('DELETE', $bucket);
157 $rest = $rest->getResponse();
158 if ($rest->error === false && $rest->code !== 204)
159 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
160 if ($rest->error !== false) {
161 trigger_error(sprintf("S3::deleteBucket({$bucket}): [%s] %s",
162 $rest->error['code'], $rest->error['message']), E_USER_WARNING);
163 return false;
164 }
165 return true;
166 }
167 /**
168 * Create input info array for putObject()
169 *
170 * @param string $file Input file
171 * @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own)
172 * @return array | false
173 */
174 public static function inputFile($file, $md5sum = true) {
175 if (!file_exists($file) || !is_file($file) || !is_readable($file)) {
176 trigger_error('S3::inputFile(): Unable to open input file: '.$file, E_USER_WARNING);
177 return false;
178 }
179 return array('file' => $file, 'size' => filesize($file),
180 'md5sum' => $md5sum !== false ? (is_string($md5sum) ? $md5sum :
181 base64_encode(md5_file($file, true))) : '');
182 }
183 /**
184 * Use a resource for input
185 *
186 * @param string $file Input file
187 * @param integer $bufferSize Input byte size
188 * @param string $md5sum MD5 hash to send (optional)
189 * @return array | false
190 */
191 public static function inputResource(&$resource, $bufferSize, $md5sum = '') {
192 if (!is_resource($resource) || $bufferSize <= 0) {
193 trigger_error('S3::inputResource(): Invalid resource or buffer size', E_USER_WARNING);
194 return false;
195 }
196 $input = array('size' => $bufferSize, 'md5sum' => $md5sum);
197 $input['fp'] =& $resource;
198 return $input;
199 }
200 /**
201 * Put an object
202 *
203 * @param mixed $input Input data
204 * @param string $bucket Bucket name
205 * @param string $uri Object URI
206 * @param constant $acl ACL constant
207 * @param array $metaHeaders Array of x-amz-meta-* headers
208 * @param string $contentType Content type
209 * @return boolean
210 */
211 public static function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) {
212 // temporarily disable this line of code.
213 //if ($input == false) return "yahoo";
214 $rest = new S3Request('PUT', $bucket, $uri);
215 if (is_string($input)) $input = array(
216 'data' => $input, 'size' => strlen($input),
217 'md5sum' => base64_encode(md5($input, true))
218 );
219 // Data
220 if (isset($input['fp']))
221 $rest->fp =& $input['fp'];
222 elseif (isset($input['file']))
223 $rest->fp = @fopen($input['file'], 'rb');
224 elseif (isset($input['data']))
225 $rest->data = $input['data'];
226 // Content-Length (required)
227 if (isset($input['size']) && $input['size'] > 0)
228 $rest->size = $input['size'];
229 else {
230 if (isset($input['file']))
231 $rest->size = filesize($input['file']);
232 elseif (isset($input['data']))
233 $rest->size = strlen($input['data']);
234 }
235 // Content-Type
236 if ($contentType !== null)
237 $input['type'] = $contentType;
238 elseif (!isset($input['type']) && isset($input['file']))
239 $input['type'] = self::__getMimeType($input['file']);
240 else
241 $input['type'] = 'application/octet-stream';
242 // We need to post with the content-length and content-type, MD5 is optional
243 if ($rest->size > 0 && ($rest->fp !== false || $rest->data !== false)) {
244 $rest->setHeader('Content-Type', $input['type']);
245 if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
246 $rest->setAmzHeader('x-amz-acl', $acl);
247 foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
248 $rest->getResponse();
249 } else
250 $rest->response->error = array('code' => 0, 'message' => 'Missing input parameters');
251 if ($rest->response->error === false && $rest->response->code !== 200)
252 $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
253 if ($rest->response->error !== false) {
254 trigger_error(sprintf("S3::putObject(): [%s] %s", $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
255 return false;
256 }
257 return true;
258 }
259 /**
260 * Puts an object from a file (legacy function)
261 *
262 * @param string $file Input file path
263 * @param string $bucket Bucket name
264 * @param string $uri Object URI
265 * @param constant $acl ACL constant
266 * @param array $metaHeaders Array of x-amz-meta-* headers
267 * @param string $contentType Content type
268 * @return boolean
269 */
270 public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null) {
271 return self::putObject(S3::inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType);
272 }
273 /**
274 * Put an object from a string (legacy function)
275 *
276 * @param string $string Input data
277 * @param string $bucket Bucket name
278 * @param string $uri Object URI
279 * @param constant $acl ACL constant
280 * @param array $metaHeaders Array of x-amz-meta-* headers
281 * @param string $contentType Content type
282 * @return boolean
283 */
284 public function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain') {
285 return self::putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
286 }
287 /**
288 * Get an object
289 *
290 * @param string $bucket Bucket name
291 * @param string $uri Object URI
292 * @param mixed &$saveTo Filename or resource to write to
293 * @return mixed
294 */
295 public static function getObject($bucket = '', $uri = '', $saveTo = false) {
296 $rest = new S3Request('GET', $bucket, $uri);
297 if ($saveTo !== false) {
298 if (is_resource($saveTo))
299 $rest->fp =& $saveTo;
300 else
301 if (($rest->fp = @fopen($saveTo, 'wb')) == false)
302 $rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
303 }
304 if ($rest->response->error === false) $rest->getResponse();
305 if ($rest->response->error === false && $rest->response->code !== 200)
306 $rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
307 if ($rest->response->error !== false) {
308 trigger_error(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
309 $rest->response->error['code'], $rest->response->error['message']), E_USER_WARNING);
310 return false;
311 }
312 $rest->file = realpath($saveTo);
313 return $rest->response;
314 }
315 /**
316 * Get object information
317 *
318 * @param string $bucket Bucket name
319 * @param string $uri Object URI
320 * @param boolean $returnInfo Return response information
321 * @return mixed | false
322 */
323 public static function getObjectInfo($bucket = '', $uri = '', $returnInfo = true) {
324 $rest = new S3Request('HEAD', $bucket, $uri);
325 $rest = $rest->getResponse();
326 if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
327 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
328 if ($rest->error !== false) {
329 trigger_error(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s",
330 $rest->error['code'], $rest->error['message']), E_USER_WARNING);
331 return false;
332 }
333 return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
334 }
335 /**
336 * Copy an object
337 *
338 * @param string $srcBucket Source bucket name
339 * @param string $srcUri Source object URI
340 * @param string $bucket Destination bucket name
341 * @param string $uri Destination object URI
342 * @param constant $acl ACL constant
343 * @param array $metaHeaders Optional array of x-amz-meta-* headers
344 * @param array $requestHeaders Optional array of request headers (content type, disposition, etc.)
345 * @param constant $storageClass Storage class constant
346 * @return mixed | false
347 */
348 public static function copyObject($srcBucket, $srcUri, $bucket, $uri, $acl = self::ACL_PUBLIC_READ, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD)
349 {
350 $rest = new S3Request('PUT', $bucket, $uri);
351 $rest->setHeader('Content-Length', 0);
352 foreach ($requestHeaders as $h => $v) $rest->setHeader($h, $v);
353 foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
354 if ($storageClass !== self::STORAGE_CLASS_STANDARD)
355 $rest->setAmzHeader('x-amz-storage-class', $storageClass);
356 $rest->setAmzHeader('x-amz-acl', $acl);
357 $rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, rawurlencode($srcUri)));
358 if (sizeof($requestHeaders) > 0 || sizeof($metaHeaders) > 0)
359 $rest->setAmzHeader('x-amz-metadata-directive', 'REPLACE');
360 $rest = $rest->getResponse();
361 if ($rest->error === false && $rest->code !== 200)
362 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
363 if ($rest->error !== false)
364 {
365 self::__triggerError(sprintf("S3::copyObject({$srcBucket}, {$srcUri}, {$bucket}, {$uri}): [%s] %s",
366 $rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
367 return false;
368 }
369 $results = array();
370 $contents = simplexml_load_string($rest->body);
371 if (isset($contents->LastModified, $contents->ETag)) {
372 $results = array(
373 'time' => strToTime((string)$contents->LastModified),
374 'hash' => substr((string)$contents->ETag, 1, -1)
375 );
376 }
377 return $results;
378 }
379 /**
380 * Set logging for a bucket
381 *
382 * @param string $bucket Bucket name
383 * @param string $targetBucket Target bucket (where logs are stored)
384 * @param string $targetPrefix Log prefix (e,g; domain.com-)
385 * @return boolean
386 */
387 public static function setBucketLogging($bucket, $targetBucket, $targetPrefix) {
388 $dom = new DOMDocument;
389 $bucketLoggingStatus = $dom->createElement('BucketLoggingStatus');
390 $bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
391 $loggingEnabled = $dom->createElement('LoggingEnabled');
392 $loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket));
393 $loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix));
394 // TODO: Add TargetGrants
395 $bucketLoggingStatus->appendChild($loggingEnabled);
396 $dom->appendChild($bucketLoggingStatus);
397 $rest = new S3Request('PUT', $bucket, '');
398 $rest->setParameter('logging', null);
399 $rest->data = $dom->saveXML();
400 $rest->size = strlen($rest->data);
401 $rest->setHeader('Content-Type', 'application/xml');
402 $rest = $rest->getResponse();
403 if ($rest->error === false && $rest->code !== 200)
404 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
405 if ($rest->error !== false) {
406 trigger_error(sprintf("S3::setBucketLogging({$bucket}, {$uri}): [%s] %s",
407 $rest->error['code'], $rest->error['message']), E_USER_WARNING);
408 return false;
409 }
410 return true;
411 }
412 /**
413 * Get logging status for a bucket
414 *
415 * This will return false if logging is not enabled.
416 * Note: To enable logging, you also need to grant write access to the log group
417 *
418 * @param string $bucket Bucket name
419 * @return array | false
420 */
421 public static function getBucketLogging($bucket = '') {
422 $rest = new S3Request('GET', $bucket, '');
423 $rest->setParameter('logging', null);
424 $rest = $rest->getResponse();
425 if ($rest->error === false && $rest->code !== 200)
426 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
427 if ($rest->error !== false) {
428 trigger_error(sprintf("S3::getBucketLogging({$bucket}): [%s] %s",
429 $rest->error['code'], $rest->error['message']), E_USER_WARNING);
430 return false;
431 }
432 if (!isset($rest->body->LoggingEnabled)) return false; // No logging
433 return array(
434 'targetBucket' => (string)$rest->body->LoggingEnabled->TargetBucket,
435 'targetPrefix' => (string)$rest->body->LoggingEnabled->TargetPrefix,
436 );
437 }
438 /**
439 * Set object or bucket Access Control Policy
440 *
441 * @param string $bucket Bucket name
442 * @param string $uri Object URI
443 * @param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy)
444 * @return boolean
445 */
446 public static function setAccessControlPolicy($bucket, $uri = '', $acp = array()) {
447 $dom = new DOMDocument;
448 $dom->formatOutput = true;
449 $accessControlPolicy = $dom->createElement('AccessControlPolicy');
450 $accessControlList = $dom->createElement('AccessControlList');
451 // It seems the owner has to be passed along too
452 $owner = $dom->createElement('Owner');
453 $owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
454 $owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
455 $accessControlPolicy->appendChild($owner);
456 foreach ($acp['acl'] as $g) {
457 $grant = $dom->createElement('Grant');
458 $grantee = $dom->createElement('Grantee');
459 $grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
460 if (isset($g['id'])) { // CanonicalUser (DisplayName is omitted)
461 $grantee->setAttribute('xsi:type', 'CanonicalUser');
462 $grantee->appendChild($dom->createElement('ID', $g['id']));
463 } elseif (isset($g['email'])) { // AmazonCustomerByEmail
464 $grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
465 $grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
466 } elseif ($g['type'] == 'Group') { // Group
467 $grantee->setAttribute('xsi:type', 'Group');
468 $grantee->appendChild($dom->createElement('URI', $g['uri']));
469 }
470 $grant->appendChild($grantee);
471 $grant->appendChild($dom->createElement('Permission', $g['permission']));
472 $accessControlList->appendChild($grant);
473 }
474 $accessControlPolicy->appendChild($accessControlList);
475 $dom->appendChild($accessControlPolicy);
476 $rest = new S3Request('PUT', $bucket, '');
477 $rest->setParameter('acl', null);
478 $rest->data = $dom->saveXML();
479 $rest->size = strlen($rest->data);
480 $rest->setHeader('Content-Type', 'application/xml');
481 $rest = $rest->getResponse();
482 if ($rest->error === false && $rest->code !== 200)
483 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
484 if ($rest->error !== false) {
485 trigger_error(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
486 $rest->error['code'], $rest->error['message']), E_USER_WARNING);
487 return false;
488 }
489 return true;
490 }
491 /**
492 * Get object or bucket Access Control Policy
493 *
494 * Currently this will trigger an error if there is no ACL on an object (will fix soon)
495 *
496 * @param string $bucket Bucket name
497 * @param string $uri Object URI
498 * @return mixed | false
499 */
500 public static function getAccessControlPolicy($bucket, $uri = '') {
501 $rest = new S3Request('GET', $bucket, $uri);
502 $rest->setParameter('acl', null);
503 $rest = $rest->getResponse();
504 if ($rest->error === false && $rest->code !== 200)
505 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
506 if ($rest->error !== false) {
507 trigger_error(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
508 $rest->error['code'], $rest->error['message']), E_USER_WARNING);
509 return false;
510 }
511 $acp = array();
512 $contents = simplexml_load_string($rest->body);
513 if (isset($contents->Owner, $contents->Owner->ID, $contents->Owner->DisplayName)) {
514 $acp['owner'] = array(
515 'id' => (string)$contents->Owner->ID, 'name' => (string)$contents->Owner->DisplayName
516 );
517 }
518 if (isset($contents->AccessControlList)) {
519 $acp['acl'] = array();
520 foreach ($contents->AccessControlList->Grant as $grant) {
521 foreach ($grant->Grantee as $grantee) {
522 if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser
523 $acp['acl'][] = array(
524 'type' => 'CanonicalUser',
525 'id' => (string)$grantee->ID,
526 'name' => (string)$grantee->DisplayName,
527 'permission' => (string)$grant->Permission
528 );
529 elseif (isset($grantee->EmailAddress)) // AmazonCustomerByEmail
530 $acp['acl'][] = array(
531 'type' => 'AmazonCustomerByEmail',
532 'email' => (string)$grantee->EmailAddress,
533 'permission' => (string)$grant->Permission
534 );
535 elseif (isset($grantee->URI)) // Group
536 $acp['acl'][] = array(
537 'type' => 'Group',
538 'uri' => (string)$grantee->URI,
539 'permission' => (string)$grant->Permission
540 );
541 else continue;
542 }
543 }
544 }
545 return $acp;
546 }
547 /**
548 * Delete an object
549 *
550 * @param string $bucket Bucket name
551 * @param string $uri Object URI
552 * @return mixed
553 */
554 public static function deleteObject($bucket = '', $uri = '') {
555 $rest = new S3Request('DELETE', $bucket, $uri);
556 $rest = $rest->getResponse();
557 if ($rest->error === false && $rest->code !== 204)
558 $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
559 if ($rest->error !== false) {
560 trigger_error(sprintf("S3::deleteObject(): [%s] %s", $rest->error['code'], $rest->error['message']), E_USER_WARNING);
561 return false;
562 }
563 return true;
564 # For debugging only.
565 //return $rest->error['message'];
566 }
567 /**
568 * Get MIME type for file
569 *
570 * @internal Used to get mime types
571 * @param string &$file File path
572 * @return string
573 */
574 public static function __getMimeType(&$file) {
575 $type = false;
576 // Fileinfo documentation says fileinfo_open() will use the
577 // MAGIC env var for the magic file
578 if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
579 ($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
580 if (($type = finfo_file($finfo, $file)) !== false) {
581 // Remove the charset and grab the last content-type
582 $type = explode(' ', str_replace('; charset=', ';charset=', $type));
583 $type = array_pop($type);
584 $type = explode(';', $type);
585 $type = array_shift($type);
586 }
587 finfo_close($finfo);
588 // If anyone is still using mime_content_type()
589 } elseif (function_exists('mime_content_type'))
590 $type = mime_content_type($file);
591 if ($type !== false && strlen($type) > 0) return $type;
592 // Otherwise do it the old fashioned way
593 static $exts = array(
594 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
595 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
596 'swf' => 'application/x-shockwave-flash', 'pdf' => 'application/pdf',
597 'zip' => 'application/zip', 'gz' => 'application/x-gzip',
598 'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
599 'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
600 'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
601 'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
602 'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
603 'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
604 'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
605 );
606 $ext = strToLower(pathInfo($file, PATHINFO_EXTENSION));
607 return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
608 }
609 /**
610 * Generate the auth string: "AWS AccessKey:Signature"
611 *
612 * This uses the hash extension if loaded
613 *
614 * @internal Signs the request
615 * @param string $string String to sign
616 * @return string
617 */
618 public static function __getSignature($string) {
619 return 'AWS '.self::$__accessKey.':'.base64_encode(extension_loaded('hash') ?
620 hash_hmac('sha1', $string, self::$__secretKey, true) : pack('H*', sha1(
621 (str_pad(self::$__secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
622 pack('H*', sha1((str_pad(self::$__secretKey, 64, chr(0x00)) ^
623 (str_repeat(chr(0x36), 64))) . $string)))));
624 }
625}
626final class S3Request {
627 private $verb, $bucket, $uri, $resource = '', $parameters = array(),
628 $amzHeaders = array(), $headers = array(
629 'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => ''
630 );
631 public $fp = false, $size = 0, $data = false, $response;
632 /**
633 * Constructor
634 *
635 * @param string $verb Verb
636 * @param string $bucket Bucket name
637 * @param string $uri Object URI
638 * @return mixed
639 */
640 function __construct($verb, $bucket = '', $uri = '') {
641 $this->verb = $verb;
642 $this->bucket = strtolower($bucket);
643 $this->uri = $uri !== '' ? '/'.$uri : '/';
644 if ($this->bucket !== '') {
645 $this->bucket = explode('/', $this->bucket);
646 $this->resource = '/'.$this->bucket[0].$this->uri;
647 $this->headers['Host'] = $this->bucket[0].'.'.S3::$__region.'.kilatstorage.id';
648 $this->bucket = implode('/', $this->bucket);
649 } else {
650 $this->headers['Host'] = S3::$__region.'.kilatstorage.id';
651 if (strlen($this->uri) > 1)
652 $this->resource = '/'.$this->bucket.$this->uri;
653 else $this->resource = $this->uri;
654 }
655 $this->headers['Date'] = gmdate('D, d M Y H:i:s T');
656 $this->response = new \stdClass;
657 $this->response->error = false;
658 }
659 /**
660 * Set request parameter
661 *
662 * @param string $key Key
663 * @param string $value Value
664 * @return void
665 */
666 public function setParameter($key, $value) {
667 $this->parameters[$key] = $value;
668 }
669 /**
670 * Set request header
671 *
672 * @param string $key Key
673 * @param string $value Value
674 * @return void
675 */
676 public function setHeader($key, $value) {
677 $this->headers[$key] = $value;
678 }
679 /**
680 * Set x-amz-meta-* header
681 *
682 * @param string $key Key
683 * @param string $value Value
684 * @return void
685 */
686 public function setAmzHeader($key, $value) {
687 $this->amzHeaders[$key] = $value;
688 }
689 /**
690 * Get the S3 response
691 *
692 * @return object | false
693 */
694 public function getResponse() {
695 $query = '';
696 if (sizeof($this->parameters) > 0) {
697 $query = substr($this->uri, -1) !== '?' ? '?' : '&';
698 foreach ($this->parameters as $var => $value)
699 if ($value == null || $value == '') $query .= $var.'&';
700 else $query .= $var.'='.$value.'&';
701 $query = substr($query, 0, -1);
702 $this->uri .= $query;
703 if (isset($this->parameters['acl']) || !isset($this->parameters['logging']))
704 $this->resource .= $query;
705 }
706 $url = (extension_loaded('openssl')?'https://':'http://').$this->headers['Host'].$this->uri;
707 //var_dump($this->bucket, $this->uri, $this->resource, $url);
708 // Basic setup
709 $curl = curl_init();
710 curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
711 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
712 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
713 curl_setopt($curl, CURLOPT_URL, $url);
714 // Headers
715 $headers = array(); $amz = array();
716 foreach ($this->amzHeaders as $header => $value)
717 if (strlen($value) > 0) $headers[] = $header.': '.$value;
718 foreach ($this->headers as $header => $value)
719 if (strlen($value) > 0) $headers[] = $header.': '.$value;
720 foreach ($this->amzHeaders as $header => $value)
721 if (strlen($value) > 0) $amz[] = strToLower($header).':'.$value;
722 $amz = (sizeof($amz) > 0) ? "\n".implode("\n", $amz) : '';
723 // Authorization string
724 $headers[] = 'Authorization: ' . S3::__getSignature(
725 $this->verb."\n".
726 $this->headers['Content-MD5']."\n".
727 $this->headers['Content-Type']."\n".
728 $this->headers['Date'].$amz."\n".$this->resource
729 );
730 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
731 curl_setopt($curl, CURLOPT_HEADER, false);
732 curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
733 curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
734 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
735 // Request types
736 switch ($this->verb) {
737 case 'GET': break;
738 case 'PUT':
739 if ($this->fp !== false) {
740 curl_setopt($curl, CURLOPT_PUT, true);
741 curl_setopt($curl, CURLOPT_INFILE, $this->fp);
742 if ($this->size > 0)
743 curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
744 } elseif ($this->data !== false) {
745 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
746 curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
747 if ($this->size > 0)
748 curl_setopt($curl, CURLOPT_BUFFERSIZE, $this->size);
749 } else
750 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
751 break;
752 case 'HEAD':
753 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
754 curl_setopt($curl, CURLOPT_NOBODY, true);
755 break;
756 case 'DELETE':
757 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
758 break;
759 default: break;
760 }
761 // Execute, grab errors
762 if (curl_exec($curl))
763 $this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
764 else
765 $this->response->error = array(
766 'code' => curl_errno($curl),
767 'message' => curl_error($curl),
768 'resource' => $this->resource
769 );
770 @curl_close($curl);
771 // Parse body into XML
772 if ($this->response->error === false && isset($this->response->headers['type']) &&
773 $this->response->headers['type'] == 'application/xml' && isset($this->response->body)) {
774 $this->response->body = simplexml_load_string($this->response->body);
775 // Grab S3 errors
776 if (!in_array($this->response->code, array(200, 204)) &&
777 isset($this->response->body->Code, $this->response->body->Message)) {
778 $this->response->error = array(
779 'code' => (string)$this->response->body->Code,
780 'message' => (string)$this->response->body->Message
781 );
782 if (isset($this->response->body->Resource))
783 $this->response->error['resource'] = (string)$this->response->body->Resource;
784 unset($this->response->body);
785 }
786 }
787 // Clean up file resources
788 if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp);
789 return $this->response;
790 }
791 /**
792 * CURL write callback
793 *
794 * @param resource &$curl CURL resource
795 * @param string &$data Data
796 * @return integer
797 */
798 private function __responseWriteCallback(&$curl, &$data) {
799 $this->response->body = '';
800 if ($this->response->code == 200 && $this->fp !== false)
801 return fwrite($this->fp, $data);
802 else
803 $this->response->body .= $data;
804 return strlen($data);
805 }
806 /**
807 * CURL header callback
808 *
809 * @param resource &$curl CURL resource
810 * @param string &$data Data
811 * @return integer
812 */
813 private function __responseHeaderCallback(&$curl, &$data) {
814 if (($strlen = strlen($data)) <= 2) return $strlen;
815 if (substr($data, 0, 4) == 'HTTP')
816 $this->response->code = (int)substr($data, 9, 3);
817 else {
818 list($header, $value) = explode(': ', trim($data));
819 if ($header == 'Last-Modified')
820 $this->response->headers['time'] = strtotime($value);
821 elseif ($header == 'Content-Length')
822 $this->response->headers['size'] = (int)$value;
823 elseif ($header == 'Content-Type')
824 $this->response->headers['type'] = $value;
825 elseif ($header == 'ETag')
826 $this->response->headers['hash'] = substr($value, 1, -1);
827 elseif (preg_match('/^x-amz-meta-.*$/', $header))
828 $this->response->headers[$header] = is_numeric($value) ? (int)$value : $value;
829 }
830 return $strlen;
831 }
832}