public
Description: Libraries for Solar PHP Framework
Homepage: http://code.google.com/p/lux/
Clone URL: git://github.com/anttih/lux.git
anttih (author)
Sun Jun 29 10:03:29 -0700 2008
commit  a9479ad9ee17188215000c8ed58109da9c01b303
tree    f709c9b2db69431b61c46e15f34e31de454e897b
parent  a310ee3b8a28478bf7e24b06eb20fd756e196a4a
lux / Lux / Service / Amazon / S3.php
100644 327 lines (282 sloc) 8.751 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
<?php
/**
*
* Provides an interface to Amazon's Simple Storage System (S3).
*
* @package Lux
*
* @subpackage Lux_Service
*
* @author Antti Holvikari <anttih@gmail.com>
*
* @license http://opensource.org/licenses/bsd-license.php BSD
*
*/
class Lux_Service_Amazon_S3 extends Solar_Base
{
    /**
*
* Provides the default values for internal configuration
*
* Keys are:
* `access_key`
* : (string) The Amazon provided S3 Access Key
*
* `secret_key`
* : (string) The Amazon provided S3 Secret Key
*
* @var array
*
*/
    protected $_Lux_Service_Amazon_S3 = array(
        'access_key' => null,
        'secret_key' => null,
        'endpoint' => 's3.amazonaws.com',
    );
    
    /**
*
* undocumented class variable
*
* @var string
*
*/
    protected $_endpoint;
    
    /**
*
* Constructor
*
* @return void
*
*/
    public function __construct($config = null)
    {
        parent::__construct($config);
        $this->_endpoint = $this->_config['endpoint'];
    }
    
    /**
*
* Gets a bucket object
*
* @param string $name Name of the bucket
*
* @return Lux_Service_Amazon_S3_Resource_Bucket
*
*/
    public function getBucket($name)
    {
        $bucket = Solar::factory(
            'Lux_Service_Amazon_S3_Resource_Bucket',
            array('s3' => $this)
        );
        $bucket->name = $name;
        return $bucket;
    }
    
    /**
*
* Fetches all buckets
*
* @return array
*
*/
    public function fetchBuckets()
    {
        $service = Solar::factory(
            'Lux_Service_Amazon_S3_Resource_Service',
            array('s3' => $this)
        );
        
        return $service->fetchBuckets();
    }
    
    /**
*
* Makes an HTTP request to Amazon
*
* @param string $method HTTP method
*
* @param object $resource Resource object
*
* @param int|array $expect Expect the HTTP status
* code to be one of these, if not, will throw an
* exception.
*
* @param array $params A list of query params
*
* @return Solar_Http_Response
*
*/
    public function fetch($method, Lux_Service_Amazon_S3_Resource $resource,
        $expect = 200, $params = array())
    {
        // new HTTP request
        $request = Solar::factory('Solar_Http_Request');
        
        // create Solar_Uri object based on resource and params
        $uri = $this->_buildUri($resource, $params);
        
        // build URI from the uri object
        $request->setUri($uri)
                ->setMethod($method)
                ->setContent($resource->getBody());
        
        // make sure these headers are sent
        $headers = array(
            'Host' => $uri->host,
            'Date' => gmdate('r'),
            'Content-Length' => strlen($resource->getBody()),
        );
        
        // merge headers from resource with these
        $headers = array_merge(
            $resource->getHeaders($method),
            $headers
        );
        
        // add all headers
        foreach ($headers as $name => $val) {
            $request->setHeader($name, $val);
        }
        
        // generate auth cert
        $this->_sign($request, $uri, $resource);
        
        // make the request
        $response = $request->fetch();
        
        // HTTP status code from response
        $code = $response->getStatusCode();
        
        // if code is not one of expected, throw an exception
        if (! in_array($code, (array) $expect)) {
            throw $this->_error($response);
        }
        
        // all seems ok!
        return $response;
    }
    
    /**
*
* Signs a request by adding Authorization header
*
* @param object $request Request object
*
* @param object $uri URI object
*
* @param object $resource Resource object
*
* @return void
*
*/
    private function _sign(Solar_Http_Request_Adapter $request, Solar_Uri $uri,
        Lux_Service_Amazon_S3_Resource $resource)
    {
        // get all request options
        $opts = $request->getOptions();
        
        $method = $opts['method'];
        $headers = $opts['headers'];
        
        ksort($headers);
        $amz_headers = array();
        foreach ($headers as $header => $value) {
            $header = strtolower($header);
            if (substr($header, 0, 6) == 'x-amz-') {
                $amz_headers[] = "$header:$value";
            }
        }
        
        $canon_resource = '/';
        if ($resource instanceof Lux_Service_Amazon_S3_Resource_Bucket
        || $resource instanceof Lux_Service_Amazon_S3_Resource_Object) {
            $canon_resource .= $resource->getBucketName() . '/';
        }
        
        if (! empty($uri->path)) {
            $canon_resource .= implode('/', $uri->path);
            
            // add format?
            $canon_resource .= empty($uri->format) ? '' : ".{$uri->format}";
        }
        
        $content_md5 = '';
        if (isset($headers['Content-MD5'])) {
            $content_md5 = $headers['Content-MD5'];
        }
        
        $content_type = '';
        if (isset($headers['Content-Type'])) {
            $content_type = $headers['Content-Type'];
        }
        
        // build "stringToSign"
        $string_to_sign = $method . "\n"
                        . $content_md5 . "\n"
                        . $content_type . "\n"
                        . $headers['Date'] . "\n"
                        . implode("\n", $amz_headers)
                        . (!empty($amz_headers) ? "\n" : '')
                        . $canon_resource;
        
        $hash = hash_hmac(
            'sha1',
            $string_to_sign,
            $this->_config['secret_key']
        );
        
        $signature = base64_encode(pack('H*', $hash));
        
        // set auth header
        $request->setHeader(
            'Authorization',
            "AWS {$this->_config['access_key']}:$signature"
        );
    }
    
    /**
*
* Builds a URI object based
*
* @param object $resource Amazon resource object
*
* @param array $params Query parameters as an assoc array
*
* @return Solar_Uri
*
*/
    protected function _buildUri(Lux_Service_Amazon_S3_Resource $resource,
        $params = array())
    {
        $uri = Solar::factory('Solar_Uri');
        
        // only http for now
        $uri->scheme = 'http';
        
        $uri->host = $this->_endpoint;
        
        if (! $resource instanceof Lux_Service_Amazon_S3_Resource_Service) {
            $bucket = $resource->getBucketName();
            $uri->host = "$bucket.{$this->_endpoint}";
        }
        
        // requests on objects set the object key in the path
        if ($resource instanceof Lux_Service_Amazon_S3_Resource_Object) {
            $uri->setPath($resource->key);
        }
        
        // i.e /?location
        foreach ($params as $key => $val) {
            $uri->query[$key] = $val;
        }
        
        return $uri;
    }
    
    /**
*
* Parses a response for error info and returns
* a correct exception class
*
* @return Lux_Service_Amazon_S3_Exception
*
*/
    protected function _error(Solar_Http_Response $response)
    {
        $status = $response->getStatusCode() . ' ' . $response->getStatusText();
        
        // add headers to info
        $info = array(
            'status' => $status,
            'headers' => $response->getHeaders(),
            'extra' => array(),
        );
        
        $content = $response->getContent();
        
        // default error code
        $code = 'ERR_UNEXPECTED_STATUS';
        
        $status_code = $response->getStatusCode();
        
        // if this was an actual error with error content
        // we'll parse the content
        if ($status_code >= 400 && ! empty($content)) {
            // parse error message
            $xml = new SimpleXMLElement($content);
            
            foreach ($xml->children() as $node) {
                $name = strtolower($node->getName());
                $info['extra'][$name] = (string) $node;
            }
            
            $code = $info['extra']['code'];
            unset($info['extra']['code']);
        }
        
        // look up an exception class for this error code
        return $this->_exception(
            $code,
            $info
        );
    }
}