/api/simpler_db.php
PHP | 91 lines | 71 code | 9 blank | 11 comment | 0 complexity | cb058e376c863c6368f3984e13a2763b MD5 | raw file
- <?php
- class SimplerDB {
- private $access_key;
- private $secret_key;
- function __construct($access_key, $secret_key, $domain = null) {
- $this->access_key = $access_key;
- $this->secret_key = $secret_key;
- $this->params = array(
- 'AWSAccessKeyId' => $this->access_key,
- 'Version' => '2009-04-15',
- 'ZoneName.0' => 'us-east-1a',
- 'ZoneName.1' => 'us-east-1b',
- 'ZoneName.2' => 'us-east-1c',
- 'SignatureVersion' => 2,
- 'SignatureMethod' => 'HmacSHA256'
- );
- }
-
- function __call($name, $args) {
- return $this->request(ucfirst($name), count($args) > 0 ? $args[0] : array());
- }
-
- function uuid($prefix = '') {
- $chars = uniqid(md5(mt_rand()), true);
- $uuid = substr($chars, 0, 8) . '-';
- $uuid .= substr($chars, 8, 4) . '-';
- $uuid .= substr($chars, 12, 4) . '-';
- $uuid .= substr($chars, 16, 4) . '-';
- $uuid .= substr($chars, 20, 12);
- return $prefix . $uuid;
- }
-
- function batchPutAttributes($items, $params = array()) {
- $params = array_merge($this->itemsToParams($items), $params);
- return $this->request('BatchPutAttributes', $params);
- }
-
- /*
- function deleteAttributes($items, $params = array()) {
- $params = array_merge($this->itemsToParams($items), $params);
- return $this->request('DeleteAttributes', $params);
- }
- */
-
- private function itemsToParams($items) {
- $params = array();
- $item_no = 0;
- foreach ($items as $item => $attributes) {
- $attr_no = 0;
- $params["Item.{$item_no}.ItemName"] = $item;
- foreach ($attributes as $name => $value) {
- $params["Item.{$item_no}.Attribute.{$attr_no}.Name"] = $name;
- $params["Item.{$item_no}.Attribute.{$attr_no}.Value"] = $value;
- $attr_no++;
- }
- $item_no++;
- }
- return $params;
- }
-
- private function request($action, $qs_params = array()) {
- // Make sure extra query string params are factored in
- foreach ($qs_params as $key => $value) {
- $this->params[$key] = $value;
- }
- // Add a timestamp
- $this->params['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z');
- $this->params['Action'] = $action;
- // Generate a version 2 signature
- uksort($this->params, 'strnatcmp');
- $qstr = '';
- foreach ($this->params as $key => $value) {
- $qstr .= '&'.$key.'='.rawurlencode($value);
- }
- $qstr = substr($qstr, 1);
- $signature_v2 = "GET\nsdb.amazonaws.com\n/\n{$qstr}";
- $this->params['Signature'] = base64_encode(hash_hmac('sha256', $signature_v2, $this->secret_key, true));
- // Send cURL call
- $ch = curl_init();
- $request_url = 'https://sdb.amazonaws.com/?'.http_build_query($this->params);
- //echo $request_url . "<br />";
- curl_setopt($ch, CURLOPT_URL, $request_url);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- $response = curl_exec($ch);
- return $response;
- }
- }