1. Justin Poliey
  2. gimmee

Commits

Justin Poliey  committed e421aa4

Added API functionality

  • Participants
  • Branches default

Comments (0)

Files changed (5)

File api/config.php

View file
+<?php
+define('AWS_ACCESS_KEY', 'AKIAJJBWJGAFFYH4G6PQ');
+define('AWS_SECRET_KEY', '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');

File api/delete.php

View file
+<?php
+require 'config.php';
+require 'simpler_db.php';
+
+/* Validate GET parameters */
+foreach (array('userId', 'keyword') as $param) {
+	if (empty($_GET[$param])) {
+		header('Status: 400 Bad Request');
+		echo json_encode(array(
+			'status' => 'error',
+			'error' => array(
+				'type' => 'MissingParameter',
+				'message' => 'Missing '.$param.' parameter'
+			)
+		));
+		die();
+	}
+}
+
+/* Sanitize GET parameters */
+$userId = urldecode(trim($_GET['userId']));
+$keyword = urldecode(trim($_GET['keyword']));
+
+/* Remove keyword from the database */
+$sdb = new SimplerDB(AWS_ACCESS_KEY, AWS_SECRET_KEY);
+$results = $sdb->deleteAttributes(array(
+	'DomainName' => 'keywords',
+	'ItemName'   => "{$userId}:{$keyword}"
+));
+
+/* Return successful JSON */
+header('Status: 200 OK');
+echo json_encode(array(
+	'status' => 'ok',
+	'user_id' => $userId,
+	'keyword' => $keyword
+));

File api/list.php

View file
+<?php
+require 'config.php';
+require 'simpler_db.php';
+
+/* Validate GET params */
+if (empty($_GET['userId'])) {
+	header('Status: 400 Bad Request');
+	echo json_encode(array(
+		'status' => 'error',
+		'error' => array(
+			'type' => 'MissingParameter',
+			'message' => 'Missing userId parameter'
+		)
+	));
+	die();
+}
+
+/* Send SimpleDB request */
+$userId = urldecode(trim($_GET['userId']));
+$sdb = new SimplerDB(AWS_ACCESS_KEY, AWS_SECRET_KEY);
+$results = $sdb->select(array(
+	'SelectExpression' => sprintf("select * from keywords where user_id='%s'", $userId)
+	//'SelectExpression' => 'select * from keywords'
+));
+
+/* Aggregate all the data, fuck SimpleXML. actually, fuck XML */
+$keywords = array();
+$result_xml = simplexml_load_string($results);
+$result_size = count($result_xml->SelectResult->Item);
+for ($i = 0; $i < $result_size; $i++) {
+	$item = $result_xml->SelectResult->Item[$i];
+	$attr_size = count($item->Attribute);
+	for ($j = 0; $j < $attr_size; $j++) {
+		if ($item->Attribute[$j]->Name == 'keyword') {
+			$keywords[] = sprintf('%s', $item->Attribute[$j]->Value);
+			//$keywords[] = $item->Attributes[$j]->Value;
+			break;
+		}
+	}
+}
+
+/* Successful request, reformat as JSON and return */
+header('200 OK');
+echo json_encode(array(
+	'status' => 'ok',
+	'user_id' => trim($_GET['userId']),
+	'keywords' => $keywords
+));

File api/put.php

View file
+<?php
+require 'config.php';
+require 'simpler_db.php';
+
+/* Validate GET parameters */
+foreach (array('userId', 'keyword') as $param) {
+	if (empty($_GET[$param])) {
+		header('Status: 400 Bad Request');
+		echo json_encode(array(
+			'status' => 'error',
+			'error' => array(
+				'type' => 'MissingParameter',
+				'message' => 'Missing '.$param.' parameter'
+			)
+		));
+		die();
+	}
+}
+
+/* Sanitize GET parameters */
+$userId = urldecode(trim($_GET['userId']));
+$keyword = urldecode(trim($_GET['keyword']));
+
+/* Add keyword record to the DB. The actual item name is a UUID, userId/keyword
+   are stored as attributes */
+$sdb = new SimplerDB(AWS_ACCESS_KEY, AWS_SECRET_KEY);
+$results = $sdb->batchPutAttributes(array(
+	"{$userId}:{$keyword}" => array(
+		'user_id' => $userId,
+		'keyword' => $keyword
+	)
+), array('DomainName' => 'keywords'));
+
+/* Return successful JSON */
+header('Status: 200 OK');
+echo json_encode(array(
+	'status' => 'ok',
+	'user_id' => $userId,
+	'keyword' => $keyword
+));

File api/simpler_db.php

View 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;
+	}
+
+}