zend-framework1 /Service/Amazon/S3.php

Language PHP Lines 971
MD5 Hash eb57cddbd5b0446730d5d1aaa52af849 Estimated Cost $14,725 (why?)
Repository https://bitbucket.org/goldie/zend-framework1.git View Raw File View Project SPDX
  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
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon_S3
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: S3.php 24083 2011-05-30 10:52:55Z ezimuel $
 */

/**
 * @see Zend_Service_Amazon_Abstract
 */
require_once 'Zend/Service/Amazon/Abstract.php';

/**
 * @see Zend_Crypt_Hmac
 */
require_once 'Zend/Crypt/Hmac.php';

/**
 * Amazon S3 PHP connection class
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon_S3
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @see        http://docs.amazonwebservices.com/AmazonS3/2006-03-01/
 */
class Zend_Service_Amazon_S3 extends Zend_Service_Amazon_Abstract
{
    /**
     * Store for stream wrapper clients
     *
     * @var array
     */
    protected static $_wrapperClients = array();

    /**
     * Endpoint for the service
     *
     * @var Zend_Uri_Http
     */
    protected $_endpoint;

    const S3_ENDPOINT = 's3.amazonaws.com';

    const S3_ACL_PRIVATE = 'private';
    const S3_ACL_PUBLIC_READ = 'public-read';
    const S3_ACL_PUBLIC_WRITE = 'public-read-write';
    const S3_ACL_AUTH_READ = 'authenticated-read';

    const S3_REQUESTPAY_HEADER = 'x-amz-request-payer';
    const S3_ACL_HEADER = 'x-amz-acl';
    const S3_CONTENT_TYPE_HEADER = 'Content-Type';

    /**
     * Set S3 endpoint to use
     *
     * @param string|Zend_Uri_Http $endpoint
     * @return Zend_Service_Amazon_S3
     */
    public function setEndpoint($endpoint)
    {
        if (!($endpoint instanceof Zend_Uri_Http)) {
            $endpoint = Zend_Uri::factory($endpoint);
        }
        if (!$endpoint->valid()) {
            /**
             * @see Zend_Service_Amazon_S3_Exception
             */
            require_once 'Zend/Service/Amazon/S3/Exception.php';
            throw new Zend_Service_Amazon_S3_Exception('Invalid endpoint supplied');
        }
        $this->_endpoint = $endpoint;
        return $this;
    }

    /**
     * Get current S3 endpoint
     *
     * @return Zend_Uri_Http
     */
    public function getEndpoint()
    {
        return $this->_endpoint;
    }

    /**
     * Constructor
     *
     * @param string $accessKey
     * @param string $secretKey
     * @param string $region
     */
    public function __construct($accessKey=null, $secretKey=null, $region=null)
    {
        parent::__construct($accessKey, $secretKey, $region);

        $this->setEndpoint('http://'.self::S3_ENDPOINT);
    }

    /**
     * Verify if the bucket name is valid
     *
     * @param string $bucket
     * @return boolean
     */
    public function _validBucketName($bucket)
    {
        $len = strlen($bucket);
        if ($len < 3 || $len > 255) {
            /**
             * @see Zend_Service_Amazon_S3_Exception
             */
            require_once 'Zend/Service/Amazon/S3/Exception.php';
            throw new Zend_Service_Amazon_S3_Exception("Bucket name \"$bucket\" must be between 3 and 255 characters long");
        }

        if (preg_match('/[^a-z0-9\._-]/', $bucket)) {
            /**
             * @see Zend_Service_Amazon_S3_Exception
             */
            require_once 'Zend/Service/Amazon/S3/Exception.php';
            throw new Zend_Service_Amazon_S3_Exception("Bucket name \"$bucket\" contains invalid characters");
        }

        if (preg_match('/(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/', $bucket)) {
            /**
             * @see Zend_Service_Amazon_S3_Exception
             */
            require_once 'Zend/Service/Amazon/S3/Exception.php';
            throw new Zend_Service_Amazon_S3_Exception("Bucket name \"$bucket\" cannot be an IP address");
        }
        return true;
    }

    /**
     * Add a new bucket
     *
     * @param  string $bucket
     * @return boolean
     */
    public function createBucket($bucket, $location = null)
    {
        $this->_validBucketName($bucket);
        $headers=array();
        if($location) {
            $data = '<CreateBucketConfiguration><LocationConstraint>'.$location.'</LocationConstraint></CreateBucketConfiguration>';
            $headers['Content-type']= 'text/plain';
            $headers['Contne-size']= strlen($data);
        } else {
            $data = null;
        }
        $response = $this->_makeRequest('PUT', $bucket, null, $headers, $data);

        return ($response->getStatus() == 200);
    }

    /**
     * Checks if a given bucket name is available
     *
     * @param  string $bucket
     * @return boolean
     */
    public function isBucketAvailable($bucket)
    {
        $response = $this->_makeRequest('HEAD', $bucket, array('max-keys'=>0));

        return ($response->getStatus() != 404);
    }

    /**
     * Checks if a given object exists
     *
     * @param  string $object
     * @return boolean
     */
    public function isObjectAvailable($object)
    {
        $object = $this->_fixupObjectName($object);
        $response = $this->_makeRequest('HEAD', $object);

        return ($response->getStatus() == 200);
    }

    /**
     * Remove a given bucket. All objects in the bucket must be removed prior
     * to removing the bucket.
     *
     * @param  string $bucket
     * @return boolean
     */
    public function removeBucket($bucket)
    {
        $response = $this->_makeRequest('DELETE', $bucket);

        // Look for a 204 No Content response
        return ($response->getStatus() == 204);
    }

    /**
     * Get metadata information for a given object
     *
     * @param  string $object
     * @return array|false
     */
    public function getInfo($object)
    {
        $info = array();

        $object = $this->_fixupObjectName($object);
        $response = $this->_makeRequest('HEAD', $object);

        if ($response->getStatus() == 200) {
            $info['type'] = $response->getHeader('Content-type');
            $info['size'] = $response->getHeader('Content-length');
            $info['mtime'] = strtotime($response->getHeader('Last-modified'));
            $info['etag'] = $response->getHeader('ETag');
        }
        else {
            return false;
        }

        return $info;
    }

    /**
     * List the S3 buckets
     *
     * @return array|false
     */
    public function getBuckets()
    {
        $response = $this->_makeRequest('GET');

        if ($response->getStatus() != 200) {
            return false;
        }

        $xml = new SimpleXMLElement($response->getBody());

        $buckets = array();
        foreach ($xml->Buckets->Bucket as $bucket) {
            $buckets[] = (string)$bucket->Name;
        }

        return $buckets;
    }

    /**
     * Remove all objects in the bucket.
     *
     * @param string $bucket
     * @return boolean
     */
    public function cleanBucket($bucket)
    {
        $objects = $this->getObjectsByBucket($bucket);
        if (!$objects) {
            return false;
        }

        while (!empty($objects)) {
            foreach ($objects as $object) {
                $this->removeObject("$bucket/$object");
            }
            $params= array (
                'marker' => $objects[count($objects)-1]
            );
            $objects = $this->getObjectsByBucket($bucket,$params);
        }
        
        return true;
    }

    /**
     * List the objects in a bucket.
     *
     * Provides the list of object keys that are contained in the bucket.  Valid params include the following.
     * prefix - Limits the response to keys which begin with the indicated prefix. You can use prefixes to separate a bucket into different sets of keys in a way similar to how a file system uses folders.
     * marker - Indicates where in the bucket to begin listing. The list will only include keys that occur lexicographically after marker. This is convenient for pagination: To get the next page of results use the last key of the current page as the marker.
     * max-keys - The maximum number of keys you'd like to see in the response body. The server might return fewer than this many keys, but will not return more.
     * delimiter - Causes keys that contain the same string between the prefix and the first occurrence of the delimiter to be rolled up into a single result element in the CommonPrefixes collection. These rolled-up keys are not returned elsewhere in the response.
     *
     * @param  string $bucket
     * @param array $params S3 GET Bucket Paramater
     * @return array|false
     */
    public function getObjectsByBucket($bucket, $params = array())
    {
        $response = $this->_makeRequest('GET', $bucket, $params);

        if ($response->getStatus() != 200) {
            return false;
        }

        $xml = new SimpleXMLElement($response->getBody());

        $objects = array();
        if (isset($xml->Contents)) {
            foreach ($xml->Contents as $contents) {
                foreach ($contents->Key as $object) {
                    $objects[] = (string)$object;
                }
            }
        }

        return $objects;
    }

    /**
     * Make sure the object name is valid
     *
     * @param  string $object
     * @return string
     */
    protected function _fixupObjectName($object)
    {
        $nameparts = explode('/', $object);

        $this->_validBucketName($nameparts[0]);

        $firstpart = array_shift($nameparts);
        if (count($nameparts) == 0) {
            return $firstpart;
        }

        return $firstpart.'/'.join('/', array_map('rawurlencode', $nameparts));
    }

    /**
     * Get an object
     *
     * @param  string $object
     * @param  bool   $paidobject This is "requestor pays" object
     * @return string|false
     */
    public function getObject($object, $paidobject=false)
    {
        $object = $this->_fixupObjectName($object);
        if ($paidobject) {
            $response = $this->_makeRequest('GET', $object, null, array(self::S3_REQUESTPAY_HEADER => 'requester'));
        }
        else {
            $response = $this->_makeRequest('GET', $object);
        }

        if ($response->getStatus() != 200) {
            return false;
        }

        return $response->getBody();
    }

    /**
     * Get an object using streaming
     *
     * Can use either provided filename for storage or create a temp file if none provided.
     *
     * @param  string $object Object path
     * @param  string $streamfile File to write the stream to
     * @param  bool   $paidobject This is "requestor pays" object
     * @return Zend_Http_Response_Stream|false
     */
    public function getObjectStream($object, $streamfile = null, $paidobject=false)
    {
        $object = $this->_fixupObjectName($object);
        self::getHttpClient()->setStream($streamfile?$streamfile:true);
        if ($paidobject) {
            $response = $this->_makeRequest('GET', $object, null, array(self::S3_REQUESTPAY_HEADER => 'requester'));
        }
        else {
            $response = $this->_makeRequest('GET', $object);
        }
        self::getHttpClient()->setStream(null);

        if ($response->getStatus() != 200 || !($response instanceof Zend_Http_Response_Stream)) {
            return false;
        }

        return $response;
    }

    /**
     * Upload an object by a PHP string
     *
     * @param  string $object Object name
     * @param  string|resource $data   Object data (can be string or stream)
     * @param  array  $meta   Metadata
     * @return boolean
     */
    public function putObject($object, $data, $meta=null)
    {
        $object = $this->_fixupObjectName($object);
        $headers = (is_array($meta)) ? $meta : array();

        if(!is_resource($data)) {
            $headers['Content-MD5'] = base64_encode(md5($data, true));
        }
        $headers['Expect'] = '100-continue';

        if (!isset($headers[self::S3_CONTENT_TYPE_HEADER])) {
            $headers[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($object);
        }

        $response = $this->_makeRequest('PUT', $object, null, $headers, $data);

        // Check the MD5 Etag returned by S3 against and MD5 of the buffer
        if ($response->getStatus() == 200) {
            // It is escaped by double quotes for some reason
            $etag = str_replace('"', '', $response->getHeader('Etag'));

            if (is_resource($data) || $etag == md5($data)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Put file to S3 as object
     *
     * @param string $path   File name
     * @param string $object Object name
     * @param array  $meta   Metadata
     * @return boolean
     */
    public function putFile($path, $object, $meta=null)
    {
        $data = @file_get_contents($path);
        if ($data === false) {
            /**
             * @see Zend_Service_Amazon_S3_Exception
             */
            require_once 'Zend/Service/Amazon/S3/Exception.php';
            throw new Zend_Service_Amazon_S3_Exception("Cannot read file $path");
        }

        if (!is_array($meta)) {
            $meta = array();
        }

        if (!isset($meta[self::S3_CONTENT_TYPE_HEADER])) {
           $meta[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($path);
        }

        return $this->putObject($object, $data, $meta);
    }

    /**
     * Put file to S3 as object, using streaming
     *
     * @param string $path   File name
     * @param string $object Object name
     * @param array  $meta   Metadata
     * @return boolean
     */
    public function putFileStream($path, $object, $meta=null)
    {
        $data = @fopen($path, "rb");
        if ($data === false) {
            /**
             * @see Zend_Service_Amazon_S3_Exception
             */
            require_once 'Zend/Service/Amazon/S3/Exception.php';
            throw new Zend_Service_Amazon_S3_Exception("Cannot open file $path");
        }

        if (!is_array($meta)) {
            $meta = array();
        }

        if (!isset($meta[self::S3_CONTENT_TYPE_HEADER])) {
           $meta[self::S3_CONTENT_TYPE_HEADER] = self::getMimeType($path);
        }

        if(!isset($meta['Content-MD5'])) {
            $headers['Content-MD5'] = base64_encode(md5_file($path, true));
        }

        return $this->putObject($object, $data, $meta);
    }

    /**
     * Remove a given object
     *
     * @param  string $object
     * @return boolean
     */
    public function removeObject($object)
    {
        $object = $this->_fixupObjectName($object);
        $response = $this->_makeRequest('DELETE', $object);

        // Look for a 204 No Content response
        return ($response->getStatus() == 204);
    }

    /**
     * Copy an object
     *
     * @param  string $sourceObject  Source object name
     * @param  string $destObject    Destination object name
     * @param  array  $meta          (OPTIONAL) Metadata to apply to desination object.
     *                               Set to null to copy metadata from source object.
     * @return boolean
     */
    public function copyObject($sourceObject, $destObject, $meta = null)
    {
        $sourceObject = $this->_fixupObjectName($sourceObject);
        $destObject   = $this->_fixupObjectName($destObject);

        $headers = (is_array($meta)) ? $meta : array();
        $headers['x-amz-copy-source'] = $sourceObject;
        $headers['x-amz-metadata-directive'] = $meta === null ? 'COPY' : 'REPLACE';

        $response = $this->_makeRequest('PUT', $destObject, null, $headers);

        if ($response->getStatus() == 200 && !stristr($response->getBody(), '<Error>')) {
            return true;
        }

        return false;
    }

    /**
     * Move an object
     *
     * Performs a copy to dest + verify + remove source
     *
     * @param string $sourceObject  Source object name
     * @param string $destObject    Destination object name
     * @param array  $meta          (OPTIONAL) Metadata to apply to destination object.
     *                              Set to null to retain existing metadata.
     */
    public function moveObject($sourceObject, $destObject, $meta = null)
    {
        $sourceInfo = $this->getInfo($sourceObject);

        $this->copyObject($sourceObject, $destObject, $meta);
        $destInfo = $this->getInfo($destObject);

        if ($sourceInfo['etag'] === $destInfo['etag']) {
            return $this->removeObject($sourceObject);
        } else {
            return false;
        }
    }

    /**
     * Make a request to Amazon S3
     *
     * @param  string $method    Request method
     * @param  string $path        Path to requested object
     * @param  array  $params    Request parameters
     * @param  array  $headers    HTTP headers
     * @param  string|resource $data        Request data
     * @return Zend_Http_Response
     */
    public function _makeRequest($method, $path='', $params=null, $headers=array(), $data=null)
    {
        $retry_count = 0;

        if (!is_array($headers)) {
            $headers = array($headers);
        }

        $headers['Date'] = gmdate(DATE_RFC1123, time());

        if(is_resource($data) && $method != 'PUT') {
            /**
             * @see Zend_Service_Amazon_S3_Exception
             */
            require_once 'Zend/Service/Amazon/S3/Exception.php';
            throw new Zend_Service_Amazon_S3_Exception("Only PUT request supports stream data");
        }

        // build the end point out
        $parts = explode('/', $path, 2);
        $endpoint = clone($this->_endpoint);
        if ($parts[0]) {
            // prepend bucket name to the hostname
            $endpoint->setHost($parts[0].'.'.$endpoint->getHost());
        }
        if (!empty($parts[1])) {
            // ZF-10218, ZF-10122
            $pathparts = explode('?',$parts[1]);
            $endpath = $pathparts[0];
            $endpoint->setPath('/'.$endpath);
            
        }
        else {
            $endpoint->setPath('/');
            if ($parts[0]) {
                $path = $parts[0].'/';
            }
        }
        self::addSignature($method, $path, $headers);

        $client = self::getHttpClient();

        $client->resetParameters(true);
        $client->setUri($endpoint);
        $client->setAuth(false);
        // Work around buglet in HTTP client - it doesn't clean headers
        // Remove when ZHC is fixed
        /*
        $client->setHeaders(array('Content-MD5'              => null,
                                  'Content-Encoding'         => null,
                                  'Expect'                   => null,
                                  'Range'                    => null,
                                  'x-amz-acl'                => null,
                                  'x-amz-copy-source'        => null,
                                  'x-amz-metadata-directive' => null));
        */
        $client->setHeaders($headers);

        if (is_array($params)) {
            foreach ($params as $name=>$value) {
                $client->setParameterGet($name, $value);
            }
         }

         if (($method == 'PUT') && ($data !== null)) {
             if (!isset($headers['Content-type'])) {
                 $headers['Content-type'] = self::getMimeType($path);
             }
             $client->setRawData($data, $headers['Content-type']);
         } 
         do {
            $retry = false;

            $response = $client->request($method);
            $response_code = $response->getStatus();

            // Some 5xx errors are expected, so retry automatically
            if ($response_code >= 500 && $response_code < 600 && $retry_count <= 5) {
                $retry = true;
                $retry_count++;
                sleep($retry_count / 4 * $retry_count);
            }
            else if ($response_code == 307) {
                // Need to redirect, new S3 endpoint given
                // This should never happen as Zend_Http_Client will redirect automatically
            }
            else if ($response_code == 100) {
                // echo 'OK to Continue';
            }
        } while ($retry);

        return $response;
    }

    /**
     * Add the S3 Authorization signature to the request headers
     *
     * @param  string $method
     * @param  string $path
     * @param  array &$headers
     * @return string
     */
    protected function addSignature($method, $path, &$headers)
    {
        if (!is_array($headers)) {
            $headers = array($headers);
        }

        $type = $md5 = $date = '';

        // Search for the Content-type, Content-MD5 and Date headers
        foreach ($headers as $key=>$val) {
            if (strcasecmp($key, 'content-type') == 0) {
                $type = $val;
            }
            else if (strcasecmp($key, 'content-md5') == 0) {
                $md5 = $val;
            }
            else if (strcasecmp($key, 'date') == 0) {
                $date = $val;
            }
        }

        // If we have an x-amz-date header, use that instead of the normal Date
        if (isset($headers['x-amz-date']) && isset($date)) {
            $date = '';
        }

        $sig_str = "$method\n$md5\n$type\n$date\n";
        // For x-amz- headers, combine like keys, lowercase them, sort them
        // alphabetically and remove excess spaces around values
        $amz_headers = array();
        foreach ($headers as $key=>$val) {
            $key = strtolower($key);
            if (substr($key, 0, 6) == 'x-amz-') {
                if (is_array($val)) {
                    $amz_headers[$key] = $val;
                }
                else {
                    $amz_headers[$key][] = preg_replace('/\s+/', ' ', $val);
                }
            }
        }
        if (!empty($amz_headers)) {
            ksort($amz_headers);
            foreach ($amz_headers as $key=>$val) {
                $sig_str .= $key.':'.implode(',', $val)."\n";
            }
        }

        $sig_str .= '/'.parse_url($path, PHP_URL_PATH);
        if (strpos($path, '?location') !== false) {
            $sig_str .= '?location';
        }
        else if (strpos($path, '?acl') !== false) {
            $sig_str .= '?acl';
        }
        else if (strpos($path, '?torrent') !== false) {
            $sig_str .= '?torrent';
        }
        else if (strpos($path, '?versions') !== false) {
            $sig_str .= '?versions';
        }

        $signature = base64_encode(Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'sha1', utf8_encode($sig_str), Zend_Crypt_Hmac::BINARY));
        $headers['Authorization'] = 'AWS '.$this->_getAccessKey().':'.$signature;

        return $sig_str;
    }

    /**
     * Attempt to get the content-type of a file based on the extension
     *
     * @param  string $path
     * @return string
     */
    public static function getMimeType($path)
    {
        $ext = substr(strrchr($path, '.'), 1);

        if(!$ext) {
            // shortcut
            return 'binary/octet-stream';
        }

        switch (strtolower($ext)) {
            case 'xls':
                $content_type = 'application/excel';
                break;
            case 'hqx':
                $content_type = 'application/macbinhex40';
                break;
            case 'doc':
            case 'dot':
            case 'wrd':
                $content_type = 'application/msword';
                break;
            case 'pdf':
                $content_type = 'application/pdf';
                break;
            case 'pgp':
                $content_type = 'application/pgp';
                break;
            case 'ps':
            case 'eps':
            case 'ai':
                $content_type = 'application/postscript';
                break;
            case 'ppt':
                $content_type = 'application/powerpoint';
                break;
            case 'rtf':
                $content_type = 'application/rtf';
                break;
            case 'tgz':
            case 'gtar':
                $content_type = 'application/x-gtar';
                break;
            case 'gz':
                $content_type = 'application/x-gzip';
                break;
            case 'php':
            case 'php3':
            case 'php4':
                $content_type = 'application/x-httpd-php';
                break;
            case 'js':
                $content_type = 'application/x-javascript';
                break;
            case 'ppd':
            case 'psd':
                $content_type = 'application/x-photoshop';
                break;
            case 'swf':
            case 'swc':
            case 'rf':
                $content_type = 'application/x-shockwave-flash';
                break;
            case 'tar':
                $content_type = 'application/x-tar';
                break;
            case 'zip':
                $content_type = 'application/zip';
                break;
            case 'mid':
            case 'midi':
            case 'kar':
                $content_type = 'audio/midi';
                break;
            case 'mp2':
            case 'mp3':
            case 'mpga':
                $content_type = 'audio/mpeg';
                break;
            case 'ra':
                $content_type = 'audio/x-realaudio';
                break;
            case 'wav':
                $content_type = 'audio/wav';
                break;
            case 'bmp':
                $content_type = 'image/bitmap';
                break;
            case 'gif':
                $content_type = 'image/gif';
                break;
            case 'iff':
                $content_type = 'image/iff';
                break;
            case 'jb2':
                $content_type = 'image/jb2';
                break;
            case 'jpg':
            case 'jpe':
            case 'jpeg':
                $content_type = 'image/jpeg';
                break;
            case 'jpx':
                $content_type = 'image/jpx';
                break;
            case 'png':
                $content_type = 'image/png';
                break;
            case 'tif':
            case 'tiff':
                $content_type = 'image/tiff';
                break;
            case 'wbmp':
                $content_type = 'image/vnd.wap.wbmp';
                break;
            case 'xbm':
                $content_type = 'image/xbm';
                break;
            case 'css':
                $content_type = 'text/css';
                break;
            case 'txt':
                $content_type = 'text/plain';
                break;
            case 'htm':
            case 'html':
                $content_type = 'text/html';
                break;
            case 'xml':
                $content_type = 'text/xml';
                break;
            case 'xsl':
                $content_type = 'text/xsl';
                break;
            case 'mpg':
            case 'mpe':
            case 'mpeg':
                $content_type = 'video/mpeg';
                break;
            case 'qt':
            case 'mov':
                $content_type = 'video/quicktime';
                break;
            case 'avi':
                $content_type = 'video/x-ms-video';
                break;
            case 'eml':
                $content_type = 'message/rfc822';
                break;
            default:
                $content_type = 'binary/octet-stream';
                break;
        }

        return $content_type;
    }

    /**
     * Register this object as stream wrapper client
     *
     * @param  string $name
     * @return Zend_Service_Amazon_S3
     */
    public function registerAsClient($name)
    {
        self::$_wrapperClients[$name] = $this;
        return $this;
    }

    /**
     * Unregister this object as stream wrapper client
     *
     * @param  string $name
     * @return Zend_Service_Amazon_S3
     */
    public function unregisterAsClient($name)
    {
        unset(self::$_wrapperClients[$name]);
        return $this;
    }

    /**
     * Get wrapper client for stream type
     *
     * @param  string $name
     * @return Zend_Service_Amazon_S3
     */
    public static function getWrapperClient($name)
    {
        return self::$_wrapperClients[$name];
    }

    /**
     * Register this object as stream wrapper
     *
     * @param  string $name
     * @return Zend_Service_Amazon_S3
     */
    public function registerStreamWrapper($name='s3')
    {
        /**
         * @see Zend_Service_Amazon_S3_Stream
         */
        require_once 'Zend/Service/Amazon/S3/Stream.php';

        stream_register_wrapper($name, 'Zend_Service_Amazon_S3_Stream');
        $this->registerAsClient($name);
    }

    /**
     * Unregister this object as stream wrapper
     *
     * @param  string $name
     * @return Zend_Service_Amazon_S3
     */
    public function unregisterStreamWrapper($name='s3')
    {
        stream_wrapper_unregister($name);
        $this->unregisterAsClient($name);
    }
}
Back to Top