Andy’s Scribbles

This week, as I built part of my App Server for Distributed Systems Design, I hit another stumbling block. The library that Amazon provides in PHP for accessing SimpleDB requires PHP 5.2. I should have known that I need to use the latest version.

Not only did Amazon’s library not work for me, but it was huge and complicated. I found another library at: Google Code, but as fate would have it, that library didn’t work either. The code was pretty ugly imho, but at least it was straighforward enough for me to understand how accessing SimpleDB worked, which led me to make my own SimpleDB client.

The script will work with any PHP 5, and doesn’t depend on anything that isn’t built in by default. I hope it is helpful to someone else. It would be really easy to add the SimpleDB requests I haven’t implemented yet.

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
/**
* AWS_SimpleDB_Client v0.1 by Andy VanWagoner, distributed under the ISC licence.
* Provides simple access to Amazon's SimpleDB from PHP 5.
*
* Copyright (c) 2009, Andy VanWagoner
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

class AWS_SimpleDB_Client {

// AWS SimpleDB API Constants
private static $service_endpoint = "sdb.amazonaws.com";
private static $api_version = "2007-11-07";
private static $timestamp_format = "Y-m-d\TH:i:s.\\\\\Z";
private static $signature_version = 1;

private static $user_agent = "AWS_SimpleDB_Client 0.1 - Andy VanWagoner";

/**
* Constructor
*
* @param string $access // your AWS "Access Key ID"
* @param string $secret // your AWS "Seceret Access Key"
*/
function AWS_SimpleDB_Client($access, $secret) {
$this->access_key = $access;
$this->secret_key = $secret;
}

/**
* AWS SimpleDB API - CreateDomain
* NOTE: This call will take a while (AWS says 10 seconds)
*
* @param string $domain // the domain to create
*
* @return array('status'=>array('code'=>, 'message'=>), 'RequestId'=>, 'BoxUsage'=>)
*/
function create_domain($domain) {
$params = array(
'Action' => 'CreateDomain',
'DomainName' => $domain
);

return $this->post($params);
}

/**
* AWS SimpleDB API - DeleteDomain
* NOTE: This call will take a while (AWS says 10 seconds)
*
* @param string $domain // the domain to delete
*
* @return array('status'=>array('code'=>, 'message'=>), 'RequestId'=>, 'BoxUsage'=>)
*/
function delete_domain($domain) {
$params = array(
'Action' => 'DeleteDomain',
'DomainName' => $domain
);

return $this->post($params);
}

/**
* AWS SimpleDB API - ListDomains
*
* @param string $next = '' // Optional - Sent as NextToken parameter
* @param string $max = 100 // Optional - Sent as MaxNumberOfDomains
*
* @return array('status'=>array('code'=>, 'message'=>), 'RequestId'=>, 'BoxUsage'=>,
* 'DomainName'=>array('...', ...) [, 'NextToken'=>])
*/
function list_domains($next = '', $max = 0) {
$params = array('Action' => 'ListDomains');

if ($max > 0 && $max) return $this->post($params);
}

/**
* AWS SimpleDB API - PutAttributes
*
* @param string $domain // The domain the item is in
* @param string $item // The name of the item
* @param array $attributes // array(array('Name'=>, 'Value'=> [, 'Replace'=>]), ...)
*
* @return array('status'=>array('code'=>, 'message'=>), 'RequestId'=>, 'BoxUsage'=>)
*/
function put_attributes($domain, $item, $attributes) {
$params = array(
'Action' => 'PutAttributes',
'DomainName' => $domain,
'ItemName' => $item
);

foreach($attributes as $i => $value) {
$params["Attribute.$i.Name"] = $value['Name'];
$params["Attribute.$i.Value"] = $value['Value'];
if (isset($value['Replace']))
$params["Attribute.$i.Replace"] = $value['Replace'];
}

return $this->post($params);
}

/**
* AWS SimpleDB API - DeleteAttributes
*
* @param string $domain // The domain the item is in
* @param string $item // The name of the item
* @param array $attributes // array(array('Name'=>, 'Value'=>), ...)
*
* @return array('status'=>array('code'=>, 'message'=>), 'RequestId'=>, 'BoxUsage'=>)
*/
function delete_attributes($domain, $item, $attributes) {
$params = array(
'Action' => 'DeleteAttributes',
'DomainName' => $domain,
'ItemName' => $item
);

foreach($attributes as $i => $value) {
$params["Attribute.$i.Name"] = $value['Name'];
$params["Attribute.$i.Value"] = $value['Value'];
}

return $this->post($params);
}

/**
* AWS SimpleDB API - GetAttributes
*
* @param string $domain // the domain name
* @param string $item // the item's name
* @param string $attribute // Optional - If specified, only this attribute's values are retrieved.
*
* @return array('status'=>array('code'=>, 'message'=>), 'RequestId'=>, 'BoxUsage'=>,
* 'Attribute'=>array(array('Name'=>,'Value'=>), ...))
*/
function get_attributes($domain, $item, $attribute = '') {
$params = array(
'Action' => 'GetAttributes',
'DomainName' => $domain,
'ItemName' => $item
);

if ($attribute)
$params['AttributeName'] = $attribute;

return $this->post($params);
}

/**
* AWS SimpleDB API - Query
*
* @param string $domain // The domain name
* @param string $query // The query to run on this domain
* @param string $next = '' // OPTIONAL - token supplied on last paged call
* @param integer $max = 100 // OPTIONAL - max items you want returned 1-250, default = 100
*
* @return array('status'=>array('code'=>, 'message'=>), 'RequestId'=>, 'BoxUsage'=>,
* 'ItemName'=>array('...', ...))
*/
function query($domain, $query, $next = '', $max = 0) {
$params = array(
'Action' => 'Query',
'DomainName' => $domain,
'QueryExpression' => $query
);

if ($max > 250) $max = 250;
if ($max > 0)
$params['MaxNumberOfItems'] = $max;
if ($next)
$params['NextToken'] = $next;

return $this->post($params);
}

/**
* Sign the parameters, following AWS version 1 signing
*
* @param array $params // array of all (except for the signiture) params to be passed to amazon
*
* @return string // signature string
*/
private function sign($params) {
uksort($params, 'strnatcasecmp');

$data = '';
foreach ($params as $key=>$value) {
$data .= $key . $value;
}

return base64_encode ( pack("H*", sha1((str_pad($this->secret_key, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
pack("H*", sha1((str_pad($this->secret_key, 64, chr(0x00)) ^ (str_repeat(chr(0x36), 64))) .
$data)))) );
}

/**
* POST to AWS SimpleDB and then parse the response.
*
* @param array $params // all params to pass on the post
*
* @return array('status'=>array('code'=>, 'message'=>), 'RequestId'=>, 'BoxUsage'=>, ...)
*/
private function post($params) {

// Add all of the common parameters needed by AWS SimpleDB
$params['AWSAccessKeyId'] = $this->access_key;
$params['Timestamp'] = gmdate(self::$timestamp_format, time());
$params['Version'] = self::$api_version;
$params['SignatureVersion'] = self::$signature_version;
$params['Signature'] = $this->sign($params);

// Generate the POST request
$content = http_build_query($params);

$post = 'POST / HTTP/1.0' . "\r\n";
$post .= 'Host: ' . self::$service_endpoint . "\r\n";
$post .= 'Content-Type: ' . 'application/x-www-form-urlencoded; charset=utf-8' . "\r\n";
$post .= 'Content-Length: ' . strlen($content) . "\r\n";
$post .= 'User-Agent: ' . self::$user_agent . "\r\n";
$post .= "\r\n";
$post .= $content;

$socket = @fsockopen(self::$service_endpoint, 80, $errno, $errstr, 10);
if ($socket) {
fwrite($socket, $post);

$response = stream_get_contents($socket);
fclose($socket);

// Parse the response
return $this->format_result($response);
}

// Return a fail result
return array('status' => array('code' => 404, 'message' => 'Not Found'),
'Error' => array('Code' => $errno, 'Message' =>
'Could not connect to ' . $this->$service_endpoint . " ($errstr)"
)
);
}

/**
* Take the XML document returned by AWS SimpleDB, and transform it into a hash
*
* @param string $result // the full http response string from SimpleDB
*/
private function format_result($result) {
list($http_headers, $content) = explode("\r\n\r\n", $result, 2);
$header_lines = explode("\r\n", $http_headers);
list($protocol, $code, $message) = explode(" ", $header_lines[0], 3);

// record the http status
$formatted = array('status' => array('code' => $code, 'message' => $message));

$xml = simplexml_load_string($content);

// Look for Errors
if (isset($xml->Errors)) {
$formatted['RequestId'] = (string)$xml->RequestId;
$formatted['Error'] = array();
foreach($xml->Errors->Error as $error) {
array_push($formatted['Error'], array(
'Code' => (string)$error->Code,
'Message' => (string)$error->Message
));
}
return $formatted;
}

// Get the metadata for this request
$metadata = $xml->ResponseMetadata;
$formatted['RequestId'] = (string)$metadata->RequestId;
$formatted['BoxUsage'] = (string)$metadata->BoxUsage;

// GetAttributes Response
if (isset($xml->GetAttributesResult)) {
$formatted['Attribute'] = array();
foreach($xml->GetAttributesResult->Attribute as $attribute) {
array_push($formatted['Attribute'], array(
'Name' => (string)$attribute->Name,
'Value' => (string)$attribute->Value
));
}
}

// ListDomains Response
if (isset($xml->ListDomainsResult)) {
$formatted['DomainName'] = array();
foreach($xml->ListDomainsResult->DomainName as $domain) {
array_push($formatted['DomainName'], (string)$domain);
}
if (isset($xml->ListDomainsResult->NextToken)) {
$formatted['NextToken'] = (string)$xml->ListDomainsResult->NextToken;
}
}

// Query Response
if (isset($xml->QueryResult)) {
$formatted['ItemName'] = array();
foreach($xml->QueryResult->ItemName as $item) {
array_push($formatted['ItemName'], (string)$item);
}
if (isset($xml->QueryResult->NextToken)) {
$formatted['NextToken'] = (string)$xml->QueryResult->NextToken;
}
}

return $formatted;
}
}

?>