cloudfusion-2.5.0/0000755000000000000000000000000011337017066012552 5ustar rootrootcloudfusion-2.5.0/sdb.class.php0000644000000000000000000005225111337016604015141 0ustar rootroot constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * * Returns: * _boolean_ false if no valid values are set, otherwise true. */ public function __construct($key = null, $secret_key = null) { $this->api_version = '2009-04-15'; $this->hostname = SDB_DEFAULT_URL; if (!$key && !defined('AWS_KEY')) { throw new SDB_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.'); } if (!$secret_key && !defined('AWS_SECRET_KEY')) { throw new SDB_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.'); } return parent::__construct($key, $secret_key); } /*%******************************************************************************************%*/ // DOMAIN /** * Method: create_domain() * Creates a new domain. The domain name must be unique among the domains associated with the Access Key ID provided in the request. The CreateDomain operation might take 10 or more seconds to complete. * * Access: * public * * Parameters: * domain_name - _string_ (Required) The domain name to use for storing data. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/1_create_domain.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_CreateDomain.html * Related - , , , */ public function create_domain($domain_name, $returnCurlHandle = null) { $opt = array(); $opt['DomainName'] = $domain_name; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('CreateDomain', $opt, $this->hostname); } /** * Method: list_domains() * Lists all domains associated with the Access Key ID. It returns domain names up to the limit set by MaxNumberOfDomains. A NextToken is returned if there are more than MaxNumberOfDomains domains. Calling ListDomains successive times with the NextToken returns up to MaxNumberOfDomains more domain names each time. * * Access: * public * * Parameters: * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * MaxNumberOfDomains - _integer_ (Optional) The maximum number of domain names you want returned. The range is 1 to 100. * NextToken - _string_ (Optional) String that tells Amazon SimpleDB where to start the next list of domain names. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/list_domains.phpt: * example::sdb/list_domains2.phpt: * example::sdb/list_domains3.phpt: * example::sdb/list_domains5.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_ListDomains.html * Related - , , , */ public function list_domains($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('ListDomains', $opt, $this->hostname); } /** * Method: delete_domain() * Deletes a domain. Any items (and their attributes) in the domain are deleted as well. The DeleteDomain operation might take 10 or more seconds to complete. Running DeleteDomain on a domain that does not exist or running the function multiple times using the same domain name will not result in an error response. * * Access: * public * * Parameters: * domain_name - _string_ (Required) The domain name to delete. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/delete_attributes.phpt: * example::sdb/delete_attributes2.phpt: * example::sdb/delete_attributes3.phpt: * example::sdb/delete_attributes4.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_DeleteDomain.html * Related - , , , */ public function delete_domain($domain_name, $returnCurlHandle = null) { $opt = array(); $opt['DomainName'] = $domain_name; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DeleteDomain', $opt, $this->hostname); } /** * Method: domain_metadata() * Returns information about the domain, including when the domain was created, the number of items and attributes, and the size of attribute names and values. * * Access: * public * * Parameters: * domain_name - _string_ (Required) The domain name to use for retrieving metadata. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/domain_metadata.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_DomainMetadata.html * Related - , , , */ public function domain_metadata($domain_name, $returnCurlHandle = null) { $opt = array(); $opt['DomainName'] = $domain_name; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DomainMetadata', $opt, $this->hostname); } /*%******************************************************************************************%*/ // ATTRIBUTES /** * Method: put_attributes() * Creates or replaces attributes in an item. You specify new attributes using a combination of the Attribute.X.Name and Attribute.X.Value parameters. * * Access: * public * * Parameters: * domain_name - _string_ (Required) The domain name to use for storing data. * item_name - _string_ (Required) The name of the base item which will contain the series of keypairs. * keypairs - _array_ (Required) Associative array of parameters which are treated as key-value and key-multivalue pairs (i.e. a key can have one or more values; think tags). * replace - _boolean|array_ (Optional) Whether to replace a key-value pair if a matching key already exists. Supports either a boolean (which affects ALL key-value pairs) or an indexed array of key names (which affects only the keys specified). Defaults to boolean false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/put_attributes.phpt: * example::sdb/put_attributes2.phpt: * example::sdb/put_attributes5.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_PutAttributes.html * Related - , */ public function put_attributes($domain_name, $item_name, $keypairs, $replace = null, $returnCurlHandle = null) { $opt = array(); $opt['DomainName'] = $domain_name; $opt['ItemName'] = $item_name; $opt['returnCurlHandle'] = $returnCurlHandle; $rstore = array(); // Start looping through the keypairs. $count = 0; foreach ($keypairs as $k => $v) { // Is one of the values an array? if (is_array($v)) { // Loop through each of them so that all values are passed as individual attributes. foreach ($v as $va) { $opt['Attribute.' . (string) $count . '.Name'] = $k; $opt['Attribute.' . (string) $count . '.Value'] = $va; // Do we want to do replacement? if ($replace) { // Do we have an associative array of key names? if (is_array($replace)) { // Store this key-index pair for later. $rstore[] = array( 'count' => $count, 'key' => $k ); } // Or just a since REPLACE ALL? else { $opt['Attribute.' . (string) $count . '.Replace'] = 'true'; } } // Increment $count++; } } else { $opt['Attribute.' . (string) $count . '.Name'] = $k; $opt['Attribute.' . (string) $count . '.Value'] = $v; // Do we want to do replacement? if ($replace) { // Do we have an associative array of key names? if (is_array($replace)) { // Store this key-index pair for later. $rstore[] = array( 'count' => $count, 'key' => $k ); } // Or just a since REPLACE ALL? else { $opt['Attribute.' . (string) $count . '.Replace'] = 'true'; } } } // Increment $count++; } // Go through all of the saved key-index pairs we saved earlier. foreach ($rstore as $k => $store) { // Did we want to replace one of these keypairs? if (in_array($store['key'], $replace)) { // Replace! $opt['Attribute.' . (string) $store['count'] . '.Replace'] = 'true'; } } return $this->authenticate('PutAttributes', $opt, $this->hostname); } /** * Method: batch_put_attributes() * Creates or replaces attributes in an item. You specify new attributes using a combination of the Attribute.X.Name and Attribute.X.Value parameters. * * Access: * public * * Parameters: * domain_name - _string_ (Required) The domain name to use for storing data. * item_keypairs - _array_ (Required) Associative array of parameters which are treated as item-key-value and item-key-multivalue pairs (i.e. a key can have one or more values; think tags). * replace - _boolean|array_ (Optional) Whether to replace a key-value pair if a matching key already exists. Supports either a boolean (which affects ALL key-value pairs) or an indexed array of key names (which affects only the keys specified). Defaults to boolean false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/batch_put_attributes.phpt: * example::sdb/batch_put_attributes2.phpt: * example::sdb/batch_put_attributes4.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_PutAttributes.html * Related - , */ public function batch_put_attributes($domain_name, $item_keypairs, $replace = null, $returnCurlHandle = null) { $opt = array(); $opt['DomainName'] = $domain_name; $opt['returnCurlHandle'] = $returnCurlHandle; $is_replace_an_array = is_array($replace); // Cache this value // Start looping through the item-keypairs $item_count = 0; foreach ($item_keypairs as $item => $keypairs) { // Clear these for re-use unset($rstore); $rstore = array(); // Set the item name $opt['Item.' . (string) $item_count . '.ItemName'] = $item; // Start looping through the keypairs. $count = 0; foreach ($keypairs as $k => $v) { // Is one of the values an array? if (is_array($v)) { // Loop through each of them so that all values are passed as individual attributes. foreach ($v as $va) { $opt['Item.' . (string) $item_count . '.Attribute.' . (string) $count . '.Name'] = $k; $opt['Item.' . (string) $item_count . '.Attribute.' . (string) $count . '.Value'] = $va; // Do we want to do replacement? if ($replace) { // Do we have an array of key names? if ($is_replace_an_array) { // Store this key-index pair for later. $rstore[] = array( 'count' => $count, 'key' => $k ); } // Or just a since REPLACE ALL? else { $opt['Item.' . (string) $item_count . '.Attribute.' . (string) $count . '.Replace'] = 'true'; } } // Increment $count++; } } else { $opt['Item.' . (string) $item_count . '.Attribute.' . (string) $count . '.Name'] = $k; $opt['Item.' . (string) $item_count . '.Attribute.' . (string) $count . '.Value'] = $v; // Do we want to do replacement? if ($replace) { // Do we have an array of key names? if ($is_replace_an_array) { // Store this key-index pair for later. $rstore[] = array( 'count' => $count, 'key' => $k ); } // Or just a since REPLACE ALL? else { $opt['Item.' . (string) $item_count . '.Attribute.' . (string) $count . '.Replace'] = 'true'; } } } // Increment $count++; } // Go through all of the saved key-index pairs we saved earlier. foreach ($rstore as $k => $store) { if (isset($replace[$item])) { // Did we want to replace one of these keypairs? if (in_array($store['key'], $replace[$item])) { // Replace! $opt['Item.' . (string) $item_count . '.Attribute.' . (string) $store['count'] . '.Replace'] = 'true'; } } } // Increment $item_count++; } return $this->authenticate('BatchPutAttributes', $opt, $this->hostname); } /** * Method: get_attributes() * Returns all of the attributes associated with the item. Optionally, the attributes returned can be limited to one or more specified attribute name parameters. If the item does not exist on the replica that was accessed for this operation, an empty set is returned. The system does not return an error as it cannot guarantee the item does not exist on other replicas. * * Access: * public * * Parameters: * domain_name - _string_ (Required) The domain name to use for storing data. * item_name - _string_ (Required) The name of the base item which will contain the series of keypairs. * keys - _string|array_ (Optional) The name of the key (attribute) in the key-value pair that you want to return. Supports a string value (for single keys) or an indexed array (for multiple keys). * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/get_attributes.phpt: * example::sdb/get_attributes2.phpt: * example::sdb/get_attributes5.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_GetAttributes.html * Related - , */ public function get_attributes($domain_name, $item_name, $keys = null, $returnCurlHandle = null) { $opt = array(); $opt['DomainName'] = $domain_name; $opt['ItemName'] = $item_name; $opt['returnCurlHandle'] = $returnCurlHandle; if ($keys) { if (is_array($keys)) { $count = 0; foreach ($keys as $key) { $opt['AttributeName.' . (string) $count] = $key; $count++; } } else { $opt['AttributeName'] = $keys; } } return $this->authenticate('GetAttributes', $opt, $this->hostname); } /** * Method: delete_attributes() * Deletes one or more attributes associated with the item. If all attributes of an item are deleted, the item is deleted. If you specify DeleteAttributes without attributes or values, all the attributes for the item are deleted. DeleteAttributes is an idempotent operation; running it multiple times on the same item or attribute does not result in an error response. * * Access: * public * * Parameters: * domain_name - _string_ (Required) The domain name to use for storing data. * item_name - _string_ (Required) The name of the base item which will contain the series of keypairs. * keys - _string|array_ (Optional) The name of the key (attribute) in the key-value pair that you want to delete. Supports a string value (for single keys), an indexed array (for multiple keys), or an associative array containing one or more key-value pairs (for deleting specific values). * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/delete_attributes.phpt: * example::sdb/delete_attributes2.phpt: * example::sdb/delete_attributes3.phpt: * example::sdb/delete_attributes4.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_DeleteAttributes.html * Related - , */ public function delete_attributes($domain_name, $item_name, $keys = null, $returnCurlHandle = null) { $opt = array(); $opt['DomainName'] = $domain_name; $opt['ItemName'] = $item_name; $opt['returnCurlHandle'] = $returnCurlHandle; // Do we have a key? if ($keys) { // An array? if (is_array($keys)) { // Indexed array of Attribute Names? if (isset($keys[0]) && !empty($keys[0])) { for ($x = 0, $i = count($keys); $x < $i; $x++) { $opt['Attribute.' . (string) $x . '.Name'] = $keys[$x]; } } // Associative array of Name/Value pairs. else { $count = 0; foreach ($keys as $k => $v) { $opt['Attribute.' . (string) $count . '.Name'] = $k; $opt['Attribute.' . (string) $count . '.Value'] = $v; $count++; } } } // Single string Attribute Name. else { $opt['Attribute.Name'] = $keys; } } return $this->authenticate('DeleteAttributes', $opt, $this->hostname); } /*%******************************************************************************************%*/ // SELECT /** * Method: select() * The Select operation returns a set of Attributes for ItemNames that match the query expression. Select is similar to the standard SQL SELECT statement. * * The total size of the response cannot exceed 1 MB in total size. Amazon SimpleDB automatically adjusts the number of items returned per page to enforce this limit. For example, even if you ask to retrieve 250 items, but each individual item is 100 kB in size, the system returns 10 items and an appropriate next token so you can get the next page of results. * * Access: * public * * Parameters: * expression - _string_ (Optional) The SimpleDB select expression to use. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * NextToken - _string_ (Optional) String that tells Amazon SimpleDB where to start the next list of domain names. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sdb/select.phpt: * example::sdb/select2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_Select.html * Related - */ public function select($expression, $opt = null) { if (!$opt) $opt = array(); $opt['SelectExpression'] = $expression; $query = $this->authenticate('Select', $opt, $this->hostname); return $query; } } cloudfusion-2.5.0/_utilities.class.php0000644000000000000000000002413511337016604016543 0ustar rootroot object */ public function __construct() { return $this; } /** * Method: hex_to_base64() * Convert a HEX value to Base64. * * Access: * public * * Parameters: * str - _string_ (Required) Value to convert. * * Returns: * _string_ Base64-encoded string. * * Examples: * example::utilities/hex_to_base64.phpt: */ public function hex_to_base64($str) { $raw = ''; for ($i = 0; $i < strlen($str); $i += 2) { $raw .= chr(hexdec(substr($str, $i, 2))); } return base64_encode($raw); } /** * Method: to_query_string() * Convert an associative array into a query string. * * Access: * public * * Parameters: * array - _array_ (Required) Array to convert. * * Returns: * _string_ URL-friendly query string. * * Examples: * example::utilities/to_query_string.phpt: */ public function to_query_string($array) { return http_build_query($array); } /** * Method: to_signable_string() * Convert an associative array into a sign-able string. * * Access: * public * * Parameters: * array - _array_ (Required) Array to convert. * * Returns: * _string_ URL-friendly sign-able string. * * Examples: * example::utilities/to_signable_string.phpt: */ public function to_signable_string($array) { $t = array(); foreach ($array as $k => $v) { $t[] = $this->encode_signature2($k) . '=' . $this->encode_signature2($v); } return implode('&', $t); } /** * Method: encode_signature2() * Encode the value according to RFC 3986. * * Access: * public * * Parameters: * string - _string_ (Required) String to convert * * Returns: * _string_ URL-friendly sign-able string. */ public function encode_signature2($string) { $string = rawurlencode($string); return str_replace('%7E', '~', $string); } /** * Method: query_to_array() * Convert a query string into an associative array. Multiple, identical keys will become an indexed array. * * Access: * public * * Parameters: * qs - _string_ (Required) Query string to convert. * * Returns: * _array_ Associative array of keys and values. * * Examples: * example::utilities/query_to_array.phpt: * example::utilities/query_to_array2.phpt: */ public function query_to_array($qs) { $query = explode('&', $qs); $data = array(); foreach ($query as $q) { $q = explode('=', $q); if (isset($data[$q[0]]) && is_array($data[$q[0]])) { $data[$q[0]][] = urldecode($q[1]); } else if (isset($data[$q[0]]) && !is_array($data[$q[0]])) { $data[$q[0]] = array($data[$q[0]]); $data[$q[0]][] = urldecode($q[1]); } else { $data[urldecode($q[0])] = urldecode($q[1]); } } return $data; } /** * Method: size_readable() * Return human readable file sizes. Original function by Aidan Lister , modified by Ryan Parman. * * Access: * public * * Parameters: * size - _integer_ (Required) Filesize in bytes. * unit - _string_ (Optional) The maximum unit to use. Defaults to the largest appropriate unit. * retstring - _string_ (Optional) The format for the return string. Defaults to '%01.2f %s' * * Returns: * _string_ The human-readable file size. * * Examples: * example::utilities/size_readable.phpt: * example::utilities/size_readable2.phpt: * example::utilities/size_readable3.phpt: * * See Also: * Original Function - http://aidanlister.com/repos/v/function.size_readable.php */ public function size_readable($size, $unit = null, $retstring = null) { // Units $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB'); $mod = 1024; $ii = count($sizes) - 1; // Max unit $unit = array_search((string) $unit, $sizes); if ($unit === null || $unit === false) { $unit = $ii; } // Return string if ($retstring === null) { $retstring = '%01.2f %s'; } // Loop $i = 0; while ($unit != $i && $size >= 1024 && $i < $ii) { $size /= $mod; $i++; } return sprintf($retstring, $size, $sizes[$i]); } /** * Method: time_hms() * Convert a number of seconds into Hours:Minutes:Seconds. * * Access: * public * * Parameters: * seconds - _integer_ (Required) The number of seconds to convert. * * Returns: * _string_ The formatted time. * * Examples: * example::utilities/time_hms.phpt: */ public function time_hms($seconds) { $time = ''; // First pass $hours = (int) ($seconds / 3600); $seconds = $seconds % 3600; $minutes = (int) ($seconds / 60); $seconds = $seconds % 60; // Cleanup $time .= ($hours) ? $hours . ':' : ''; $time .= ($minutes < 10 && $hours > 0) ? '0' . $minutes : $minutes; $time .= ':'; $time .= ($seconds < 10) ? '0' . $seconds : $seconds; return $time; } /** * Method: try_these() * Returns the first value that is set. Based on Try.these() from Prototype . * * Access: * public * * Parameters: * attrs - _array_ (Required) The attributes to test, as strings. Intended for testing properties of the $base object, but also works with variables if you place an @ symbol at the beginning of the command. * base - _object_ (Optional) The base object to use, if any. * default - _mixed_ (Optional) What to return if there are no matches. Defaults to null. * * Returns: * _mixed_ Either a matching property of a given object, _boolean_ false, or any other data type you might choose. * * Examples: * example::utilities/try_these.phpt: * example::utilities/try_these2.phpt: * example::utilities/try_these3.phpt: * example::utilities/try_these4.phpt: * example::utilities/try_these5.phpt: */ public function try_these($attrs, $base = null, $default = null) { if ($base) { foreach ($attrs as $attr) { if (isset($base->$attr)) { return $base->$attr; } } } else { foreach ($attrs as $attr) { if (isset($attr)) { return $attr; } } } return $default; } /** * Method: json_encode() * Replicates json_encode() for versions of PHP 5 earlier than 5.2. * * Access: * public * * Parameters: * obj - _mixed_ (Required) The PHP object to convert into a JSON string. * * Returns: * _string_ A JSON string. * * Examples: * example::utilities/json_encode2.phpt: * example::utilities/json_encode3.phpt: * example::utilities/json_encode4.phpt: * example::utilities/json_encode5.phpt: * example::utilities/json_encode6.phpt: */ public function json_encode($obj) { if (function_exists('json_encode')) { return json_encode($obj); } return $this->json_encode_php51($obj); } /** * Method: json_encode_php51() * Called by CFUtilities::json_encode() if PHP 5.2's json_encode() is unavailable. DO NOT CALL THIS METHOD DIRECTLY! Use $obj->util->json_encode() instead. * * Author: * http://us2.php.net/manual/en/function.json-encode.php#82904 * * Access: * public * * Parameters: * obj - _mixed_ (Required) The PHP object to convert into a JSON string. * * Returns: * _string_ A JSON string. */ public function json_encode_php51($obj) { if (is_null($obj)) return 'null'; if ($obj === false) return 'false'; if ($obj === true) return 'true'; if (is_scalar($obj)) { if (is_float($obj)) { // Always use '.' for floats. return str_replace(',', '.', strval($obj)); } elseif (is_int($obj)) { return strval($obj); } elseif (is_string($obj)) { static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $obj) . '"'; } return $obj; } $isList = true; for ($i = 0, reset($obj); $i < count($obj); $i++, next($obj)) { if (key($obj) !== $i) { $isList = false; break; } } $result = array(); if ($isList) { foreach ($obj as $v) { $result[] = json_encode($v); } return '[' . join(',', $result) . ']'; } else { foreach ($obj as $k => $v) { $result[] = json_encode($k).':'.json_encode($v); } return '{' . join(',', $result) . '}'; } } /** * Method: convert_response_to_array() * Converts a SimpleXML response to an array structure. * * Author: * Adrien Cahen * * Access: * public * * Parameters: * obj - _ResponseCore_ (Required) A CloudFusion ResponseCore response value. * * Returns: * _array_ The response value as a standard, multi-dimensional array. * * Examples: * example::utilities/convert_response_to_array.phpt: * * Requirements: * PHP 5.2 or newer. */ public function convert_response_to_array(ResponseCore $response) { return json_decode(json_encode((array) $response), true); } /** * Method: convert_date_to_iso8601() * Checks to see if a date stamp is ISO-8601 formatted, and if not, makes it so. * * Access: * public * * Parameters: * datestamp - _string_ (Required) A date stamp, or a string that can be parsed into a date stamp. * * Returns: * _string_ An ISO-8601 formatted date stamp. * * Examples: * example::utilities/convert_date_to_iso8601.phpt: */ public function convert_date_to_iso8601($datestamp) { if (!preg_match('/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}((\+|-)\d{2}:\d{2}|Z)/m', $datestamp)) { return gmdate(DATE_FORMAT_ISO8601, strtotime($datestamp)); } return $datestamp; } } cloudfusion-2.5.0/README.textile0000644000000000000000000000605311337016604015110 0ustar rootrooth1. CloudFusion Build awesome, cloud-based web applications in a fraction of the time! h2. Requirements * PHP 5.1.4 or newer (PHP 5.2+ recommended) * SimpleXML extension * cURL extension with SSL support Caching support requires one or more of the following: * *File:* Write permissions to the file system. * *APC:* APC extension * *XCache:* XCache extension * *Memcache:* Memcached system service, Memcache PHP extension * *SQLite:* PDO extension, PDO_SQLITE adapter, SQLite extension * *MySQL:* PDO extension, PDO_MYSQL adapter, MySQL extension (or mysqlnd for PHP 5.3) * *PostgreSQL:* PDO extension, PDO_PGSQL adapter, PGSQL extension h2. Get the latest code The following will pull down the latest development code, including CacheCore and RequestCore.
git clone git://github.com/skyzyx/cloudfusion.git
cd cloudfusion
git submodule init
git submodule update
h2. Donate Help me stop being broke by donating anything you can towards the further development of this software. h2. Getting the hang of Git As of early November 2009, CloudFusion has moved to the Git SCM and GitHub for a code repository. h3. Mac Mac users can install Git either from "the installer":http://code.google.com/p/git-osx-installer/downloads/list?can=3 or via "MacPorts":http://macports.org. If installing via MacPorts, I'd recommend calling sudo port install git-core +svn. h3. Windows Windows users can install "msys-git":http://code.google.com/p/msysgit/ or "TortoiseGit":http://code.google.com/p/tortoisegit/. "Getting started with Git and Github on Windows":http://kylecordes.com/2008/04/30/git-windows-go/ would be a good place to start. h3. Linux Depending on your flavor of Linux you can likely either use yum or apt-get to install the Git package. h2. Contributing I want to see CloudFusion become a community project. If you have a patch for a bug or new feature, fork CloudFusion, make the updates, then send me a Github pull request. This makes patching much easier. It's even better when it's unit tested. Bug fix patches should include matching "PHPT":http://qa.php.net/write-test.php unit tests, and new features should include unit tests and documentation in "NaturalDocs":http://naturaldocs.org format. Documentation is equally as important as the code itself, and unit tests are actually used for code samples within the documentation. Doing your best will make my job easier. :) I definitely need help with: * Writing PHPT tests for the S3 class * Writing PHPT tests for the EC2 class * Supporting the new EC2-related services that have come out in the past few months h2. Links * "Main site":http://getcloudfusion.com * "API reference":http://getcloudfusion.com/docs/latest * "Tutorials and screencasts":http://getcloudfusion.com/docs * "Discussion and support list":http://getcloudfusion.com/discussion * Donate! -- Click the little "Donate" button in the upper-right corner h2. License Code is BSD licensed. Documentation and tutorials are Creative Commons licensed. You can find exact details in the footer of the main site. cloudfusion-2.5.0/sqsqueue.class.php0000644000000000000000000002131611337016604016242 0ustar rootroot constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * * Returns: * _boolean_ false if no valid values are set, otherwise true. * * Examples: * example::sqsqueue/5_send_message.phpt: * example::sqsqueue/7_receive_message.phpt: * example::sqsqueue/8_delete_message.phpt: */ public function __construct($queue = null, $key = null, $secret_key = null) { $this->queue_name = $queue; return parent::__construct($key, $secret_key); } /*%******************************************************************************************%*/ // QUEUES /** * Method: create_queue() * Identical to . The queue URL created from this method will replace the queue URL already being used with this class. * * New queue URL will NOT automatically apply when using MultiCurl for parallel requests. * * Access: * public * * Parameters: * queue_name - See . * returnCurlHandle - See . * * Returns: * object * * Examples: * example::sqsqueue/1_create_queue.phpt: * example::sqsqueue/1_create_queue3.phpt: */ public function create_queue($queue_name, $returnCurlHandle = null) { $data = parent::create_queue($queue_name, $returnCurlHandle); if ($data instanceof ResponseCore) { $this->queue_name = (string) $data->body->CreateQueueResult->QueueUrl; } return $data; } /** * Method: delete_queue() * Identical to , except that you don't need to pass in a queue URL. * * Access: * public * * Parameters: * returnCurlHandle - See . * * Returns: * object * * Examples: * example::sqsqueue/z_delete_queue.phpt: * example::sqsqueue/z_delete_queue3.phpt: */ public function delete_queue($returnCurlHandle = null) { if ($this->queue_name) { return parent::delete_queue($this->queue_name, $returnCurlHandle); } throw new SQSQueue_Exception(SQSQUEUE_DEFAULT_ERROR); } /** * Method: get_queue_attributes() * Identical to , except that you don't need to pass in a queue URL. * * Access: * public * * Parameters: * attributes - _string_|_array_ (Optional) The attribute you want to get. Setting this value to 'All' returns all the queue's attributes. Pass a string for a single attribute, or an indexed array for multiple attributes. Possible values are 'All', 'ApproximateNumberOfMessages', 'VisibilityTimeout', 'CreatedTimestamp', 'LastModifiedTimestamp', and 'Policy'. Defaults to 'All'. * returnCurlHandle - See . * * Returns: * object * * Examples: * example::sqsqueue/4_get_queue_attributes.phpt: * example::sqsqueue/4_get_queue_attributes4.phpt: * example::sqsqueue/4_get_queue_attributes5.phpt: */ public function get_queue_attributes($attributes = 'All', $returnCurlHandle = null) { if ($this->queue_name) { return parent::get_queue_attributes($this->queue_name, $attributes, $returnCurlHandle); } throw new SQSQueue_Exception(SQSQUEUE_DEFAULT_ERROR); } /** * Method: set_queue_attributes() * Identical to , except that you don't need to pass in a queue URL. * * Access: * public * * Parameters: * opt - See . * * Returns: * object * * Examples: * example::sqsqueue/3_set_queue_attributes.phpt: */ public function set_queue_attributes($opt = null) { if ($this->queue_name) { return parent::set_queue_attributes($this->queue_name, $opt); } throw new SQSQueue_Exception(SQSQUEUE_DEFAULT_ERROR); } /*%******************************************************************************************%*/ // MESSAGES /** * Method: send_message() * Identical to , except that you don't need to pass in a queue URL. * * Access: * public * * Parameters: * message - See . * returnCurlHandle - See . * * Returns: * object * * Examples: * example::sqsqueue/5_send_message.phpt: * example::sqsqueue/5_send_message3.phpt: */ public function send_message($message, $returnCurlHandle = null) { if ($this->queue_name) { return parent::send_message($this->queue_name, $message, $returnCurlHandle); } throw new SQSQueue_Exception(SQSQUEUE_DEFAULT_ERROR); } /** * Method: receive_message() * Identical to , except that you don't need to pass in a queue URL. * * Access: * public * * Parameters: * opt - See . * * Returns: * object * * Examples: * example::sqsqueue/7_receive_message.phpt: * example::sqsqueue/7_receive_message3.phpt: * example::sqsqueue/7_receive_message4.phpt: * example::sqsqueue/7_receive_message7.phpt: * example::sqsqueue/7_receive_message8.phpt: */ public function receive_message($opt = null) { if ($this->queue_name) { return parent::receive_message($this->queue_name, $opt); } throw new SQSQueue_Exception(SQSQUEUE_DEFAULT_ERROR); } /** * Method: delete_message() * Identical to , except that you don't need to pass in a queue URL. * * Access: * public * * Parameters: * receipt_handle - See . * returnCurlHandle - See . * * Returns: * object * * Examples: * example::sqsqueue/8_delete_message.phpt: */ public function delete_message($receipt_handle, $returnCurlHandle = null) { if ($this->queue_name) { return parent::delete_message($this->queue_name, $receipt_handle, $returnCurlHandle); } throw new SQSQueue_Exception(SQSQUEUE_DEFAULT_ERROR); } /** * */ public function change_message_visibility() { } /*%******************************************************************************************%*/ // ACCESS CONTROL METHODS // Inherit from parent class // public function generate_policy() {} public function add_permission() {} public function remove_permission() {} /*%******************************************************************************************%*/ // HELPER/UTILITY METHODS /** * Method: get_queue_size() * Identical to , except that you don't need to pass in a queue URL. * * Access: * public * * Returns: * _integer_ The Approximate number of messages in the queue. * * Examples: * example::sqsqueue/6_get_queue_size.phpt: */ public function get_queue_size() { if ($this->queue_name) { return parent::get_queue_size($this->queue_name); } throw new SQSQueue_Exception(SQSQUEUE_DEFAULT_ERROR); } } cloudfusion-2.5.0/cloudfront.class.php0000644000000000000000000006430711337016604016555 0ustar rootroot constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * * Returns: * _boolean_ false if no valid values are set, otherwise true. */ public function __construct($key = null, $secret_key = null) { $this->api_version = '2009-12-01'; $this->hostname = CDN_DEFAULT_URL; $this->base_standard_xml = ''; $this->base_streaming_xml = ''; if (!$key && !defined('AWS_KEY')) { throw new CloudFront_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.'); } if (!$secret_key && !defined('AWS_SECRET_KEY')) { throw new CloudFront_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.'); } return parent::__construct($key, $secret_key); } /*%******************************************************************************************%*/ // AUTHENTICATION /** * Method: authenticate() * Authenticates a connection to CloudFront. This should not be used directly unless you're writing custom methods for this class. * * Access: * public * * Parameters: * method - _string_ (Required) The HTTP method to use to connect. Accepts , , , , and . * path - _string_ (Optional) The endpoint path to make requests to. * opt - _array_ (Optional) Associative array of parameters for authenticating. See the individual methods for allowed keys. * xml - _string_ (Optional) The XML body content to send along in the request. * etag - _string_ (Optional) The ETag value to pass along with the If-Match HTTP header. * * Returns: * object * * See Also: * http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/RESTAuthentication.html */ public function authenticate($method = HTTP_GET, $path = null, $opt = null, $xml = null, $etag = null) { $querystring = null; if (!$opt) $opt = array(); // Generate the querystring from $opt, removing a reference to returnCurlHandle. if ($opt) { $query = $opt; if (isset($query['returnCurlHandle'])) { unset($query['returnCurlHandle']); } if (isset($query['Streaming'])) { unset($query['Streaming']); } if (count($query) > 0) { $querystring = '?' . $this->util->to_query_string($query); } } // Gather information to pass along to other classes. $helpers = array( 'utilities' => $this->utilities_class, 'request' => $this->request_class, 'response' => $this->response_class, ); // Compose the request. if (isset($opt['Streaming']) && $opt['Streaming'] == (bool) true) // Did we ask to stream? { $request_url = 'https://' . $this->hostname . '/' . $this->api_version . '/streaming-distribution'; } else { $request_url = 'https://' . $this->hostname . '/' . $this->api_version . '/distribution'; } $request_url .= ($path) ? $path : ''; $request_url .= ($querystring) ? $querystring : ''; $request = new $this->request_class($request_url, $this->set_proxy, $helpers); // Generate required headers. $request->set_method($method); $canonical_date = gmdate(DATE_FORMAT_RFC2616); $request->add_header('x-amz-date', $canonical_date); $signature = $this->util->hex_to_base64(hash_hmac('sha1', $canonical_date, $this->secret_key)); $request->add_header('Authorization', 'AWS ' . $this->key . ':' . $signature); // Add configuration XML if we have it. if ($xml) { $request->add_header('Content-Length', strlen($xml)); $request->add_header('Content-Type', 'text/plain'); $request->set_body($xml); } // Set If-Match: ETag header if we have one. if ($etag) { $request->add_header('If-Match', $etag); } // If we have a "true" value for returnCurlHandle, do that instead of completing the request. if (isset($opt['returnCurlHandle'])) { return $request->prep_request(); } // Send! $request->send_request(); // Prepare the response. $headers = $request->get_response_header(); $headers['x-cloudfusion-requesturl'] = $request_url; if ($xml) $headers['x-cloudfusion-body'] = $xml; $data = new $this->response_class($headers, new SimpleXMLElement($request->get_response_body()), $request->get_response_code()); // Return! return $data; } /*%******************************************************************************************%*/ // SET CUSTOM SETTINGS /** * Method: disable_ssl() * Throws an error because SSL is required for the CloudFront service. * * Access: * public * * Returns: * void */ public function disable_ssl() { throw new CloudFront_Exception('SSL/HTTPS is REQUIRED for CloudFront and cannot be disabled.'); } /*%******************************************************************************************%*/ // GENERATE DISTRIBUTION CONFIG XML /** * Method: generate_config_xml() * Used to generate the Distribution Config XML used in and . * * Access: * public * * Parameters: * origin - _string_ (Required) The source S3 bucket to use for the CloudFront distribution. * caller_reference - _string_ (Required) A unique identifier for the request. Must be generated on your own. A time stamp or hash is a good example. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * CNAME - _string_|_array_ (Optional) A DNS CNAME to use to map to the CloudFront distribution. If setting more than one, use an indexed array. Supports 1-10 CNAMEs. * Comment - _integer_ (Optional) A comment to apply to the distribution. Cannot exceed 128 characters. * Enabled - _string_ (Optional) Defaults to true. Use this to set Enabled to false. * Streaming - _boolean_ (Optional) Whether this should be for a streaming distribution or not. Defaults to false. * * Returns: * String DistributionConfig XML document. * * Examples: * example::cloudfront/generate_config_xml3.phpt: * example::cloudfront/generate_config_xml4.phpt: * example::cloudfront/generate_config_xml5.phpt: * example::cloudfront/generate_config_xml9.phpt: * example::cloudfront/generate_config_xml10.phpt: * * See Also: * Related - , , */ public function generate_config_xml($origin, $caller_reference, $opt = null) { // Default, empty XML if (isset($opt['Streaming']) && $opt['Streaming'] == (bool) true) // Did we ask to stream? { $xml = simplexml_load_string($this->base_streaming_xml); } else { $xml = simplexml_load_string($this->base_standard_xml); } // Origin if (stripos($origin, '.s3.amazonaws.com') !== false) { $xml->addChild('Origin', $origin); } else { $xml->addChild('Origin', $origin . '.s3.amazonaws.com'); } // CallerReference $xml->addChild('CallerReference', $caller_reference); // CNAME if (isset($opt['CNAME'])) { if (is_array($opt['CNAME'])) { foreach ($opt['CNAME'] as $cname) { $xml->addChild('CNAME', $cname); } } else { $xml->addChild('CNAME', $opt['CNAME']); } } // Comment if (isset($opt['Comment'])) { $xml->addChild('Comment', $opt['Comment']); } // Enabled if (isset($opt['Enabled'])) { $xml->addChild('Enabled', $opt['Enabled'] ? 'true' : 'false'); } else { $xml->addChild('Enabled', 'true'); } // Logging if (isset($opt['Logging'])) { if (is_array($opt['Logging'])) { $logging = $xml->addChild('Logging'); $bucket_name = $opt['Logging']['Bucket']; // Origin if (stripos($bucket_name, '.s3.amazonaws.com') !== false) { $logging->addChild('Bucket', $bucket_name); } else { $logging->addChild('Bucket', $bucket_name . '.s3.amazonaws.com'); } $logging->addChild('Prefix', $opt['Logging']['Prefix']); } } return $xml->asXML(); } /** * Method: update_config_xml() * Used to update an existing DistributionConfig XML document. * * Access: * public * * Parameters: * xml - _SimpleXMLElement_|_ResponseCore_|_string_ (Required) The source DistributionConfig XML to make updates to. Can be the SimpleXMLElement body of a response, the entire of a response, or a string of XML generated by or . * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * CNAME - _string_|_array_ (Optional) This (these) value(s) will be ADDED to the existing list of CNAME values. To remove a CNAME value, see . * Comment - _integer_ (Optional) This value will replace the existing value for 'Comment'. Cannot exceed 128 characters. * Enabled - _string_ (Optional) This value will replace the existing value for 'Enabled'. * Streaming - _boolean_ (Optional) Whether this should be for a streaming distribution or not. Defaults to false. * * Returns: * String DistributionConfig XML document. * * Examples: * example::cloudfront/update_config_xml4.phpt: * example::cloudfront/update_config_xml10.phpt: * * See Also: * Related - , , */ public function update_config_xml($xml, $opt = null) { // If we receive a full ResponseCore object, only use the body. if ($xml instanceof ResponseCore) { $xml = $xml->body; } // If we received a string of XML, convert it into a SimpleXMLElement object. if (is_string($xml)) { $xml = simplexml_load_string($xml); } // Default, empty XML if (isset($opt['Streaming']) && $opt['Streaming'] == (bool) true) // Did we ask to stream? { $update = simplexml_load_string($this->base_streaming_xml); } else { $update = simplexml_load_string($this->base_standard_xml); } // These can't change. $update->addChild('Origin', $xml->Origin); $update->addChild('CallerReference', $xml->CallerReference); // Add existing CNAME values if ($xml->CNAME) { $update->addChild('CNAME', $xml->CNAME); } // Add new CNAME values if (isset($opt['CNAME'])) { if (is_array($opt['CNAME'])) { foreach ($opt['CNAME'] as $cname) { $update->addChild('CNAME', $cname); } } else { $update->addChild('CNAME', $opt['CNAME']); } } // Comment if (isset($opt['Comment'])) { $update->addChild('Comment', $opt['Comment']); } elseif (isset($xml->Comment)) { $update->addChild('Comment', $xml->Comment); } // Enabled if (isset($opt['Enabled'])) { $update->addChild('Enabled', $opt['Enabled'] ? 'true' : 'false'); } elseif (isset($xml->Enabled)) { $update->addChild('Enabled', $xml->Enabled); } // Logging if (isset($opt['Logging'])) { if (is_array($opt['Logging'])) { $logging = $update->addChild('Logging'); $bucket_name = $opt['Logging']['Bucket']; // Origin if (stripos($bucket_name, '.s3.amazonaws.com') !== false) { $logging->addChild('Bucket', $bucket_name); } else { $logging->addChild('Bucket', $bucket_name . '.s3.amazonaws.com'); } $logging->addChild('Prefix', $opt['Logging']['Prefix']); } } elseif (isset($xml->Logging)) { $logging = $update->addChild('Logging'); $logging->addChild('Bucket',$xml->Logging->Bucket); $logging->addChild('Prefix', $xml->Logging->Prefix); } // Output return $update->asXML(); } /** * Method: remove_cname() * Used to remove one or more CNAMEs from a DistributionConfig XML document. * * Access: * public * * Parameters: * xml - _SimpleXMLElement_|_ResponseCore_|_string_ (Required) The source DistributionConfig XML to make updates to. Can be the SimpleXMLElement body of a response, the entire of a response, or a string of XML generated by or . * cname - _string_|_array_ (Optional) This (these) value(s) will be REMOVED from the existing list of CNAME values. To add a CNAME value, see . * * Returns: * String DistributionConfig XML document. * * Examples: * example::cloudfront/remove_cname2.phpt: * * See Also: * Related - , , */ public function remove_cname($xml, $cname) { // If we receive a full ResponseCore object, only use the body. if ($xml instanceof ResponseCore) { $xml = $xml->body; } // If we received a string of XML, convert it into a SimpleXMLElement object. if (is_string($xml)) { $xml = simplexml_load_string($xml); } // Let's make sure that we have CNAMEs to remove in the first place. if (isset($xml->CNAME)) { // If we have an array of CNAME values... if (is_array($cname)) { foreach ($cname as $cn) { for ($i = 0, $length = sizeof($xml->CNAME); $i < $length; $i++) { if ((string) $xml->CNAME[$i] == $cn) { unset($xml->CNAME[$i]); break; } } } } // If we only have one CNAME value... else { for ($i = 0, $length = sizeof($xml->CNAME); $i < $length; $i++) { if ((string) $xml->CNAME[$i] == $cname) { unset($xml->CNAME[$i]); break; } } } } return $xml->asXML(); } /*%******************************************************************************************%*/ // DISTRIBUTIONS /** * Method: create_distribution() * The response echoes the DistributionConfig element and returns other metadata about the distribution. For more information, see Parts of a Basic Distribution. It takes a short time for CloudFront to propagate your new distribution's information throughout the CloudFront system. For more information, see Eventual Consistency. You can have up to 100 distributions in the Amazon CloudFront system. * * For an Adobe Real-Time Messaging Protocol (RTMP) streaming distribution, set the Streaming option to true. * * Access: * public * * Parameters: * origin - _string_ (Required) The source S3 bucket to use for the CloudFront distribution. * caller_reference - _integer_ (Required) A unique identifier for the request. Must be generated on your own. A timestamp could be good. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * CNAME - _string_|_array_ (Optional) A DNS CNAME to use to map to the CloudFront distribution. If setting more than one, use an indexed array. Supports 1-10 CNAMEs. * Comment - _integer_ (Optional) A comment to apply to the distribution. Cannot exceed 128 characters. * Enabled - _string_ (Optional) Defaults to true. Use this to set Enabled to false. * Streaming - _boolean_ (Optional) Whether this should be for a streaming distribution or not. Defaults to false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::cloudfront/create_distribution.phpt: * example::cloudfront/create_distribution3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/CreateDistribution.html * Related - , , , */ public function create_distribution($origin, $caller_reference, $opt = null) { $auth = array(); if (isset($opt['returnCurlHandle'])) { $auth['returnCurlHandle'] = $opt['returnCurlHandle']; unset($opt['returnCurlHandle']); } if (isset($opt['Streaming']) && $opt['Streaming'] == (bool) true) { $auth['Streaming'] = $opt['Streaming']; } $xml = $this->generate_config_xml($origin, $caller_reference, $opt); return $this->authenticate(HTTP_POST, null, $auth, $xml, null); } /** * Method: list_distributions() * Gets a list of your distributions. By default, your entire list of distributions is returned in one single page. If the list is long, you can paginate it using the MaxItems and Marker parameters. * * Standard distributions are listed separately from streaming distributions. For streaming distributions, set the Streaming option to true. * * Access: * public * * Parameters: * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * Marker - _string_ (Optional) Use this when paginating results to indicate where in your list of distributions to begin. The results include distributions in the list that occur after the marker. To get the next page of results, set the Marker to the value of the NextMarker from the current page's response (which is also the ID of the last distribution on that page). * MaxItems - _integer_ (Optional) The maximum number of distributions you want in the response body. Maximum of 100. * Streaming - _boolean_ (Optional) Whether this should be for a streaming distribution or not. Defaults to false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::cloudfront/list_distributions.phpt: * example::cloudfront/list_distributions2.phpt: * example::cloudfront/list_distributions4.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/ListDistributions.html * Related - , , , */ public function list_distributions($opt = null) { return $this->authenticate(HTTP_GET, null, $opt, null, null); } /** * Method: get_distribution_info() * Gets information about a given distribution. * * Standard distributions are handled separately from streaming distributions. For streaming distributions, set the Streaming option to true. * * Access: * public * * Parameters: * distribution_id - _string_ (Required) The distribution ID returned from or . * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * Streaming - _boolean_ (Optional) Whether this should be for a streaming distribution or not. Defaults to false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::cloudfront/get_distribution_info.phpt: * example::cloudfront/get_distribution_info3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/GetDistribution.html * Related - , , , */ public function get_distribution_info($distribution_id, $opt = null) { return $this->authenticate(HTTP_GET, '/' . $distribution_id, $opt, null, null); } /** * Method: delete_distribution() * Deletes a disabled distribution. If you haven't disabled the distribution, Amazon CloudFront returns a DistributionNotDisabled error. Use to disable a distribution before attempting to delete. * * For an Adobe Real-Time Messaging Protocol (RTMP) streaming distribution, set the Streaming option to true. * * Access: * public * * Parameters: * distribution_id - _string_ (Required) The distribution ID returned from or . * etag - _string_ (Required) The ETag header value retrieved from a call to . * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * Streaming - _boolean_ (Optional) Whether this should be for a streaming distribution or not. Defaults to false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::cloudfront/z_delete_distribution.phpt: * example::cloudfront/z_delete_distribution2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/DeleteDistribution.html * Related - , , , */ public function delete_distribution($distribution_id, $etag = null, $opt = null) { return $this->authenticate(HTTP_DELETE, '/' . $distribution_id, $opt, null, $etag); } /*%******************************************************************************************%*/ // DISTRIBUTION CONFIG /** * Method: get_distribution_config() * Gets the current distribution config information for a given distribution ID. * * Standard distributions are handled separately from streaming distributions. For streaming distributions, set the Streaming option to true. * * Access: * public * * Parameters: * distribution_id - _string_ (Required) The distribution ID returned from or . * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * Streaming - _boolean_ (Optional) Whether this should be for a streaming distribution or not. Defaults to false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::cloudfront/get_distribution_config.phpt: * example::cloudfront/get_distribution_config2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/GetConfig.html * Related - , */ public function get_distribution_config($distribution_id, $opt = null) { return $this->authenticate(HTTP_GET, '/' . $distribution_id . '/config', $opt, null, null); } /** * Method: set_distribution_config() * Sets a new distribution config for a given distribution ID. * * Standard distributions are handled separately from streaming distributions. For streaming distributions, set the Streaming option to true. * * Access: * public * * Parameters: * distribution_id - _string_ (Required) The distribution ID returned from or . * xml - _string_ (Required) The DistributionConfig XML generated by or . * etag - _string_ (Required) The ETag header value retrieved from a call to . * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * Streaming - _boolean_ (Optional) Whether this should be for a streaming distribution or not. Defaults to false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::cloudfront/set_distribution_config.phpt: * example::cloudfront/set_distribution_config3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/PutConfig.html * Related - , */ public function set_distribution_config($distribution_id, $xml, $etag, $opt = null) { return $this->authenticate(HTTP_PUT, '/' . $distribution_id . '/config', $opt, $xml, $etag); } } cloudfusion-2.5.0/pas.class.php0000755000000000000000000041476311337016604015171 0ustar rootroot constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * assoc_id - _string_ (Optional) Your Amazon Associates ID. If blank, it will look for the constant. * * Returns: * _boolean_ false if no valid values are set, otherwise true. */ public function __construct($key = null, $secret_key = null, $assoc_id = null) { $this->api_version = '2009-07-01'; if (!$key && !defined('AWS_KEY')) { throw new PAS_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.'); } if (!$secret_key && !defined('AWS_SECRET_KEY')) { throw new PAS_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.'); } if (!$assoc_id && !defined('AWS_ASSOC_ID')) { throw new PAS_Exception('No Amazon Associates ID was passed into the constructor, nor was it set in the AWS_ASSOC_ID constant.'); } return parent::__construct($key, $secret_key, null, $assoc_id); } /*%******************************************************************************************%*/ // SET CUSTOM SETTINGS /** * Method: set_locale() * Override the default locale to use for PAS requests. * * Access: * public * * Parameters: * locale - _string_ (Optional) The locale to use. Allows PAS_LOCALE_US, PAS_LOCALE_UK, PAS_LOCALE_CANADA, PAS_LOCALE_FRANCE, PAS_LOCALE_GERMANY, PAS_LOCALE_JAPAN * * Examples: * example::pas/set_locale.phpt: * example::pas/set_locale7.phpt: * * Returns: * void */ public function set_locale($locale = null) { $this->locale = $locale; } /*%******************************************************************************************%*/ // CORE FUNCTIONALITY /** * Method: authenticate() * Construct a URL to request from Amazon, request it, and return a formatted response. * * Access: * public * * Parameters: * action - _string_ (Required) Indicates the action to perform. * opt - _array_ (Optional) Associative array of parameters. See the individual methods for allowed keys. * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Returns: * object */ public function pas_authenticate($action, $opt = null, $locale = null) { // If there is no locale, use the default one. if ($locale === null) { // Was this set with set_locale()? if ($this->locale !== null) { $locale = $this->locale; } // Fall back to the one set in the config file. else { $locale = (defined('AWS_DEFAULT_LOCALE')) ? AWS_DEFAULT_LOCALE : null; } } // Determine the hostname switch ($locale) { // United Kingdom case PAS_LOCALE_UK: $hostname = 'ecs.amazonaws.co.uk'; break; // Canada case PAS_LOCALE_CANADA: $hostname = 'ecs.amazonaws.ca'; break; // France case PAS_LOCALE_FRANCE: $hostname = 'ecs.amazonaws.fr'; break; // Germany case PAS_LOCALE_GERMANY: $hostname = 'ecs.amazonaws.de'; break; // Japan case PAS_LOCALE_JAPAN: $hostname = 'ecs.amazonaws.jp'; break; // Default to United States default: $hostname = 'ecs.amazonaws.com'; break; } // Use alternate hostname, if one exists. if ($this->hostname) { $hostname = $this->hostname; } $return_curl_handle = false; $key_prepend = 'AWSAccessKeyId=' . $this->key . '&'; // Manage the key-value pairs that are used in the query. $query['Operation'] = $action; $query['Service'] = 'AWSECommerceService'; $query['SignatureMethod'] = 'HmacSHA256'; $query['SignatureVersion'] = 2; $query['Timestamp'] = gmdate(DATE_FORMAT_ISO8601, time() + $this->adjust_offset); $query['Version'] = $this->api_version; // Merge in any options that were passed in if (is_array($opt)) { $query = array_merge($query, $opt); } $return_curl_handle = isset($query['returnCurlHandle']) ? $query['returnCurlHandle'] : false; unset($query['returnCurlHandle']); // Do a case-insensitive, natural order sort on the array keys. uksort($query, 'strcasecmp'); // Create the string that needs to be hashed. $canonical_query_string = $key_prepend . $this->util->to_signable_string($query); // Set the proper verb. $verb = HTTP_GET; // Set the proper path $path = '/onca/xml'; // Prepare the string to sign $stringToSign = "$verb\n$hostname\n$path\n$canonical_query_string"; // Hash the AWS secret key and generate a signature for the request. $query['Signature'] = $this->util->hex_to_base64(hash_hmac('sha256', $stringToSign, $this->secret_key)); // Generate the querystring from $query $querystring = $key_prepend . $this->util->to_query_string($query); // Gather information to pass along to other classes. $helpers = array( 'utilities' => $this->utilities_class, 'request' => $this->request_class, 'response' => $this->response_class, ); // Compose the request. $request_url = $this->enable_ssl ? 'https://' : 'http://'; $request_url .= $hostname; $request_url .= $path; $request_url .= '?' . $querystring; $request = new $this->request_class($request_url, $this->set_proxy, $helpers); $request->set_useragent(CLOUDFUSION_USERAGENT); // If we have a "true" value for returnCurlHandle, do that instead of completing the request. if ($return_curl_handle) { return $request->prep_request(); } // Send! $request->send_request(); // Prepare the response. $headers = $request->get_response_header(); $headers['x-cloudfusion-requesturl'] = $request_url; $headers['x-cloudfusion-stringtosign'] = $stringToSign; $data = new $this->response_class($headers, new SimpleXMLElement($request->get_response_body()), $request->get_response_code()); // Return! return $data; } /*%******************************************************************************************%*/ // BROWSE NODE LOOKUP /** * Method: browse_node_lookup() * Given a browse node ID, returns the specified browse node's name, children, and ancestors. The names and browse node IDs of the children and ancestor browse nodes are also returned. enables you to traverse the browse node hierarchy to find a browse node. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * browse_node_id - _integer_ (Required) A positive integer assigned by Amazon that uniquely identifies a product category. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. Allows 'BrowseNodeInfo' (default), 'NewReleases', 'TopSellers'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_browse_node_lookup.php: * example::pas/browse_node_lookup.phpt: * example::pas/browse_node_lookup2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/BrowseNodeLookup.html */ public function browse_node_lookup($browse_node_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['BrowseNodeId'] = $browse_node_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('BrowseNodeLookup', $opt, $locale); } /*%******************************************************************************************%*/ // CART METHODS /** * Method: cart_add() * Enables you to add items to an existing remote shopping cart. can only be used to place a new item in a shopping cart. It cannot be used to increase the quantity of an item already in the cart. If you would like to increase the quantity of an item that is already in the cart, you must use the operation. * * You add an item to a cart by specifying the item's OfferListingId, or ASIN and ListItemId. Once in a cart, an item can only be identified by its CartItemId. That is, an item in a cart cannot be accessed by its ASIN or OfferListingId. CartItemId is returned by , , and . * * To add items to a cart, you must specify the cart using the CartId and HMAC values, which are returned by the operation. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * cart_id - _string_ (Required) Alphanumeric token returned by that identifies a cart. * hmac - _string_ (Required) Encrypted alphanumeric token returned by that authorizes access to a cart. * offer_listing_id - _string|array_ (Required) Either a string containing the Offer ID to add, or an associative array where the Offer ID is the key and the quantity is the value. An offer listing ID is an alphanumeric token that uniquely identifies an item. Use the OfferListingId instead of an item's ASIN to add the item to the cart. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MergeCart - _boolean_ (Optional) A boolean value that when True specifies that the items in a customer's remote shopping cart are added to the customer's Amazon retail shopping cart. This occurs when the customer elects to purchase the items in their remote shopping cart. When the value is False the remote shopping cart contents are not added to the retail shopping cart. Instead, the customer is sent directly to the Order Pipeline when they elect to purchase the items in their cart. This parameter is valid only in the US locale. In all other locales, the parameter is invalid but the request behaves as though the value were set to True. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_cart_add.php: * example::pas/cart_add.phpt: * example::pas/cart_add2.phpt: * example::pas/cart_add3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CartAdd.html */ public function cart_add($cart_id, $hmac, $offer_listing_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['CartId'] = $cart_id; $opt['HMAC'] = $hmac; if (is_array($offer_listing_id)) { $count = 1; foreach ($offer_listing_id as $offer => $quantity) { $opt['Item.' . $count . '.OfferListingId'] = $offer; $opt['Item.' . $count . '.Quantity'] = $quantity; $count++; } } else { $opt['Item.1.OfferListingId'] = $offer_listing_id; $opt['Item.1.Quantity'] = 1; } if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('CartAdd', $opt, $locale); } /** * Method: cart_clear() * Enables you to remove all of the items in a remote shopping cart, including SavedForLater items. To remove only some of the items in a cart or to reduce the quantity of one or more items, use . * * To delete all of the items from a remote shopping cart, you must specify the cart using the CartId and HMAC values, which are returned by the operation. A value similar to the HMAC, URLEncodedHMAC, is also returned. This value is the URL encoded version of the HMAC. This encoding is necessary because some characters, such as + and /, cannot be included in a URL. Rather than encoding the HMAC yourself, use the URLEncodedHMAC value for the HMAC parameter. * * does not work after the customer has used the PurchaseURL to either purchase the items or merge them with the items in their Amazon cart. Carts exist even though they have been emptied. The lifespan of a cart is 7 days since the last time it was acted upon. For example, if a cart created 6 days ago is modified, the cart lifespan is reset to 7 days. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * cart_id - _string_ (Required) Alphanumeric token returned by that identifies a cart. * hmac - _string_ (Required) Encrypted alphanumeric token returned by that authorizes access to a cart. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MergeCart - _boolean_ (Optional) A boolean value that when True specifies that the items in a customer's remote shopping cart are added to the customer's Amazon retail shopping cart. This occurs when the customer elects to purchase the items in their remote shopping cart. When the value is False the remote shopping cart contents are not added to the retail shopping cart. Instead, the customer is sent directly to the Order Pipeline when they elect to purchase the items in their cart. This parameter is valid only in the US locale. In all other locales, the parameter is invalid but the request behaves as though the value were set to True. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_cart_clear.php: * example::pas/cart_clear.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CartClear.html */ public function cart_clear($cart_id, $hmac, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['CartId'] = $cart_id; $opt['HMAC'] = $hmac; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('CartClear', $opt, $locale); } /** * Method: cart_create() * Enables you to create a remote shopping cart. A shopping cart is the metaphor used by most e-commerce solutions. It is a temporary data storage structure that resides on Amazon servers. The structure contains the items a customer wants to buy. In Amazon Associates Web Service, the shopping cart is considered remote because it is hosted by Amazon servers. In this way, the cart is remote to the vendor's web site where the customer views and selects the items they want to purchase. * * Once you add an item to a cart by specifying the item's ListItemId and ASIN, or OfferListing ID, the item is assigned a CartItemId and accessible only by that value. That is, in subsequent requests, an item in a cart cannot be accessed by its ListItemId and ASIN, or OfferListingId. * * Because the contents of a cart can change for different reasons, such as item availability, you should not keep a copy of a cart locally. Instead, use the other cart operations to modify the cart contents. For example, to retrieve contents of the cart, which are represented by CartItemIds, use . * * Available products are added as cart items. Unavailable items, for example, items out of stock, discontinued, or future releases, are added as SaveForLaterItems. No error is generated. The Amazon database changes regularly. You may find a product with an offer listing ID but by the time the item is added to the cart the product is no longer available. The checkout page in the Order Pipeline clearly lists items that are available and those that are SaveForLaterItems. * * It is impossible to create an empty shopping cart. You have to add at least one item to a shopping cart using a single request. You can add specific quantities (up to 999) of each item. can be used only once in the life cycle of a cart. To modify the contents of the cart, use one of the other cart operations. * * Carts cannot be deleted. They expire automatically after being unused for 7 days. The lifespan of a cart restarts, however, every time a cart is modified. In this way, a cart can last for more than 7 days. If, for example, on day 6, the customer modifies a cart, the 7 day countdown starts over. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * offer_listing_id - _string|array_ (Required) Either a string containing the Offer ID to add, or an associative array where the Offer ID is the key and the quantity is the value. An offer listing ID is an alphanumeric token that uniquely identifies an item. Use the OfferListingId instead of an item's ASIN to add the item to the cart. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MergeCart - _boolean_ (Optional) A boolean value that when True specifies that the items in a customer's remote shopping cart are added to the customer's Amazon retail shopping cart. This occurs when the customer elects to purchase the items in their remote shopping cart. When the value is False the remote shopping cart contents are not added to the retail shopping cart. Instead, the customer is sent directly to the Order Pipeline when they elect to purchase the items in their cart. This parameter is valid only in the US locale. In all other locales, the parameter is invalid but the request behaves as though the value were set to True. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_cart_create.php: * example::pas/cart_create.phpt: * example::pas/cart_create2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CartCreate.html */ public function cart_create($offer_listing_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); if (is_array($offer_listing_id)) { $count = 1; foreach ($offer_listing_id as $offer => $quantity) { $opt['Item.' . $count . '.OfferListingId'] = $offer; $opt['Item.' . $count . '.Quantity'] = $quantity; $count++; } } else { $opt['Item.1.OfferListingId'] = $offer_listing_id; $opt['Item.1.Quantity'] = 1; } if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('CartCreate', $opt, $locale); } /** * Method: cart_get() * Enables you to retrieve the IDs, quantities, and prices of all of the items, including SavedForLater items in a remote shopping cart. * * Because the contents of a cart can change for different reasons, such as availability, you should not keep a copy of a cart locally. Instead, use to retrieve the items in a remote shopping cart. To retrieve the items in a cart, you must specify the cart using the CartId and HMAC values, which are returned in the operation. A value similar to HMAC, URLEncodedHMAC, is also returned. * * This value is the URL encoded version of the HMAC. This encoding is necessary because some characters, such as + and /, cannot be included in a URL. Rather than encoding the HMAC yourself, use the URLEncodedHMAC value for the HMAC parameter. * * does not work after the customer has used the PurchaseURL to either purchase the items or merge them with the items in their Amazon cart. * * Access: * public * * Parameters: * cart_id - _string_ (Required) Alphanumeric token returned by that identifies a cart. * hmac - _string_ (Required) Encrypted alphanumeric token returned by that authorizes access to a cart. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * CartItemId - _string_ (Optional) Alphanumeric token that uniquely identifies an item in a cart. Once an item, specified by an ASIN or OfferListingId, has been added to a cart, you must use the CartItemId to refer to it. The other identifiers will not work. * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MergeCart - _boolean_ (Optional) A boolean value that when True specifies that the items in a customer's remote shopping cart are added to the customer's Amazon retail shopping cart. This occurs when the customer elects to purchase the items in their remote shopping cart. When the value is False the remote shopping cart contents are not added to the retail shopping cart. Instead, the customer is sent directly to the Order Pipeline when they elect to purchase the items in their cart. This parameter is valid only in the US locale. In all other locales, the parameter is invalid but the request behaves as though the value were set to True. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_cart_get.php: * example::pas/cart_get.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CartGet.html */ public function cart_get($cart_id, $hmac, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['CartId'] = $cart_id; $opt['HMAC'] = $hmac; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('CartGet', $opt, $locale); } /** * Method: cart_modify() * Enables you to change the quantity of items that are already in a remote shopping cart, move items from the active area of a cart to the SaveForLater area or the reverse, and change the MergeCart setting. * * To modify the number of items in a cart, you must specify the cart using the CartId and HMAC values that are returned in the operation. A value similar to HMAC, URLEncodedHMAC, is also returned. This value is the URL encoded version of the HMAC. This encoding is necessary because some characters, such as + and /, cannot be included in a URL. Rather than encoding the HMAC yourself, use the URLEncodedHMAC value for the HMAC parameter. * * You can use to modify the number of items in a remote shopping cart by setting the value of the Quantity parameter appropriately. You can eliminate an item from a cart by setting the value of the Quantity parameter to zero. Or, you can double the number of a particular item in the cart by doubling its Quantity. You cannot, however, use to add new items to a cart. * * Access: * public * * Parameters: * cart_id - _string_ (Required) Alphanumeric token returned by that identifies a cart. * hmac - _string_ (Required) Encrypted alphanumeric token returned by that authorizes access to a cart. * cart_item_id - _array_ (Required) Associative array that specifies an item to be modified in the cart where N is a positive integer between 1 and 10, inclusive. Up to ten items can be modified at a time. CartItemId is neither an ASIN nor an OfferListingId. It is, instead, an alphanumeric token returned by and . This parameter is used in conjunction with Item.N.Quantity to modify the number of items in a cart. Also, instead of adjusting the quantity, you can set 'SaveForLater' or 'MoveToCart' as actions instead. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * Action - _string_ (Optional) Change cart items to move items to the Saved-For-Later area, or change Saved-For- Later (SaveForLater) items to the active cart area (MoveToCart). * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * ListItemId - _string_ (Optional) The ListItemId parameter is returned by the ListItems response group. The parameter identifies an item on a list, such as a wishlist. To add this item to a cart, you must include in the request the item's ASIN and ListItemId. The ListItemId includes the name and address of the list owner, which the ASIN alone does not. * MergeCart - _boolean_ (Optional) A boolean value that when True specifies that the items in a customer's remote shopping cart are added to the customer's Amazon retail shopping cart. This occurs when the customer elects to purchase the items in their remote shopping cart. When the value is False the remote shopping cart contents are not added to the retail shopping cart. Instead, the customer is sent directly to the Order Pipeline when they elect to purchase the items in their cart. This parameter is valid only in the US locale. In all other locales, the parameter is invalid but the request behaves as though the value were set to True. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_cart_modify.php: * example::pas/cart_modify.phpt: * example::pas/cart_modify2.phpt: * example::pas/cart_modify3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CartModify.html */ public function cart_modify($cart_id, $hmac, $cart_item_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['CartId'] = $cart_id; $opt['HMAC'] = $hmac; if (is_array($cart_item_id)) { $count = 1; foreach ($cart_item_id as $offer => $quantity) { $action = is_numeric($quantity) ? 'Quantity' : 'Action'; $opt['Item.' . $count . '.CartItemId'] = $offer; $opt['Item.' . $count . '.' . $action] = $quantity; $count++; } } else { throw new PAS_Exception('$cart_item_id MUST be an array. See the ' . CLOUDFUSION_NAME . ' documentation for more details.'); } if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('CartModify', $opt, $locale); } /*%******************************************************************************************%*/ // CUSTOMER CONTENT METHODS /** * Method: customer_content_lookup() * For a given customer ID, the operation retrieves all of the information a customer has made public about themselves on Amazon. Such information includes some or all of the following: About Me, Birthday, City, State, Country, Customer Reviews, Customer ID, Name, Nickname, Wedding Registry, or WishList. To find a customer ID, use the operation. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * customer_id - _string_ (Required) An alphanumeric token assigned by Amazon that uniquely identifies a customer. Only one customer_id can be submitted at a time in . * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. Allows 'CustomerInfo' (default), 'CustomerReviews', 'CustomerLists', 'CustomerFull', 'TaggedGuides', 'TaggedItems', 'TaggedListmaniaLists', 'TagsSummary', or 'Tags'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * ReviewPage - _integer_ (Optional) A positive integer that specifies the page of reviews to read. There are ten reviews per page. For example, to read reviews 11 through 20, specify ReviewPage=2. The total number of pages is returned in the TotalPages response tag. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * TagPage - _integer_ (Optional) Specifies the page of results to return. There are ten results on a page. The maximum page number is 400. * TagsPerPage - _integer_ (Optional) The number of tags to return that are associated with a specified item. * TagSort - _string_ (Optional) Specifies the sorting order for the results. Allows 'FirstUsed', 'LastUsed', 'Name', or 'Usages' (default) * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_customer_content_lookup.php: * example::pas/customer_content_lookup.phpt: * example::pas/customer_content_lookup2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CustomerContentLookup.html * Related - , */ public function customer_content_lookup($customer_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['CustomerId'] = $customer_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('CustomerContentLookup', $opt, $locale); } /** * Method: customer_content_search() * For a given customer Email address or name, the operation returns matching customer IDs, names, nicknames, and residence information (city, state, and country). In general, supplying an Email address returns unique results whereas supplying a name more often returns multiple results. This operation is US-only. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * email_name - _string_ (Required) Either the email address or the name of the customer you want to look up the ID for. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * CustomerPage - _integer_ (Optional) A positive integer that specifies the page of customer IDs to return. Up to twenty customer IDs are returned per page. Defaults to 1. * Email - _string_ (Optional) Besides the first parameter, you can set the email address here. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * Name - _string_ (Optional) Besides the first parameter, you can set the name here. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_customer_content_search.php: * example::pas/customer_content_search.phpt: * example::pas/customer_content_search2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CustomerContentSearch.html * Related - , */ public function customer_content_search($email_name, $opt = null) { if (!$opt) $opt = array(); if (strpos($email_name, '@')) { $opt['Email'] = $email_name; } else { $opt['Name'] = $email_name; } if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('CustomerContentSearch', $opt, PAS_LOCALE_US); } /*%******************************************************************************************%*/ // HELP /** * Method: help() * The Help operation provides information about PAS operations and response groups. For operations, Help lists required and optional request parameters, as well as default and optional response groups the operation can use. For response groups, Help lists the operations that can use the response group as well as the response tags returned by the response group in the XML response. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * about - _string_ (Required) Specifies the operation or response group about which you want more information. Allows all PAS operations, all PAS response groups. * help_type - _string_ (Required) Specifies whether the help topic is an operation or response group. HelpType and About values must both be operations or response groups, not a mixture of the two. Allows 'Operation' or 'ResponseGroup'. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. Allows 'Request' or 'Help'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/Help.html */ public function help($about, $help_type, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['About'] = $about; $opt['HelpType'] = $help_type; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('Help', $opt, $locale); } /*%******************************************************************************************%*/ // ITEM METHODS /** * Method: item_lookup() * Given an Item identifier, the ItemLookup operation returns some or all of the item attributes, depending on the response group specified in the request. By default, returns an item’s ASIN, DetailPageURL, Manufacturer, ProductGroup, and Title of the item. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * item_id - _string_ (Required) A positive integer that unique identifies an item. The meaning of the number is specified by IdType. That is, if IdType is ASIN, the ItemId value is an ASIN. If ItemId is an ASIN, a search index cannot be specified in the request. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * Condition - _string_ (Optional) Specifies an item's condition. If Condition is set to "All," a separate set of responses is returned for each valid value of Condition. The default value is "New" (not "All"). So, if your request does not return results, consider setting the value to "All." When the value is "New," the ItemSearch Availability parameter cannot be set to "Available." Amazon only sells items that are "New." Allows 'New', 'Used', 'Collectible', 'Refurbished', and 'All'. Defaults to 'New'. * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * IdType - _string_ (Optional) Type of item identifier used to look up an item. All IdTypes except ASINx require a SearchIndex to be specified. SKU requires a MerchantId to be specified also. Allows 'ASIN', 'SKU', 'UPC', 'EAN', 'ISBN' (US only, when search index is Books), and 'JAN'. UPC is not valid in the Canadian locale. Defaults to 'ASIN'. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * OfferPage - _string_ (Optional) Page of offers returned. There are 10 offers per page. To examine offers 11 trough 20, for example, set OfferPage to 2. Allows 1 through 100. * RelatedItemsPage - _integer_ (Optional) This optional parameter is only valid when the RelatedItems response group is used. Each ItemLookup request can return, at most, ten related items. The RelatedItemsPage value specifies the set of ten related items to return. A value of 2, for example, returns the second set of ten related items. * RelationshipType - _string_ (Optional) This parameter is required when the RelatedItems response group is used. The type of related item returned is specified by the RelationshipType parameter. Sample values include Episode, Season, and Tracks. For a complete list of types, go to the documentation for "Relationship Types". Required when 'RelatedItems' response group is used. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. Check the documentation for all allowed values. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * ReviewPage - _integer_ (Optional) Page of reviews returned. There are 5 reviews per page. To examine reviews 6 through 10, for example, set ReviewPage to 2. Allows 1 through 20. * ReviewSort - _string_ (Optional) Specifies the order in which Reviews are sorted in the return. Allows '-HelpfulVotes', 'HelpfulVotes', '-OverallRating', 'OverallRating', 'SubmissionDate' and '-SubmissionDate'. Defaults to '-SubmissionDate'. * SearchIndex - _string_ (Optional) The product category to search. Constraint: If ItemIds an ASIN, a search index cannot be specified in the request. Required for for non-ASIN ItemIds. Allows any valid search index. See the "Search Indices" documentation page for more details. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * TagPage - _integer_ (Optional) Specifies the page of results to return. There are ten results on a page. Allows 1 through 400. * TagsPerPage - _integer_ (Optional) The number of tags to return that are associated with a specified item. * TagSort - _string_ (Optional) Specifies the sorting order for the results. Allows 'FirstUsed', '-FirstUsed', 'LastUsed', '-LastUsed', 'Name', '-Name', 'Usages', and '-Usages'. Defaults to '-Usages'. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * VariationPage - _string_ (Optional) Page number of variations returned by ItemLookup. By default, ItemLookup returns all variations. Use VariationPage to return a subsection of the response. There are 10 variations per page. To examine offers 11 trough 20, for example, set VariationPage to 2. Allows 1 through 150. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_item_lookup.php: * example::pas/item_lookup.phpt: * example::pas/item_lookup2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/ItemLookup.html * Related - , */ public function item_lookup($item_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['ItemId'] = $item_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('ItemLookup', $opt, $locale); } /** * Method: item_search() * The operation returns items that satisfy the search criteria, including one or more search indices. is the operation that is used most often in requests. In general, when trying to find an item for sale, you use this operation. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * keywords - _string_ (Required) A word or phrase associated with an item. The word or phrase can be in various product fields, including product title, author, artist, description, manufacturer, and so forth. When, for example, the search index equals "MusicTracks", the Keywords parameter enables you to search by song title. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * Actor - _string_ (Optional) Name of an actor associated with the item. You can enter all or part of the name. * Artist - _string_ (Optional) Name of an artist associated with the item. You can enter all or part of the name. * AudienceRating - _string_ (Optional) Movie ratings based on MPAA ratings or age, depending upon the locale. You may specify one or more values in a comma-separated list. * Author - _string_ (Optional) Name of an author associated with the item. You can enter all or part of the name. * Availability - _string_ (Optional) Enables ItemSearch to return only those items that are available. This parameter must be used in combination with a merchant ID and Condition. When Availability is set to "Available," the Condition parameter cannot be set to "New". * Brand - _string_ (Optional) Name of a brand associated with the item. You can enter all or part of the name. * BrowseNode - _integer_ (Optional) Browse nodes are positive integers that identify product categories. * City - _string_ (Optional) Name of a city associated with the item. You can enter all or part of the name. This parameter only works in the US locale. * Composer - _string_ (Optional) Name of an composer associated with the item. You can enter all or part of the name. * Condition - _string_ (Optional) Use the Condition parameter to filter the offers returned in the product list by condition type. By default, Condition equals "New". If you do not get results, consider changing the value to "All. When the Availability parameter is set to "Available," the Condition parameter cannot be set to "New". ItemSearch returns up to ten search results at a time. Allows 'New', 'Used', 'Collectible', 'Refurbished', 'All'. * Conductor - _string_ (Optional) Name of a conductor associated with the item. You can enter all or part of the name. * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * Director - _string_ (Optional) Name of a director associated with the item. You can enter all or part of the name. * ItemPage - _integer_ (Optional) Retrieves a specific page of items from all of the items in a response. Up to ten items are returned on a page unless Condition equals "All." In that case, returns up to three results per Condition, for example, three new, three used, three refurbished, and three collectible items. Or, for example, if there are no collectible or refurbished items being offered, returns three new and three used items. The total number of pages of items found is returned in the TotalPages response tag. Allows 1 through 400. * Keywords - _string_ (Optional) A word or phrase associated with an item. The word or phrase can be in various product fields, including product title, author, artist, description, manufacturer, and so forth. When, for example, the search index equals "MusicTracks," the Keywords parameter enables you to search by song title. * Manufacturer - _string_ (Optional) Name of a manufacturer associated with the item. You can enter all or part of the name. * MaximumPrice - _string_ (Optional) Specifies the maximum price of the items in the response. Prices are in terms of the lowest currency denomination, for example, pennies. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * MinimumPrice - _string_ (Optional) Specifies the minimum price of the items in the response. Prices are in terms of the lowest currency denomination, for example, pennies. * Neighborhood - _string_ (Optional) Name of a neighborhood You can enter all or part of the name. The neighborhoods are located in one of the valid values for City. * Orchestra - _string_ (Optional) Name of an orchestra associated with the item. You can enter all or part of the name. * PostalCode - _string_ (Optional) Postal code of the merchant. In the US, the postal code is the postal code. This parameter enables you to search for items sold in a specified region of a country. * Power - _string_ (Optional) Performs a book search using a complex query string. Only works when the search index is set equal to "Books". * Publisher - _string_ (Optional) Name of a publisher associated with the item. You can enter all or part of the name. * RelatedItemsPage - _integer_ (Optional) This optional parameter is only valid when the RelatedItems response group is used. Each ItemLookup request can return, at most, ten related items. The RelatedItemsPage value specifies the set of ten related items to return. A value of 2, for example, returns the second set of ten related items. * RelationshipType - _string_ (Optional; Required when RelatedItems response group is used) This parameter is required when the RelatedItems response group is used. The type of related item returned is specified by the RelationshipType parameter. Sample values include Episode, Season, and Tracks. A complete list of values follows this table. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * ReviewSort - _string_ (Optional) Sorts reviews based on the value of the parameter. '-HelpfulVotes', 'HelpfulVotes', '-OverallRating', 'OverallRating', 'Rank', '-Rank', '-SubmissionDate', 'SubmissionDate'. * SearchIndex - _string_ (Optional) The product category to search. Many ItemSearch parameters are valid with only specific values of SearchIndex. * Sort - _string_ (Optional) Means by which the items in the response are ordered. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * TagPage - _integer_ (Optional) Specifies the page of results to return. There are ten results on a page. The maximum page number is 400. * TagsPerPage - _integer_ (Optional) The number of tags to return that are associated with a specified item. * TagSort - _string_ (Optional) Specifies the sorting order for the results. Allows 'FirstUsed', '-FirstUsed', 'LastUsed', '-LastUsed', 'Name', '-Name', 'Usages', and '-Usages'. To sort items in descending order, prefix the values with a negative sign (-). * TextStream - _string_ (Optional) A search based on two or more words. Picks out of the block of text up to ten keywords and returns up to ten items that match those keywords. For example, if five keywords are found, two items for each keyword are returned. Only one page of results is returned so ItemPage does not work with TextStream. * Title - _string_ (Optional) The title associated with the item. You can enter all or part of the title. Title searches are a subset of Keyword searches. If a Title search yields insufficient results, consider using a Keywords search. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * VariationPage - _integer_ (Optional) Retrieves a specific page of variations returned by ItemSearch. By default, ItemSearch returns all variations. Use VariationPage to return a subsection of the response. There are 10 variations per page. To examine offers 11 trough 20, for example, set VariationPage to 2. The total number of pages is returned in the TotalPages element. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_item_search.php: * example::pas/item_search.phpt: * example::pas/item_search2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/ItemSearch.html * Related - , */ public function item_search($keywords, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['Keywords'] = $keywords; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } if (!isset($opt['SearchIndex']) || empty($opt['SearchIndex'])) { $opt['SearchIndex'] = 'All'; } return $this->pas_authenticate('ItemSearch', $opt, $locale); } /*%******************************************************************************************%*/ // LIST METHODS /** * Method: list_lookup() * The operation returns, by default, summary information about a list that you specify in the request. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * list_id - _string_ (Required) Number that uniquely identifies a list. * list_type - _string_ (Required) Type of list. Accepts 'WeddingRegistry', 'Listmania', 'WishList'. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * Condition - _string_ (Optional) Specifies an item's condition. If Condition is set to "All", a separate set of responses is returned for each valid value of Condition. Allows 'All', 'Collectible', 'Refurbished', or 'Used'. * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * IsOmitPurchasedItems - _boolean_ (Optional) If you set IsOmitPurchasedItems to TRUE, items on a wishlist that have been purchased will not be returned. Only those items that have not been purchased or those for which the entire quantity has not been purchased are returned. Defaults to FALSE. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ProductGroup - _string_ (Optional) Category of the item, for example, 'Book' or 'DVD'. * ProductPage - _integer_ (Optional) Retrieves a specific page of lists returned. There are ten lists per page. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Sort - _string_ (Optional) Means by which the list items in the response are ordered. Use only with wishlists. Allows 'DateAdded', 'LastUpdated', 'Price', and 'Priority'. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_list_lookup.php: * example::pas/list_lookup.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/ListLookup.html * Related - , */ public function list_lookup($list_id, $list_type, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['ListId'] = isset($list_id) ? $list_id : ''; $opt['ListType'] = isset($list_type) ? $list_type : ''; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('ListLookup', $opt, $locale); } /** * Method: list_search() * Given a customer name or Email address, the operation returns the associated list ID(s) but not the list items. To find those, use the list ID returned by with . * * Specifying a full name or just a first or last name in the request typically returns multiple lists belonging to different people. Using Email as the identifier produces more filtered results. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * email_name - _string_ (Required) Name or email address of the list creator. This parameter is not supported for the BabyRegistry. Set this to null if you want to explicitly pass FirstName and LastName for $opt. * list_type - _string_ (Required) Specifies the kind of list you are retrieving. Allows 'BabyRegistry', 'WeddingRegistry', 'WishList'. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * City - _string_ (Optional) City in which the list creator lives. * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * Email - _string_ (Optional) E-mail address of the list creator. This parameter is not supported for the BabyRegistry. * FirstName - _string_ (Optional) First name of the list creator. Returns all list owners that have FirstName in their first name. For example, specifying 'John', will return first names of 'John', 'Johnny', and 'Johnson'. * LastName - _string_ (Optional) Last name of the list creator. ListSearch returns all list owners that have LastName in their last name. For example, specifying 'Ender', will return the last names of 'Ender', 'Enders', and 'Enderson'. * ListPage - _integer_ (Optional) Retrieve a specific page of list IDs. There are ten list IDs per page. The total number of pages is returned in the TotalPages response tag. The default is to return the first page. Allows 1 through 20. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * State - _string_ (Optional) State in which the list creator lives. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_list_search.php: * example::pas/list_search.phpt: * example::pas/list_search2.phpt: * example::pas/list_search3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/ListSearch.html * Related - , */ public function list_search($email_name, $list_type, $opt = null, $locale = null) { if (!$opt) $opt = array(); if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } if (strpos($email_name, '@')) { $opt['Email'] = $email_name; } else { $opt['Name'] = isset($email_name) ? $email_name : ''; } $opt['ListType'] = $list_type; return $this->pas_authenticate('ListSearch', $opt, $locale); } /*%******************************************************************************************%*/ // SELLER METHODS /** * Method: seller_listing_lookup() * Enables you to return information about a seller's listings, including product descriptions, availability, condition, and quantity available. The response also includes the seller's nickname. Each request requires a seller ID. * * You can also find a seller's items using ItemLookup. There are, however, some reasons why it is better to use : (a) enables you to search by seller ID. (b) returns much more information than . * * This operation only works with sellers who have less than 100,000 items for sale. Sellers that have more items for sale should use, instead of Amazon Associates Web Service, other APIs, including the Amazon Inventory Management System, and the Merchant@ API. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * item_id - _string_ (Optional) Number that uniquely identifies an item. The valid value depends on the value for IdType. Allows an Exchange ID, a Listing ID, an ASIN, or a SKU. * id_type - _string_ (Optional) Use the IdType parameter to specify the value type of the Id parameter value. If you are looking up an Amazon Marketplace item, use Exchange, ASIN, or SKU as the value for IdType. Discontinued, out of stock, or unavailable products will not be returned if IdType is Listing, SKU, or ASIN. Those products will be returned, however, if IdType is Exchange. Allows 'Exchange', 'Listing', 'ASIN', 'SKU'. * seller_id - _string_ (Optional) Alphanumeric token that uniquely identifies a seller. This parameter limits the results to a single seller ID. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_seller_listing_lookup.php: * example::pas/seller_listing_lookup.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/SellerListingLookup.html * Related - , */ public function seller_listing_lookup($item_id, $id_type, $seller_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['Id'] = $item_id; $opt['IdType'] = $id_type; $opt['SellerId'] = $seller_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('SellerListingLookup', $opt, $locale); } /** * Method: seller_listing_search() * Enables you to search for items offered by specific sellers. You cannot use to look up items sold by merchants. To look up an item sold by a merchant, use or along with the MerchantId parameter. * * returns the listing ID or exchange ID of an item. Typically, you use those values with to find out more about those items. * * Each request returns up to ten items. By default, the first ten items are returned. You can use the ListingPage parameter to retrieve additional pages of (up to) ten listings. To use Amazon Associates Web Service, sellers must have less than 100,000 items for sale. Sellers that have more items for sale should use, instead of Amazon Associates Web Service, other seller APIs, including the Amazon Inventory Management System, and the Merchant@ API. * * requires a seller ID, which means that you cannot use this operation to search across all sellers. Amazon Associates Web Service does not have a seller-specific operation that does this. To search across all sellers, use or . * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * seller_id - _string_ (Required) An alphanumeric token that uniquely identifies a seller. These tokens are created by Amazon and distributed to sellers. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * ListingPage - _integer_ (Optional) Page of the response to return. Up to ten lists are returned per page. For customers that have more than ten lists, more than one page of results are returned. By default, the first page is returned. To return another page, specify the page number. Allows 1 through 500. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * OfferStatus - _string_ (Optional) Specifies whether the product is available (Open), or not (Closed.) Closed products are those that are discontinued, out of stock, or unavailable. Defaults to 'Open'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Sort - _string_ (Optional) Use the Sort parameter to specify how your seller listing search results will be ordered. The -bfp (featured listings - default), applies only to the US, UK, and DE locales. Allows '-startdate', 'startdate', '+startdate', '-enddate', 'enddate', '-sku', 'sku', '-quantity', 'quantity', '-price', 'price |+price', '-title', 'title'. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Title - _string_ (Optional) Searches for products based on the product's name. Keywords and Title are mutually exclusive; you can have only one of the two in a request. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_seller_listing_search.php: * example::pas/seller_listing_search.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/SellerListingSearch.html * Related - , */ public function seller_listing_search($seller_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['SellerId'] = $seller_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('SellerListingSearch', $opt, $locale); } /** * Method: seller_lookup() * Returns detailed information about sellers and, in the US locale, merchants. To lookup a seller, you must use their seller ID. The information returned includes the seller's name, average rating by customers, and the first five customer feedback entries. will not, however, return the seller's e-mail or business addresses. * * A seller must enter their information. Sometimes, sellers do not. In that case, cannot return some seller-specific information. * * To look up more than one seller in a single request, insert a comma-delimited list of up to five seller IDs in the SellerId parameter of the REST request. Customers can rate sellers. 5 is the best rating; 0 is the worst. The rating reflects the customer's experience with the seller. The operation, by default, returns review comments by individual customers. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * seller_id - _string_ (Required) An alphanumeric token that uniquely identifies a seller. These tokens are created by Amazon and distributed to sellers. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * FeedbackPage - _string_ (Optional) Specifies the page of reviews to return. Up to five reviews are returned per page. The first page is returned by default. To access additional pages, use this parameter to specify the desired page. The maximum number of pages that can be returned is 10 (50 feedback items). Allows 1 through 10. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_seller_lookup.php: * example::pas/seller_lookup.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/SellerLookup.html * Related - , */ public function seller_lookup($seller_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['SellerId'] = $seller_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('SellerLookup', $opt, $locale); } /*%******************************************************************************************%*/ // VEHICLE METHODS /** * Method: vehicle_part_lookup() * Given a car part, returns the vehicle models and years the part works in. For example, one carburetor might work in the same vehicle model over a five year period. You can page through the parts returned using the parameters, Count and FitmentPage. This operation is US-only. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * make_id - _integer_ (Required) Identifier that uniquely identifies the make of the car. This can be retrieved by using first. * model_id - _integer_ (Required) Identifier that uniquely identifies the model of the car. This can be retrieved by using first. * year - _integer_ (Required) The year of the car the part works in. * item_id - _string_ (Required) The part ID to lookup. This is typically an ASIN, and can be looked up with . * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * BedId - _integer_ (Optional) Identifier that uniquely identifies the bed style of a truck. This parameter does not pertain to cars. * BodyStyleId - _integer_ (Optional) Identifier that uniquely identifies the body style of the car. * BrakesId - _integer_ (Optional) Identifier that uniquely identifies the brake type on a car. * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * DriveTypeId - _integer_ (Optional) Identifier that uniquely identifies the type of drive on the car. A drive type, for example, is four wheel drive. * EngineId - _integer_ (Optional) Identifier that uniquely identifies the type of engine in the car. An engine type would be, for example, the piston displacement, like 409 cu. inches. * FitmentCount - _integer_ (Optional) Specifies the number of Fitments returned per page of results. Fitments are a combination of car characteristics, including make, model, year, and trim. This parameter is only used with the Fitments response group. * FitmentPage - _integer_ (Optional) The page number of the Fitments returned. Use FitmentPage with Count to page through the results. * IdType - _string_ (Optional) Specifies the type of ID. * MakeId - _integer_ (Optional; Required when using the VehiclePartFit response group) Identifier that uniquely identifies the make of the car. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * MfrBodyCodeId - _integer_ (Optional) Identifier that uniquely identifies the manufacturer's car body code. * ModelId - _integer_ (Optional; Required when using the VehiclePartFit response group) Identifier that uniquely identifies the model of the car. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. Allows 'Fitments', 'HasPartCompatibility', and 'VehiclePartFit'. Defaults to 'HasPartCompatibility'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * SpringTypesId - _integer_ (Optional) Identifier that uniquely identifies the type of spring shocks in the car. * SteeringId - _integer_ (Optional) Identifier that uniquely identifies the steering type of the car. A steering type would be power steering. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * TransmissionId - _integer_ (Optional) Identifier that uniquely identifies the transmission type used in the car. * TrimId - _integer_ (Optional) Identifier that uniquely identifies the trim on the car. Trim generally refers to a package of car options (e.g. Volvo GL vs. Volvo DL). Using this parameter helps narrow responses. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * WheelbaseId - _integer_ (Optional) Identifier that uniquely identifies the car's wheelbase. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * Year - _integer_ (Optional; Required when using the VehiclePartFit response group) The year of the vehicle. * * Returns: * object * * Examples: * example::pas/help_vehicle_part_lookup.php: * example::pas/vehicle_part_lookup.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/VehiclePartLookup.html * Related - , */ public function vehicle_part_lookup($make_id, $model_id, $year, $item_id, $opt = null) { if (!$opt) $opt = array(); $opt['MakeId'] = $make_id; $opt['ModelId'] = $model_id; $opt['Year'] = $year; $opt['ItemId'] = $item_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('VehiclePartLookup', $opt, PAS_LOCALE_US); } /** * Method: vehicle_part_search() * Returns the parts that work in the car. For example, a 2008 GMC Yukon has a list of parts that can work in it. The more parameters that you supply in the request, the narrower your results. * * VehicleSearch has additional, optional parameters to narrow the results, for example BrowseNodeId and Brand. You can page through the vehicles returned using the parameters, Count, PartPageDirection, and FromItemId. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * make_id - _integer_ (Required) Identifier that uniquely identifies the make of the car. This can be retrieved by using first. * model_id - _integer_ (Required) Identifier that uniquely identifies the model of the car. This can be retrieved by using first. * year - _integer_ (Required) The year of the car the part works in. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * BedId - _integer_ (Optional) Identifier that uniquely identifies the bed style of a truck. This parameter does not pertain to cars. * BodyStyleId - _integer_ (Optional) Identifier that uniquely identifies the body style of the car. * BrakesId - _integer_ (Optional) Identifier that uniquely identifies the brake type on a car. * Brand - _integer_ (Optional) The brand of the company that made the part. * BrowseNodeId - _integer_ (Optional) Identifier that uniquely identifies the BrowseNode to which the part belongs. * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * Count - _integer_ (Optional) Controls the number of items returned. Use Count with FitmentPage to page through the results. * DriveTypeId - _integer_ (Optional) Identifier that uniquely identifies the type of drive on the car. A drive type, for example, is four wheel drive. * EngineId - _integer_ (Optional) Identifier that uniquely identifies the type of engine in the car. An engine type would be, for example, the piston displacement, like 409 cu. inches. * FromItemId - _integer_ (Optional) An ASIN that identifies where to start or end the next page of returned results. If PartPageDirection is "Next," the ASIN after this one starts the next set of up to 15 returned results. If PartPageDirection is "Previous," the ASIN is one after the previous set of up to fifteen results returned. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * MfrBodyCodeId - _integer_ (Optional) Identifier that uniquely identifies the manufacturer's car body code. * PartPageDirection - _string_ (Optional) Specifies the direction, forward or backward, to go from FromItemId in presenting the next set of (up to) fifteen results. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. Allows 'PartBrowseNodeBinsSummary', 'PartBrandBinsSummary', 'HasPartCompatibility', 'VehiclePartFit', and 'VehicleParts'. Defaults to 'VehicleParts'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * SpringTypesId - _integer_ (Optional) Identifier that uniquely identifies the type of spring shocks in the car. * SteeringId - _integer_ (Optional) Identifier that uniquely identifies the steering type of the car. A steering type would be power steering. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * TransmissionId - _integer_ (Optional) Identifier that uniquely identifies the transmission type used in the car. * TrimId - _integer_ (Optional; Sometimes Required) Identifier that uniquely identifies the trim on the car. Required when using one of the following parameters: 'BedId', 'BodyStyleId', 'BrakesId', 'DriveTypeId', 'EngineId', 'MfrBodyCodeId', 'SpringTypesId', 'SteeringId', 'TransmissionId', 'WheelbaseId'. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * WheelbaseId - _integer_ (Optional) Identifier that uniquely identifies the car's wheelbase. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_vehicle_part_search.php: * example::pas/vehicle_part_search.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/VehiclePartSearch.html * Related - , */ public function vehicle_part_search($make_id, $model_id, $year, $opt = null) { if (!$opt) $opt = array(); $opt['MakeId'] = $make_id; $opt['ModelId'] = $model_id; $opt['Year'] = $year; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('VehiclePartSearch', $opt, PAS_LOCALE_US); } /** * Method: vehicle_search() * Returns all vehicles that match the specified values for year, make, model, and trim. The request can have one or more of those parameters—the more parameters, the narrower the results. Typically, VehicleSearch requests are repeated, first with the year to get the make, then with the year and make to get the model, and then with the year, make, and model, to get the trim. * * The operation can also return all of the vehicle's options, including BedId, BedName, BodyStyleId, BodyStyleName, BrakesId, BrakesName, DriveTypeId, DriveTypeName, EngineId, EngineName, MakeId, and MakeName. (The full list of options follows.) All of these parameters can be used in subsequent requests with the other vehicle operations to narrow results. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MakeId - _integer_ (Optional; Sometimes Required) Identifier that uniquely identifies the make of the car. The make is the car's manufacturer, such as Ford or General Motors. Use with 'Year' to get model. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ModelId - _integer_ (Optional; Sometimes Required) Identifier that uniquely identifies the model of the car. Use with 'Year' and 'MakeId' to get trim. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. Allows 'VehicleYears', 'VehicleMakes', 'VehicleModels', 'VehicleTrims', and 'VehicleOptions'. Defaults to 'VehicleYears'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * TrimId - _integer_ (Optional; Sometimes Required) Identifier that uniquely identifies the trim on the car. Required when when using the 'VehicleOptions' response group. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * Year - _integer_ (Optional; Sometimes Required) The year of the car the part works in. Required only if including 'MakeId' in request or if you are using 'VehicleSearch' to look up a 'MakeId'. * * Returns: * object * * Examples: * example::pas/help_vehicle_search.php: * example::pas/vehicle_search.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/VehicleSearch.html * Related - , */ public function vehicle_search($opt = null) { if (!$opt) $opt = array(); if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('VehicleSearch', $opt, PAS_LOCALE_US); } /*%******************************************************************************************%*/ // OTHER LOOKUP METHODS /** * Method: similarity_lookup() * Returns up to ten products per page that are similar to one or more items specified in the request. This operation is typically used to pique a customer's interest in buying something similar to what they've already ordered. * * If you specify more than one item, returns the intersection of similar items each item would return separately. Alternatively, you can use the SimilarityType parameter to return the union of items that are similar to any of the specified items. A maximum of ten similar items are returned; the operation does not return additional pages of similar items. If there are more than ten similar items, running the same request can result in different answers because the ten that are included in the response are picked randomly. The results are picked randomly only when you specify multiple items and the results include more than ten similar items. * * When you specify multiple items, it is possible for there to be no intersection of similar items. In this case, the operation returns an error. * * Similarity is a measurement of similar items purchased, that is, customers who bought X also bought Y and Z. It is not a measure, for example, of items viewed, that is, customers who viewed X also viewed Y and Z. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * item_id - _string_ (Required) Specifies the item you want to look up. An ItemId is an alphanumeric identifier assigned to an item. You can specify up to ten ItemIds separated by commas. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * Condition - _string_ (Optional) Specifies an item's condition. If Condition is set to "All", a separate set of responses is returned for each valid value of Condition. Allows 'All', 'Collectible', 'Refurbished', or 'Used'. * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MerchantId - _string_ (Optional) Specifies the merchant who is offering the item. MerchantId is an alphanumeric identifier assigned by Amazon to merchants. Make sure to use a Merchant ID and not a Seller ID. Seller IDs are not supported. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * SimilarityType - _string_ (Optional) "Intersection" returns the intersection of items that are similar to all of the ASINs specified. "Random" returns the union of items that are similar to all of the ASINs specified. Only ten items are returned. So, if there are more than ten similar items found, a random selection from the group is returned. For this reason, running the same request multiple times can yield different results. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_similarity_lookup.php: * example::pas/similarity_lookup.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/SimilarityLookup.html * Related - , */ function similarity_lookup($item_id, $opt = null, $locale = null) { if (!$opt) $opt = array(); $opt['ItemId'] = $item_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('SimilarityLookup', $opt, $locale); } /** * Method: tag_lookup() * Returns entities based on specifying one to five tags. A tag is a descriptive word that a customer uses to label entities on Amazon's retail web site. Entities can be items for sale, Listmania lists, guides, and so forth. For example, a customer might tag a given entity with the phrase, "BestCookbook". This operation is US-only. * * In the tag-related response groups, Tags and TagSummary specify the amount of information returned. The other tag-related response groups, TaggedGuides, TaggedItems, and Tagged listmaniaLists, specify the kind of entity tagged. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * tagname - _string_ (Required) Comma separated list of tag names. Up to five tags can be included in a request. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * locale - _string_ (Optional) Which Amazon-supported locale do we use? Defaults to United States. * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * Count - _integer_ (Optional) Number of tagged entities to return per tag. The default is 5; the maximum is 20. * CustomerId - _string_ (Optional) Alphanumeric token that uniquely identifies a customer. This parameter limits the tags returned to those provided by a single customer. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * TagPage - _integer_ (Optional) Specifies the page of results to return. There are twenty results on a page. * TagSort - _string_ (Optional) Specifies the sorting order for the results. Allows 'FirstUsed', '-FirstUsed', 'LastUsed', '-LastUsed', 'Name', '-Name', 'Usages', and '-Usages'. To sort items in descending order, prefix the previous values with a negative sign (-). * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_tag_lookup.php: * example::pas/tag_lookup.phpt: * example::pas/tag_lookup2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/TagLookup.html * Related - , */ function tag_lookup($tagname, $opt = null) { if (!$opt) $opt = array(); $opt['TagName'] = $tagname; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('TagLookup', $opt, PAS_LOCALE_US); } /** * Method: transaction_lookup() * Returns information about up to ten purchases that have already taken place. Transaction IDs are created whenever a purchase request is made by a customer. This operation is US-only. * * If you added your Associates ID to the config.inc.php file, or you passed it into the AmazonPAS() constructor, it will be passed along in this request automatically. * * Access: * public * * Parameters: * transaction_id - _string_ (Required) A number that uniquely identifies a transaction. The retail web site calls this number the Order number. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * THIS IS AN INCOMPLETE LIST. For the latest information, check the AWS documentation page (noted below), or run the method (noted in the examples below). * * ContentType - _string_ (Optional) Specifies the format of the content in the response. Generally, ContentType should only be changed for REST requests when the Style parameter is set to an XSLT stylesheet. For example, to transform your Amazon Associates Web Service response into HTML, set ContentType to text/html. Allows 'text/xml' and 'text/html'. Defaults to 'text/xml'. * MerchantId - _string_ (Optional) An alphanumeric token distributed by Amazon that uniquely identifies a merchant. Allows 'All', 'Amazon', 'FeaturedBuyBoxMerchant', or a specific Merchant ID. Defaults to 'Amazon'. * ResponseGroup - _string_ (Optional) Specifies the types of values to return. You can specify multiple response groups in one request by separating them with commas. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * Style - _string_ (Optional) Controls the format of the data returned in Amazon Associates Web Service responses. Set this parameter to "XML," the default, to generate a pure XML response. Set this parameter to the URL of an XSLT stylesheet to have Amazon Associates Web Service transform the XML response. See ContentType. * Validate - _boolean_ (Optional) Prevents an operation from executing. Set the Validate parameter to True to test your request without actually executing it. When present, Validate must equal True; the default value is False. If a request is not actually executed (Validate=True), only a subset of the errors for a request may be returned because some errors (for example, no_exact_matches) are only generated during the execution of a request. Defaults to FALSE. * XMLEscaping - _string_ (Optional) Specifies whether responses are XML-encoded in a single pass or a double pass. By default, XMLEscaping is Single, and Amazon Associates Web Service responses are encoded only once in XML. For example, if the response data includes an ampersand character (&), the character is returned in its regular XML encoding (&). If XMLEscaping is Double, the same ampersand character is XML-encoded twice (&). The Double value for XMLEscaping is useful in some clients, such as PHP, that do not decode text within XML elements. Defaults to 'Single'. * * Returns: * object * * Examples: * example::pas/help_transaction_lookup.php: * example::pas/transaction_lookup.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/TransactionLookup.html * Related - , */ function transaction_lookup($transaction_id, $opt = null) { if (!$opt) $opt = array(); $opt['TransactionId'] = $transaction_id; if (isset($this->assoc_id)) { $opt['AssociateTag'] = $this->assoc_id; } return $this->pas_authenticate('TransactionLookup', $opt, PAS_LOCALE_US); } } cloudfusion-2.5.0/s3.class.php0000755000000000000000000020313611337016604014721 0ustar rootroot constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * * Returns: * _boolean_ false if no valid values are set, otherwise true. */ public function __construct($key = null, $secret_key = null) { $this->vhost = null; $this->api_version = '2006-03-01'; $this->hostname = S3_DEFAULT_URL; $this->base_acp_xml = ''; $this->base_logging_xml = ''; if (!$key && !defined('AWS_KEY')) { throw new S3_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.'); } if (!$secret_key && !defined('AWS_SECRET_KEY')) { throw new S3_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.'); } return parent::__construct($key, $secret_key); } /*%******************************************************************************************%*/ // AUTHENTICATION /** * Method: authenticate() * Authenticates a connection to S3. This should not be used directly unless you're writing custom methods for this class. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * opt - _array_ (Optional) Associative array of parameters for authenticating. See the individual methods for allowed keys. * location - _string_ (Do Not Use) Used internally by this function on occasions when S3 returns a redirect code and it needs to call itself recursively. * redirects - _integer_ (Do Not Use) Used internally by this function on occasions when S3 returns a redirect code and it needs to call itself recursively. * * Returns: * object * * See Also: * http://docs.amazonwebservices.com/AmazonS3/latest/RESTAuthentication.html */ public function authenticate($bucket, $opt = null, $location = null, $redirects = 0) { // If nothing was passed in, don't do anything. if (!$opt) { return false; } else { // Set default values $bucket = strtolower($bucket); $acl = null; $body = null; $contentType = 'application/x-www-form-urlencoded'; $delimiter = null; $filename = null; $headers = null; $marker = null; $maxKeys = null; $method = null; $prefix = null; $verb = null; $lastmodified = null; $etag = null; $qsa = null; $md5 = null; $metadataDirective = null; $meta = null; $hmeta = null; $range = null; $returnCurlHandle = null; // Break the array into individual variables, while storing the original. $_opt = $opt; extract($opt); $filename = rawurlencode($filename); // Set hostname if ($this->vhost) { $hostname = $this->vhost; } elseif ($method == 'list_buckets') { $hostname = $this->hostname; } else { $hostname = $bucket . '.' . $this->hostname; } // Get the UTC timestamp in RFC 2616 format $since_epoch = time() + $this->adjust_offset; $httpDate = gmdate(DATE_FORMAT_RFC2616, $since_epoch); // Generate the request string $request = ''; // Append additional parameters $request .= '/' . $filename; // List Object settings if ($method == 'list_objects') { $request = ''; if (isset($prefix) && !empty($prefix)) { $request .= '&prefix=' . $prefix; } if (isset($marker) && !empty($marker)) { $request .= '&marker=' . $marker; } if (isset($maxKeys) && !empty($maxKeys)) { $request .= '&max-keys=' . $maxKeys; } if (isset($delimiter) && !empty($delimiter)) { $request .= '&delimiter=' . $delimiter; } $request = '/?' . ltrim($request, '&'); } // Logging elseif ($method == 'get_logs' || $method == 'enable_logging' || $method == 'disable_logging') { $request .= '?logging'; $filename .= '?logging'; } // Get Bucket Locale settings elseif ($method == 'get_bucket_locale') { $request = '/?location'; $filename = '?location'; } // Add ACL stuff if we're getting/setting ACL preferences. elseif ($method == 'get_bucket_acl' || $method == 'get_object_acl' || $method == 'set_bucket_acl' || $method == 'set_object_acl') { $request .= '?acl'; $filename .= '?acl'; } elseif ($method == 'get_object_url') { $filename = rawurldecode($filename); } if (!$request == '/') { $request = '/' . $request; } // Prepare the request. if ($location) { $this->request_url = $location; } else { $scheme = ($this->enable_ssl) ? 'https://' : 'http://'; $this->request_url = $scheme . $hostname . $request; } // Instantiate the request class $req = new $this->request_class($this->request_url, $this->set_proxy); // Do we have a verb? if (isset($verb) && !empty($verb)) { $req->set_method($verb); } // Do we have a contentType? if (isset($contentType) && !empty($contentType)) { $req->add_header('Content-Type', $contentType); } // Do we have a date? if (isset($httpDate) && !empty($httpDate)) { $req->add_header("Date", $httpDate); } // Do we have ACL settings? (Optional in signed string) if (isset($acl) && !empty($acl)) { $req->add_header("x-amz-acl", $acl); $acl = 'x-amz-acl:' . $acl . "\n"; } // Do we have COPY settings? if ($method == 'copy_object' || $method == 'update_object') { // Copy data $acl .= 'x-amz-copy-source:/' . $sourceBucket . '/' . $sourceObject . "\n"; $req->add_header('x-amz-copy-source', '/' . $sourceBucket . '/' . $sourceObject); // Add any standard HTTP headers. if ($headers) { uksort($headers, 'strnatcasecmp'); foreach ($headers as $k => $v) { $req->add_header($k, $v); } } // Add any meta headers. if ($meta) { uksort($meta, 'strnatcasecmp'); foreach ($meta as $k => $v) { // Strip line breaks. $v = str_replace(array("\r", "\n", '%0A'), '', $v); $req->add_header('x-amz-meta-' . strtolower($k), $v); $acl .= 'x-amz-meta-' . strtolower($k) . ':' . $v . "\n"; } } // Metadata directive $acl .= 'x-amz-metadata-directive:' . $metadataDirective . "\n"; $req->add_header('x-amz-metadata-directive', $metadataDirective); } // Set DevPay tokens if we have them. if ($this->devpay_tokens) { $request->add_header('x-amz-security-token', $this->devpay_tokens); } // Are we checking for changes? if ($lastmodified && $etag) { $req->add_header('If-Modified-Since', $lastmodified); $req->add_header('If-None-Match', $etag); } // Partial content range if ($range) { $req->add_header('Range', 'bytes=' . $range); } // Add a body if we're creating or setting if ($method == 'create_object' || $method == 'create_bucket' || $method == 'enable_logging' || $method == 'disable_logging' || $method == 'set_object_acl' || $method == 'set_bucket_acl') { if (isset($body) && !empty($body)) { $req->set_body($body); $md5 = $this->util->hex_to_base64(md5($body)); $req->add_header('Content-MD5', $md5); } // Add any standard HTTP headers. if ($headers) { uksort($headers, 'strnatcasecmp'); foreach ($headers as $k => $v) { $req->add_header($k, $v); } } // Add any meta headers. if ($meta) { uksort($meta, 'strnatcasecmp'); foreach ($meta as $k => $v) { // Strip line breaks. $v = str_replace(array("\r", "\n", '%0A'), '', $v); $req->add_header('x-amz-meta-' . strtolower($k), $v); $hmeta .= 'x-amz-meta-' . strtolower($k) . ':' . $v . "\n"; } } } // Data that will be "signed". $filename = '/' . $filename; // If we're listing buckets, there is no filename value. if ($method == 'list_buckets') { $filename = ''; } if ($qsa) { // Prepare the string to sign $stringToSign = "$verb\n\n\n$since_epoch\n$acl$hmeta/$bucket$filename"; } else { // Prepare the string to sign $stringToSign = "$verb\n$md5\n$contentType\n$httpDate\n$acl$hmeta/$bucket$filename"; } // Hash the AWS secret key and generate a signature for the request. $signature = $this->util->hex_to_base64(hash_hmac('sha1', $stringToSign, $this->secret_key)); // Pass the developer key and signature $req->add_header("Authorization", "AWS " . $this->key . ":" . $signature); // If we have a "true" value for returnCurlHandle, do that instead of completing the request. if ($returnCurlHandle) { return $req->prep_request(); } // Are we getting a Query String Auth? if ($qsa) { return array( 'bucket' => $bucket, 'filename' => $filename, 'key' => $this->key, 'expires' => $since_epoch, 'signature' => $signature, ); } // Send! $req->send_request(); // Prepare the response. $headers = $req->get_response_header(); $headers['x-cloudfusion-redirects'] = $redirects; $headers['x-cloudfusion-requesturl'] = $this->request_url; $headers['x-cloudfusion-stringtosign'] = $stringToSign; $headers['x-cloudfusion-requestheaders'] = $req->request_headers; if (strpos($req->get_response_body(), 'response_class($headers, new SimpleXMLElement($req->get_response_body()), $req->get_response_code()); } else { $data = new $this->response_class($headers, $req->get_response_body(), $req->get_response_code()); } // Did Amazon tell us to redirect? Typically happens for multiple rapid requests EU datacenters. // @see http://docs.amazonwebservices.com/AmazonS3/latest/Redirects.html if ((int) $req->get_response_code() == 307) // Temporary redirect to new endpoint. { $redirects++; $data = $this->authenticate($bucket, $_opt, $headers['location'], $redirects); } // Return! return $data; } } /** * Method: set_vhost() * Use this virtual host instead of the normal bucket.s3.amazonaws.com domain. * * Access: * public * * Parameters: * vhost - _string_ (Required) The hostname to use instead of bucket.s3.amazonaws.com. * * Returns: * void * * See Also: * Virtual Hosting of Buckets - http://docs.amazonwebservices.com/AmazonS3/latest/VirtualHosting.html */ public function set_vhost($vhost) { $this->vhost = $vhost; } /*%******************************************************************************************%*/ // BUCKET METHODS /** * Method: create_bucket() * The bucket holds all of your objects, and provides a globally unique namespace in which you can manage the keys that identify objects. A bucket can hold any number of objects. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * locale - _string_ (Optional) Sets the preferred geographical location for the bucket. Accepts S3_LOCATION_US or S3_LOCATION_EU. Defaults to S3_LOCATION_US. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTBucketPUT.html * Using Buckets - http://docs.amazonwebservices.com/AmazonS3/latest/UsingBucket.html * Related - , , */ public function create_bucket($bucket, $locale = null, $returnCurlHandle = null) { // Defaults $body = null; $contentType = null; if ($locale) { switch(strtolower($locale)) { case 'eu': $body = '' . strtoupper($locale) . ''; $contentType = 'application/xml'; break; default: $body = 'US'; $contentType = 'application/xml'; break; } } else { $body = 'US'; $contentType = 'application/xml'; } // Authenticate to S3 return $this->authenticate($bucket, array( 'verb' => HTTP_PUT, 'method' => 'create_bucket', 'body' => $body, 'contentType' => $contentType, 'returnCurlHandle' => $returnCurlHandle )); } /** * Method: get_bucket() * Referred to as "GET Bucket" in the AWS docs, but implemented here as AmazonS3::list_objects(). Therefore, this is an alias of list_objects(). * * See Also: * Related - , , , */ public function get_bucket($bucket, $opt = null) { if (!$opt) $opt = array(); return $this->list_objects($bucket, $opt); } /** * Method: get_bucket_locale() * Lists the location constraint of the bucket. U.S.-based buckets have no response. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTBucketLocationGET.html */ public function get_bucket_locale($bucket, $returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_GET; $opt['method'] = 'get_bucket_locale'; $opt['returnCurlHandle'] = $returnCurlHandle; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: head_bucket() * Reads only the HTTP headers of a bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectHEAD.html * Related - , , */ public function head_bucket($bucket, $returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_HEAD; $opt['method'] = 'head_bucket'; $opt['returnCurlHandle'] = $returnCurlHandle; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: if_bucket_exists() * Checks whether this bucket already exists in your account or not. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * * Returns: * _boolean_ Whether the bucket exists or not. */ public function if_bucket_exists($bucket) { $header = $this->head_bucket($bucket); return $header->isOK(); } /** * Method: delete_bucket() * Deletes a bucket from your account. All objects in the bucket must be deleted before the bucket itself can be deleted. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * force - _boolean_ (Optional) Whether to force-delete the bucket and all of its contents. Defaults to false. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object if normal bucket deletion or if forced bucket deletion was successful, a boolean false if the forced deletion was unsuccessful. * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTBucketDELETE.html * Related - , , */ public function delete_bucket($bucket, $force = false, $returnCurlHandle = null) { // Set default value $success = true; if ($force) { // Delete all of the items from the bucket. $success = $this->delete_all_objects($bucket); } // As long as we were successful... if ($success) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_DELETE; $opt['method'] = 'delete_bucket'; $opt['returnCurlHandle'] = $returnCurlHandle; // Authenticate to S3 return $this->authenticate($bucket, $opt); } return false; } /** * Method: copy_bucket() * Copies the contents of a bucket into a new bucket. * * Access: * public * * Parameters: * source_bucket - _string_ (Required) The name of the source bucket. * dest_bucket - _string_ (Required) The name of the destination bucket. * acl - _string_ (Optional) One of the following options: , , , or . Defaults to . * * Returns: * object * * See Also: * Related - , , */ public function copy_bucket($source_bucket, $dest_bucket, $acl = S3_ACL_PRIVATE) { // Since S3 can't yet copy across geographical locations, make sure that the new bucket matches the existing bucket. $locale = $this->get_bucket_locale($source_bucket); switch ($locale->body) { case S3_LOCATION_EU: $locale = S3_LOCATION_EU; break; default: $locale = S3_LOCATION_US; break; } $dest = $this->create_bucket($dest_bucket, $locale); if ($dest->isOK()) { $list = $this->get_object_list($source_bucket); $handles = array(); foreach ($list as $item) { $handles[] = $this->copy_object($source_bucket, $item, $dest_bucket, $item, array( 'acl' => $acl, 'returnCurlHandle' => true )); } $request = new $this->request_class(null); return $request->send_multi_request($handles); } return false; } /** * Method: rename_bucket() * Renames a bucket by making a copy and deleting the original. * * Access: * public * * Parameters: * source_bucket - _string_ (Required) The name of the source bucket. * dest_bucket - _string_ (Required) The name of the destination bucket. * * Returns: * object * * See Also: * Related - , , */ public function rename_bucket($source_bucket, $dest_bucket) { $responses['copy'] = $this->copy_bucket($source_bucket, $dest_bucket); $responses['delete'] = $this->delete_bucket($source_bucket, true); return $responses; } /** * Method: get_bucket_size() * Gets the number of files in the bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * * Returns: * _integer_ The number of files in the bucket. * * See Also: * Related - */ public function get_bucket_size($bucket) { return count($this->get_object_list($bucket)); } /** * Method: get_bucket_filesize() * Gets the file size of the contents of the bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * friendly_format - _boolean_ (Optional) Whether to format the value to 2 decimal points using the largest possible unit (i.e. 3.42 GB). * * Returns: * _integer_|_string_ The number of bytes as an integer, or the friendly format as a string. * * See Also: * Related - , */ public function get_bucket_filesize($bucket, $friendly_format = false) { $filesize = 0; $list = $this->list_objects($bucket); foreach ($list->body->Contents as $filename) { $filesize += (int) $filename->Size; } if ($friendly_format) { $filesize = $this->util->size_readable($filesize); } return $filesize; } /** * Method: list_buckets() * Gets a list of all of the buckets on the S3 account. * * Access: * public * * Parameters: * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTServiceGET.html * Related - */ public function list_buckets($returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_GET; $opt['method'] = 'list_buckets'; $opt['returnCurlHandle'] = $returnCurlHandle; // Authenticate to S3 return $this->authenticate('', $opt); } /** * Method: get_bucket_list() * ONLY lists the bucket names, as an array, on the S3 account. * * Access: * public * * Parameters: * pcre - _string_ (Optional) A Perl-Compatible Regular Expression (PCRE) to filter the names against. * * Returns: * _array_ The list of matching bucket names. * * See Also: * Related - */ public function get_bucket_list($pcre = null) { // Set some default values $bucketnames = array(); // Get a list of buckets. $list = $this->list_buckets(); // If we have a PCRE regex, store it. if ($pcre) { // Loop through and find the bucket names. foreach ($list->body->Buckets->Bucket as $bucket) { $bucket = (string) $bucket->Name; if (preg_match($pcre, $bucket)) { $bucketnames[] = $bucket; } } } else { // Loop through and find the bucket names. foreach ($list->body->Buckets->Bucket as $bucket) { $bucketnames[] = (string) $bucket->Name; } } return (count($bucketnames) > 0) ? $bucketnames : null; } /** * Method: get_bucket_acl() * Gets the ACL settings for a bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html * Related - , , */ public function get_bucket_acl($bucket, $returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_GET; $opt['method'] = 'get_bucket_acl'; $opt['returnCurlHandle'] = $returnCurlHandle; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: set_bucket_acl() * Sets the ACL settings for a bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * acl - _string_ (Optional) One of the following options: , , , or . Alternatively, an array of associative arrays. Each associative array contains an 'id' and a 'permission'. Defaults to . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html * Related - , , */ public function set_bucket_acl($bucket, $acl = S3_ACL_PRIVATE, $returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_PUT; $opt['method'] = 'set_bucket_acl'; $opt['returnCurlHandle'] = $returnCurlHandle; // Make sure these are defined. if (!defined('AWS_CANONICAL_ID') || !defined('AWS_CANONICAL_NAME')) { // Fetch the data live. $canonical = $this->get_canonical_user_id(); define('AWS_CANONICAL_ID', $canonical['id']); define('AWS_CANONICAL_NAME', $canonical['display_name']); // Issue a notice. trigger_error('One or both of the configuration settings AWS_CANONICAL_ID and AWS_CANONICAL_NAME have NOT been set in config.inc.php. ' . CLOUDFUSION_NAME . ' must make additional requests to fetch the data, resulting in slower performance for ' . __FUNCTION__ . '(). For best performance, be sure to define these values in your config.inc.php file. For more details, see http://tarzan-aws.googlecode.com/svn/tags/' . CLOUDFUSION_VERSION . '/config-sample.inc.php', E_USER_NOTICE); } if (is_array($acl)) { $opt['body'] = $this->generate_access_policy(AWS_CANONICAL_ID, AWS_CANONICAL_NAME, $acl); } else { $opt['acl'] = $acl; } // Authenticate to S3 return $this->authenticate($bucket, $opt); } /*%******************************************************************************************%*/ // OBJECT METHODS /** * Method: create_object() * Once you have a bucket, you can start storing objects in it. Objects are stored using the HTTP PUT method. Each object can hold up to 5 GB of data. When you store an object, S3 streams the data to multiple storage servers in multiple data centers to ensure that the data remains available in the event of internal network or hardware failure. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * filename - _string_ (Required) The filename for the object. * body - _string_ (Required) The data to be stored in the object. * contentType - _string_ (Required) The type of content that is being sent in the body. * acl - _string_ (Optional) One of the following options: , , , or . Defaults to . * headers - _array_ (Optional) Standard HTTP headers to send along in the request. * meta - _array_ (Optional) Associative array of key-value pairs. Represented by x-amz-meta-: Any header starting with this prefix is considered user metadata. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectPUT.html * ACL Policy - http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html * Related - , , */ public function create_object($bucket, $opt = null) { if (!$opt) $opt = array(); // Add this to our request $opt['verb'] = HTTP_PUT; $opt['method'] = 'create_object'; $opt['filename'] = $opt['filename']; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: get_object() * Reads the contents of an object within a bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * lastmodified - _string_ (Optional) The LastModified header passed in from a previous request. If used, requires 'etag' as well. Will return a 304 if file hasn't changed. * etag - _string_ (Optional) The ETag header passed in from a previous request. If used, requires 'lastmodified' as well. Will return a 304 if file hasn't changed. * range - _string_ (Optional) A range of bytes to fetch from the file. Useful for downloading partial bits or completing incomplete files. Range notated with a hyphen (e.g. 0-10485759). Defaults to the complete file. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectGET.html * Related - , , */ public function get_object($bucket, $filename, $opt = null) { if (!$opt) $opt = array(); // Add this to our request $opt['verb'] = HTTP_GET; $opt['method'] = 'get_object'; $opt['filename'] = $filename; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: head_object() * Reads only the HTTP headers of an object within a bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectHEAD.html * Related - , , , */ public function head_object($bucket, $filename, $returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_HEAD; $opt['method'] = 'head_object'; $opt['filename'] = $filename; $opt['returnCurlHandle'] = $returnCurlHandle; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: if_object_exists() * Checks whether this object already exists in this bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * * Returns: * _boolean_ Whether the object exists or not. * * See Also: * Related - */ public function if_object_exists($bucket, $filename) { $header = $this->head_object($bucket, $filename); return $header->isOK(); } /** * Method: delete_object() * Deletes an object from within a bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectDELETE.html * Related - , , , */ public function delete_object($bucket, $filename, $returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_DELETE; $opt['method'] = 'delete_object'; $opt['filename'] = $filename; $opt['returnCurlHandle'] = $returnCurlHandle; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: delete_all_objects() * Delete all of the objects inside the specified bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * pcre - _string_ (Optional) A Perl-Compatible Regular Expression (PCRE) to filter the names against. Defaults to . * * Returns: * _boolean_ Determines the success of deleting all files. * * See Also: * Related - */ public function delete_all_objects($bucket, $pcre = S3_PCRE_ALL) { // Collect all matches $list = $this->get_object_list($bucket, array('pcre' => $pcre)); // As long as we have at least one match... if (count($list) > 0) { // Hold CURL handles $handles = array(); // Go through all of the items and delete them. foreach ($list as $item) { $handles[] = $this->delete_object($bucket, $item, true); } $request = new $this->request_class(null); return $request->send_multi_request($handles); } return false; } /** * Method: list_objects() * Lists the objects in a bucket. Provided as the 'GetBucket' action in Amazon's REST API. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * prefix - _string_ (Optional) Restricts the response to only contain results that begin with the specified prefix. * marker - _string_ (Optional) It restricts the response to only contain results that occur alphabetically after the value of marker. * maxKeys - _string_ (Optional) Limits the number of results returned in response to your query. Will return no more than this number of results, but possibly less. * delimiter - _string_ (Optional) Unicode string parameter. Keys that contain the same string between the prefix and the first occurrence of the delimiter will be rolled up into a single result element in the CommonPrefixes collection. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTBucketGET.html * List Keys - http://docs.amazonwebservices.com/AmazonS3/latest/ListingKeysRequest.html * Related - , */ public function list_objects($bucket, $opt = null) { if (!$opt) $opt = array(); // Add this to our request $opt['verb'] = HTTP_GET; $opt['method'] = 'list_objects'; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: get_object_filesize() * Gets the file size of the object. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * friendly_format - _boolean_ (Optional) Whether to format the value to 2 decimal points using the largest possible unit (i.e. 3.42 GB). * * Returns: * _integer_|_string_ The number of bytes as an integer, or the friendly format as a string. * * See Also: * Related - */ public function get_object_filesize($bucket, $filename, $friendly_format = false) { $object = $this->head_object($bucket, $filename); $filesize = (integer) $object->header['content-length']; if ($friendly_format) { $filesize = $this->util->size_readable($filesize); } return $filesize; } /** * Method: get_object_list() * ONLY lists the object filenames from a bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * prefix - _string_ (Optional) Restricts the response to only contain results that begin with the specified prefix. * marker - _string_ (Optional) It restricts the response to only contain results that occur alphabetically after the value of marker. * maxKeys - _string_ (Optional) Limits the number of results returned in response to your query. Will return no more than this number of results, but possibly less. * delimiter - _string_ (Optional) Unicode string parameter. Keys that contain the same string between the prefix and the first occurrence of the delimiter will be rolled up into a single result element in the CommonPrefixes collection. * pcre - _string_ (Optional) A Perl-Compatible Regular Expression (PCRE) to filter the names against. This is applied AFTER any native S3 filtering from 'prefix', 'marker', 'maxKeys', or 'delimiter'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * _array_ The list of matching object names. * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/ListingKeysRequest.html * List Keys - http://docs.amazonwebservices.com/AmazonS3/latest/gsg/ListKeys.html * Related - , */ public function get_object_list($bucket, $opt = null) { // Set some default values $filenames = array(); $pcre = null; // Get a list of files. $list = $this->list_objects($bucket, $opt); // Extract the options if ($opt) { extract($opt); } // If we have a PCRE regex, store it. if ($pcre) { if (isset($list)) { // Loop through and find the filenames. foreach ($list->body->Contents as $file) { $file = (string) $file->Key; if (preg_match($pcre, $file)) { $filenames[] = $file; } } } } else { if (isset($list)) { // Loop through and find the filenames. foreach ($list->body->Contents as $file) { $filenames[] = (string) $file->Key; } } } return (count($filenames) > 0) ? $filenames : null; } /** * Method: copy_object() * Copies an object to a new location, whether in the same locale/bucket or otherwise. * * Access: * public * * Parameters: * source_bucket - _string_ (Required) The name of the bucket that contains the source file. * source_filename - _string_ (Required) The source filename that you want to copy. * dest_bucket - _string_ (Required) The name of the bucket that you want to copy the file to. * dest_filename - _string_ (Required) The filename that you want to give to the copy. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * acl - _string_ (Optional) One of the following options: , , , or . Defaults to . * headers - _array_ (Optional) Standard HTTP headers to send along in the request. * meta - _array_ (Optional) Associative array of key-value pairs. Represented by x-amz-meta-: Any header starting with this prefix is considered user metadata. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB. * metadataDirective - _string_ (Optional) Accepts either COPY or REPLACE. You will likely never need to use this, as it manages itself with no issues. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectCOPY.html * Using and Copying Objects - http://docs.amazonwebservices.com/AmazonS3/latest/UsingCopyingObjects.html * PUT Request Headers - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectPUT.html#RESTObjectPUTRequestHeaders * Related - , , , */ public function copy_object($source_bucket, $source_filename, $dest_bucket, $dest_filename, $opt = null) { if (!$opt) $opt = array(); // Add this to our request $opt['verb'] = HTTP_PUT; $opt['method'] = 'copy_object'; $opt['sourceBucket'] = $source_bucket; $opt['sourceObject'] = $source_filename; $opt['destinationBucket'] = $dest_bucket; $opt['destinationObject'] = $dest_filename; $opt['filename'] = $dest_filename; $opt['metadataDirective'] = isset($opt['metadataDirective']) ? $opt['metadataDirective'] : 'COPY'; // Do we have metadata? if (isset($opt['meta']) && is_array($opt['meta'])) { $opt['metadataDirective'] = 'REPLACE'; } // Authenticate to S3 return $this->authenticate($dest_bucket, $opt); } /** * Method: update_object() * Updates an existing object with new content or settings. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket that contains the source file. * filename - _string_ (Required) The source filename that you want to update. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * acl - _string_ (Optional) One of the following options: , , , or . Defaults to . * headers - _array_ (Optional) Standard HTTP headers to send along in the request. * meta - _array_ (Optional) Associative array of key-value pairs. Represented by x-amz-meta-: Any header starting with this prefix is considered user metadata. It will be stored with the object and returned when you retrieve the object. The total size of the HTTP request, not including the body, must be less than 4 KB. * metadataDirective - _string_ (Optional) Accepts either COPY or REPLACE. You will likely never need to use this, as it manages itself with no issues. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectCOPY.html * Using and Copying Objects - http://docs.amazonwebservices.com/AmazonS3/latest/UsingCopyingObjects.html * PUT Request Headers - http://docs.amazonwebservices.com/AmazonS3/latest/RESTObjectPUT.html#RESTObjectPUTRequestHeaders * Related - , , , */ public function update_object($bucket, $filename, $opt) { if (!$opt) $opt = array(); // Add this to our request $opt['verb'] = HTTP_PUT; $opt['method'] = 'update_object'; $opt['sourceBucket'] = $bucket; $opt['sourceObject'] = $filename; $opt['destinationBucket'] = $bucket; $opt['destinationObject'] = $filename; $opt['filename'] = $filename; $opt['metadataDirective'] = 'REPLACE'; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: duplicate_object() * Identical to , except that it only copies within a single bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket that contains the file. * source_filename - _string_ (Required) The source filename that you want to copy. * dest_filename - _string_ (Required) The filename that you want to give to the copy. * acl - _string_ (Optional) One of the following options: , , , or . Defaults to . * * Returns: * object * * See Also: * Related - , , */ public function duplicate_object($bucket, $source_filename, $dest_filename, $acl = S3_ACL_PRIVATE) { return $this->copy_object($bucket, $source_filename, $bucket, $dest_filename, array('acl' => $acl)); } /** * Method: move_object() * Moves an object to a new location, whether in the same locale/bucket or otherwise. * * Access: * public * * Parameters: * source_bucket - _string_ (Required) The name of the bucket that contains the source file. * source_filename - _string_ (Required) The source filename that you want to copy. * dest_bucket - _string_ (Required) The name of the bucket that you want to copy the file to. * dest_filename - _string_ (Required) The filename that you want to give to the copy. * acl - _string_ (Optional) One of the following options: , , , or . Defaults to . * * Returns: * _array_ objects for the copy and the delete. * * See Also: * Related - , , */ public function move_object($source_bucket, $source_filename, $dest_bucket, $dest_filename, $acl = S3_ACL_PRIVATE) { $return = array(); $return['copy'] = $this->copy_object($source_bucket, $source_filename, $dest_bucket, $dest_filename, array('acl' => $acl)); $return['delete'] = $this->delete_object($source_bucket, $source_filename); return $return; } /** * Method: rename_object() * Identical to , except that it only moves within a single bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket that contains the file. * source_filename - _string_ (Required) The source filename that you want to copy. * dest_filename - _string_ (Required) The filename that you want to give to the copy. * acl - _string_ (Optional) One of the following options: , , , or . Defaults to . * * Returns: * object * * See Also: * Related - , , */ public function rename_object($bucket, $source_filename, $dest_filename, $acl = S3_ACL_PRIVATE) { return $this->move_object($bucket, $source_filename, $bucket, $dest_filename, $acl); } /** * Method: get_object_acl() * Gets the ACL settings for a object. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html * Related - , , */ public function get_object_acl($bucket, $filename, $returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_GET; $opt['method'] = 'get_object_acl'; $opt['filename'] = $filename; $opt['returnCurlHandle'] = $returnCurlHandle; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: set_object_acl() * Sets the ACL settings for a object. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * acl - _string_ (Optional) One of the following options: , , , or . Alternatively, an array of associative arrays. Each associative array contains an 'id' and a 'permission'. Defaults to . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/RESTAccessPolicy.html * Related - , , */ public function set_object_acl($bucket, $filename, $acl = S3_ACL_PRIVATE, $returnCurlHandle = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_PUT; $opt['method'] = 'set_object_acl'; $opt['filename'] = $filename; $opt['returnCurlHandle'] = $returnCurlHandle; // Make sure these are defined. if (!defined('AWS_CANONICAL_ID') || !defined('AWS_CANONICAL_NAME')) { // Fetch the data live. $canonical = $this->get_canonical_user_id(); define('AWS_CANONICAL_ID', $canonical['id']); define('AWS_CANONICAL_NAME', $canonical['display_name']); // Issue a notice. trigger_error('One or both of the configuration settings AWS_CANONICAL_ID and AWS_CANONICAL_NAME have NOT been set in config.inc.php. ' . CLOUDFUSION_NAME . ' must make additional requests to fetch the data, resulting in slower performance for ' . __FUNCTION__ . '(). For best performance, be sure to define these values in your config.inc.php file. For more details, see http://tarzan-aws.googlecode.com/svn/tags/' . CLOUDFUSION_VERSION . '/config-sample.inc.php', E_USER_NOTICE); } if (is_array($acl)) { $opt['body'] = $this->generate_access_policy(AWS_CANONICAL_ID, AWS_CANONICAL_NAME, $acl); } else { $opt['acl'] = $acl; } // Authenticate to S3 return $this->authenticate($bucket, $opt); } /*%******************************************************************************************%*/ // LOGGING METHODS /** * Method: get_logs() * Get the access logs associated with a given bucket. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. Pass null if using . * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/ServerLogs.html * Related - , , */ public function get_logs($bucket) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_GET; $opt['method'] = 'get_logs'; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: enable_logging() * Enable access logging. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be log. Pass null if using . * target_bucket - _string_ (Required) The name of the bucket to store the logs in. * target_prefix - _string_ (Required) The prefix to give to the log filenames. * users - _array_ (Optional) Any non-owner users to give access to. Set as an array of key-value pairs: the email address (must be tied to an AWS account) is the key, and the permission is the value. Allowable permissions are , , , , and . * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/LoggingAPI.html * Permissions - http://docs.amazonwebservices.com/AmazonS3/latest/S3_ACLs.html#S3_ACLs_Permissions * Related - , , */ public function enable_logging($bucket, $target_bucket, $target_prefix, $users = null) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_PUT; $opt['method'] = 'enable_logging'; $xml = simplexml_load_string($this->base_logging_xml); $LoggingEnabled = $xml->addChild('LoggingEnabled'); $LoggingEnabled->addChild('TargetBucket', $target_bucket); $LoggingEnabled->addChild('TargetPrefix', $target_prefix); $TargetGrants = $LoggingEnabled->addChild('TargetGrants'); if ($users && is_array($users)) { foreach ($users as $email => $permission) { $Grant = $TargetGrants->addChild('Grant'); $Grantee = $Grant->addChild('Grantee'); $Grantee->addAttribute('xsi:type', 'AmazonCustomerByEmail', 'http://www.w3.org/2001/XMLSchema-instance'); $Grantee->addChild('EmailAddress', $email); $Grant->addChild('Permission', $permission); } } $opt['body'] = $xml->asXML(); // Authenticate to S3 return $this->authenticate($bucket, $opt); } /** * Method: disable_logging() * Disable access logging. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. Pass null if using . * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/LoggingAPI.html * Related - , , */ public function disable_logging($bucket) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_PUT; $opt['method'] = 'disable_logging'; $opt['body'] = $this->base_logging_xml; // Authenticate to S3 return $this->authenticate($bucket, $opt); } /*%******************************************************************************************%*/ // CONVENIENCE METHODS /** * Method: store_remote_file() * Takes an existing remote URL, stores it to S3, and returns a URL for the stored copy. For creating new objects in S3, use the method. * * Access: * public * * Parameters: * remote_file - _string_ (Required) The full URL of the file to store on the S3 service. * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * acl - _string_ (Optional) One of the following options: , , , or . Defaults to . * overwrite - _boolean_ (Optional) If set to true, checks to see if the file exists and will overwrite the old data with new data. Defaults to false. * * Returns: * _string_ The S3 URL for the uploaded file. Returns null if unsuccessful. */ public function store_remote_file($remote_file, $bucket, $filename, $opt = null) { // Set default values. $acl = S3_ACL_PUBLIC; $overwrite = false; $cname = null; if ($opt) { // Break the options out. extract($opt); } // Does the file already exist? $object = $this->head_object($bucket, $filename); // As long as it doesn't already exist, fetch and store it. if (!$object->isOK() || $overwrite) { // Fetch the file $file = new $this->request_class($remote_file); $file->send_request(); // Store it in S3 unset($object); $object = $this->create_object($bucket, array( 'filename' => $filename, 'body' => $file->get_response_body(), 'contentType' => $file->get_response_header('content-type'), 'acl' => $acl )); } // Was the request successful? if ($object->isOK()) { $url = $object->header['x-cloudfusion-requesturl']; // If we have a virtual host value, use that instead of Amazon's hostname. There are better ways of doing this, but it works for now. if ($this->vhost) { $url = str_ireplace('http://', '', $url); $url = explode('/', $url); $url[0] = $this->vhost; $url = 'http://' . implode('/', $url); } return $url; } else { return null; } } /** * Method: change_content_type() * Changes the content type for an existing object. * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * contentType - _string_ (Required) The content-type to apply to the object. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object */ public function change_content_type($bucket, $filename, $contentType, $returnCurlHandle = null) { return $s3->copy_object($bucket, $filename, $bucket, $filename, array( 'contentType' => $contentType, 'metadataDirective' => 'REPLACE', 'returnCurlHandle' => $returnCurlHandle )); } /*%******************************************************************************************%*/ // URLS /** * Method: get_object_url() * Gets the web-accessible URL for the file (assuming you've set the ACL settings to ). * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * qsa - _integer_ (Optional) How many seconds should the query string authenticated URL work for? Only generates query string authentication parameters if value is greater than 0. Defaults to 0. * torrent - _boolean_ (Optional) Whether to return the torrent version of the URL or not. Defaults to false. * * Returns: * _string_ The file URL (with authentication and/or torrent parameters if requested). * * See Also: * Query String Authentication - http://docs.amazonwebservices.com/AmazonS3/latest/S3_QSAuth.html * Related - */ public function get_object_url($bucket, $filename, $qsa = 0, $torrent = false) { if ($qsa) { // Add this to our request $opt = array(); $opt['verb'] = HTTP_GET; $opt['method'] = 'get_object_url'; $opt['filename'] = $filename . (($torrent) ? '?torrent' : ''); $opt['qsa'] = $qsa; // Adjust the clock $old_offset = $this->adjust_offset; $this->adjust_offset($qsa); // Authenticate to S3 $data = $this->authenticate($bucket, $opt); // Reset the clock $this->adjust_offset = $old_offset; if ($this->vhost) { return 'http://' . $this->vhost . $data['filename'] . ((!$torrent) ? '?' : '&') . 'AWSAccessKeyId=' . $data['key'] . '&Expires=' . $data['expires'] . '&Signature=' . rawurlencode($data['signature']); } return 'http://' . $data['bucket'] . '.s3.amazonaws.com' . $data['filename'] . ((!$torrent) ? '?' : '&') . 'AWSAccessKeyId=' . $data['key'] . '&Expires=' . $data['expires'] . '&Signature=' . rawurlencode($data['signature']); } else { // If we're using a virtual host, use that instead. if ($this->vhost) { return 'http://' . $this->vhost . '/' . $filename . (($torrent) ? '?torrent' : ''); } return 'http://' . $bucket . '.s3.amazonaws.com/' . $filename . (($torrent) ? '?torrent' : ''); } } /** * Method: get_torrent_url() * Gets the web-accessible torrent URL for the file (assuming you've set the ACL settings to ). * * Access: * public * * Parameters: * bucket - _string_ (Required) The name of the bucket to be used. * filename - _string_ (Required) The filename for the object. * qsa - _integer_ (Optional) How many seconds should the query string authenticated URL work for? Only generates query string authentication parameters if value is greater than 0. Defaults to 0. * * Returns: * _string_ The torrent URL (with authentication parameters if requested). * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/index.html?S3TorrentRetrieve.html * Related - */ public function get_torrent_url($bucket, $filename, $qsa = 0) { if ($qsa) { return $this->get_object_url($bucket, $filename, $qsa, true); } return $this->get_object_url($bucket, $filename, 0 , true); } /*%******************************************************************************************%*/ // ACCESS CONTROL POLICY /** * Method: generate_access_policy() * Generate the XML to be used for the Access Control Policy. * * Access: * public * * Parameters: * canonical_id - _string_ (Required) The Canonical ID for the Owner. Use the constant or the 'id' value from . * canonical_name - _string_ (Required) The Canonical Display Name for the Owner. Use the constant or the 'display_name' value from . * users - _array_ (Optional) Array of associative arrays. Each associative array contains an 'id' and a 'permission'. * * Returns: * _string_ Access Control Policy XML. * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonS3/latest/S3_ACLs.html */ public function generate_access_policy($canonical_id, $canonical_name, $users) { $xml = simplexml_load_string($this->base_acp_xml); $owner = $xml->addChild('Owner'); $owner->addChild('ID', $canonical_id); $owner->addChild('DisplayName', $canonical_name); $acl = $xml->addChild('AccessControlList'); foreach ($users as $user) { $grant = $acl->addChild('Grant'); $grantee = $grant->addChild('Grantee'); switch ($user['id']) { // Authorized Users case S3_USERS_AUTH: $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance'); $grantee->addChild('URI', S3_USERS_AUTH); break; // All Users case S3_USERS_ALL: $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance'); $grantee->addChild('URI', S3_USERS_ALL); break; // The Logging User case S3_USERS_LOGGING: $grantee->addAttribute('xsi:type', 'Group', 'http://www.w3.org/2001/XMLSchema-instance'); $grantee->addChild('URI', S3_USERS_LOGGING); break; // Assume an Email Address default: $grantee->addAttribute('xsi:type', 'AmazonCustomerByEmail', 'http://www.w3.org/2001/XMLSchema-instance'); $grantee->addChild('EmailAddress', $user['id']); break; } $grant->addChild('Permission', $user['permission']); } return $xml->asXML(); } /** * Method: get_canonical_user_id() * Obtains the CanonicalUser ID and DisplayName from the server. * * Access: * public * * Returns: * _array_ The id and display_name values. */ public function get_canonical_user_id() { $id = $this->list_buckets(); return array( 'id' => (string) $id->body->Owner->ID, 'display_name' => (string) $id->body->Owner->DisplayName ); } } cloudfusion-2.5.0/sqs.class.php0000755000000000000000000005537611337016604015215 0ustar rootroot constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * * Returns: * _boolean_ false if no valid values are set, otherwise true. */ public function __construct($key = null, $secret_key = null) { $this->api_version = '2009-02-01'; $this->hostname = SQS_DEFAULT_URL; if (!$key && !defined('AWS_KEY')) { throw new SQS_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.'); } if (!$secret_key && !defined('AWS_SECRET_KEY')) { throw new SQS_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.'); } return parent::__construct($key, $secret_key); } /*%******************************************************************************************%*/ // MISCELLANEOUS /** * Method: set_locale() * By default SQS will self-select the most appropriate locale. This allows you to explicitly sets the locale for SQS to use. * * Access: * public * * Parameters: * locale - _string_ (Required) The locale to explicitly set for SQS. Available options are and . * * Returns: * void * * Examples: * example::sqs/1_create_queue3.phpt: * example::sqs/5_send_message3.phpt: * example::sqs/z_delete_queue3.phpt: */ public function set_locale($locale) { $this->hostname = $locale . SQS_DEFAULT_URL; } /*%******************************************************************************************%*/ // QUEUES /** * Method: create_queue() * Creates a new queue to store messages in. You must provide a queue name that is unique within the scope of the queues you own. The queue is assigned a queue URL; you must use this URL when performing actions on the queue. When you create a queue, if a queue with the same name already exists, returns the queue URL with an error indicating that the queue already exists. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to use for this action. The queue name must be unique within the scope of all your queues. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/1_create_queue.phpt: * example::sqs/1_create_queue3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Query_QueryCreateQueue.html * Related - , , , */ public function create_queue($queue_name, $returnCurlHandle = null) { $opt = array(); $opt['QueueName'] = $queue_name; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('CreateQueue', $opt, $this->hostname); } /** * Method: delete_queue() * Deletes the queue specified by the queue URL. This will delete the queue even if it's not empty. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to perform the action on. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/z_delete_queue.phpt: * example::sqs/z_delete_queue3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Query_QueryDeleteQueue.html * Related - , , , */ public function delete_queue($queue_name, $returnCurlHandle = null) { $opt = array(); $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DeleteQueue', $opt, $this->hostname . '/' . $queue_name); } /** * Method: list_queues() * Returns a list of your queues. A maximum 1000 queue URLs are returned. If you specify a value for the optional parameter, only queues with a name beginning with the specified value are returned. * * Access: * public * * Parameters: * queue_name_prefix - _string_ (Optional) String to use for filtering the list results. Only those queues whose name begins with the specified string are returned. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/2_list_queues.phpt: * example::sqs/2_list_queues2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Query_QueryListQueues.html * Related - , , , */ public function list_queues($queue_name_prefix = null, $returnCurlHandle = null) { $opt = array(); $opt['returnCurlHandle'] = $returnCurlHandle; if ($queue_name_prefix) { $opt['QueueNamePrefix'] = $queue_name_prefix; } return $this->authenticate('ListQueues', $opt, $this->hostname); } /** * Method: get_queue_attributes() * Gets one or all attributes of a queue. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to perform the action on. * attributes - _string_|_array_ (Optional) The attribute you want to get. Setting this value to 'All' returns all the queue's attributes. Pass a string for a single attribute, or an indexed array for multiple attributes. Possible values are 'All', 'ApproximateNumberOfMessages', 'VisibilityTimeout', 'CreatedTimestamp', 'LastModifiedTimestamp', and 'Policy'. Defaults to 'All'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/4_get_queue_attributes.phpt: * example::sqs/4_get_queue_attributes4.phpt: * example::sqs/4_get_queue_attributes5.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Query_QueryGetQueueAttributes.html * Related - , , , */ public function get_queue_attributes($queue_name, $attributes = 'All', $returnCurlHandle = null) { $opt = array(); if (is_array($attributes)) { for ($i = 0, $max = count($attributes); $i < $max; $i++) { $opt['AttributeName.' . ($i + 1)] = $attributes[$i]; } } else { $opt['AttributeName.1'] = $attributes; } $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('GetQueueAttributes', $opt, $this->hostname . '/' . $queue_name); } /** * Method: set_queue_attributes() * Sets an attribute of a queue. Currently, you can set only the attribute for a queue. See Visibility Timeout for more information. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to perform the action on. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * VisibilityTimeout - _integer_ (Optional) Must be an integer from 0 to 7200 (2 hours). * Policy - _string_ (Optional) A policy generated by . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/3_set_queue_attributes.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Query_QueryGetQueueAttributes.html * Related - , , , */ public function set_queue_attributes($queue_name, $opt = null) { if (!$opt) $opt = array(); $count = 1; if (isset($opt['VisibilityTimeout'])) { $opt['Attribute.' . $count . '.Name'] = 'VisibilityTimeout'; $opt['Attribute.' . $count . '.Value'] = $opt['VisibilityTimeout']; unset($opt['VisibilityTimeout']); $count++; } if (isset($opt['Policy'])) { $opt['Attribute.' . $count . '.Name'] = 'Policy'; $opt['Attribute.' . $count . '.Value'] = $opt['Policy']; unset($opt['VisibilityTimeout']); $count++; } return $this->authenticate('SetQueueAttributes', $opt, $this->hostname . '/' . $queue_name); } /*%******************************************************************************************%*/ // MESSAGES /** * Method: send_message() * Delivers a message to the specified queue. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to perform the action on. * message - _string_ (Required) Message size cannot exceed 8 KB. Allowed Unicode characters (according to http://www.w3.org/TR/REC-xml/#charsets): #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/5_send_message.phpt: * example::sqs/5_send_message3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Query_QuerySendMessage.html * Related - , , , */ public function send_message($queue_name, $message, $returnCurlHandle = null) { $opt = array(); $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('SendMessage', $opt, $this->hostname . '/' . $queue_name, $message); } /** * Method: receive_message() * Retrieves one or more messages from the specified queue, including the message body and message ID of each message. Messages returned by this action stay in the queue until you delete them. However, once a message is returned to a request, it is not returned on subsequent requests for the duration of the . If you do not specify a in the request, the overall visibility timeout for the queue is used for the returned messages. A default visibility timeout of 30 seconds is set when you create the queue. You can also set the visibility timeout for the queue by using . See Visibility Timeout for more information. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to perform the action on. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * AttributeName - _string_|_array_ (Optional) The attribute you want to get. Pass a string for a single attribute, or an indexed array for multiple attributes. Possible values are 'SenderId' and 'SentTimestamp'. * VisibilityTimeout - _integer_ (Optional) Must be an integer from 0 to 7200 (2 hours). * MaxNumberOfMessages - _integer_ (Optional) Maximum number of messages to return, from 1 to 10. Not necessarily all the messages in the queue are returned. If there are fewer messages in the queue than , the maximum number of messages returned is the current number of messages in the queue. Defaults to 1 message. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/7_receive_message.phpt: * example::sqs/7_receive_message3.phpt: * example::sqs/7_receive_message4.phpt: * example::sqs/7_receive_message7.phpt: * example::sqs/7_receive_message8.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Query_QueryReceiveMessage.html * Related - , , , */ public function receive_message($queue_name, $opt = null) { if (!$opt) $opt = array(); if (isset($opt['AttributeName'])) { if (is_array($opt['AttributeName'])) { for ($i = 0, $max = count($opt['AttributeName']); $i < $max; $i++) { $opt['AttributeName.' . ($i + 1)] = $opt['AttributeName'][$i]; } } else { $opt['AttributeName.1'] = $opt['AttributeName']; } unset($opt['AttributeName']); } return $this->authenticate('ReceiveMessage', $opt, $this->hostname . '/' . $queue_name); } /** * Method: delete_message() * Unconditionally removes the specified message from the specified queue. Even if the message is locked by another reader due to the visibility timeout setting, it is still deleted from the queue. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to perform the action on. * receipt_handle - _string_ (Required) The receipt handle of the message to delete, returned by . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/8_delete_message.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Query_QueryDeleteMessage.html * Related - , , , */ public function delete_message($queue_name, $receipt_handle, $returnCurlHandle = null) { $opt = array(); $opt['ReceiptHandle'] = $receipt_handle; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DeleteMessage', $opt, $this->hostname . '/' . $queue_name); } /** * Method: change_message_visibility() * Changes the visibility timeout of a specified message in a queue to a new value. The maximum allowed timeout value you can set the value to is 12 hours. This means you can't extend the timeout of a message in an existing queue to more than a total visibility timeout of 12 hours. * * For example, let's say you have a message and its default message visibility timeout is 30 minutes. You could call ChangeMessageVisiblity with a value of two hours and the effective timeout would be two hours and 30 minutes. When that time comes near you could again extend the time out by calling ChangeMessageVisiblity, but this time the maximum allowed timeout would be 9 hours and 30 minutes. * * Access: * public * * Parameters: * receipt_handle - _string_ (Required) The receipt handle associated with the message whose visibility timeout you want to change. This parameter is returned by . * visibility_timeout - _string_ (Required) The new value for the message's visibility timeout (in seconds). This value is limited to 43200 seconds (12 hours). * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryChangeMessageVisibility.html * Related - , , , */ public function change_message_visibility($receipt_handle, $visibility_timeout, $returnCurlHandle = null) { $opt = array(); $opt['ReceiptHandle'] = $receipt_handle; $opt['VisibilityTimeout'] = $visibility_timeout; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('ChangeMessageVisibility', $opt, $this->hostname); } /*%******************************************************************************************%*/ // ACCESS CONTROL METHODS /** * */ public function generate_policy() { } /** * Method: add_permission() * Adds a permission to a queue for a specific principal. This allows for sharing access to the queue. When you create a queue, you have full control access rights for the queue. Only you (as owner of the queue) can grant or deny permissions to the queue. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to perform the action on. * label - _string_ (Required) The unique identification of the permission you're setting. Maximum 80 characters; alphanumeric characters, hyphens (-), and underscores (_) are allowed. * permissions - _array_ (Required) An associative array of AWS account numbers (key) and the actions they're allowed to execute (value). AWS account numbers are for those who will be given permission. Actions can be passed as a string for a single action, or an indexed array for multiple actions. Valid values are '*', 'SendMessage', 'ReceiveMessage', 'DeleteMessage', 'ChangeMessageVisibility', or 'GetQueueAttributes'. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::sqs/add_permission.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryAddPermission.html * Related - , , */ public function add_permission($queue_name, $label, $permissions, $returnCurlHandle = null) { $opt = array(); $opt['Label'] = $label; // Starting point. $count = 1; // Parse through the array if (is_array($permissions)) { foreach ($permissions as $account_id => $actions) { if (is_array($actions)) { foreach ($actions as $action) { $opt['AWSAccountId.' . $count] = $account_id; $opt['ActionName.' . $count] = $action; $count++; } } else { $opt['AWSAccountId.1'] = $account_id; $opt['ActionName.1'] = $actions; } $count++; } } else { throw new SQS_Exception('$permissions MUST be an associative array of AWS Account IDs and Actions they\'re allowed to execute.'); } $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('AddPermission', $opt, $this->hostname . '/' . $queue_name); } /** * Method: remove_permission() * Revokes any permissions in the queue policy that matches the Label parameter. Only the owner of the queue can remove permissions. * * Access: * public * * Parameters: * label - _string_ (Required) This should match the label you set in . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/index.html?Query_QueryRemovePermission.html * Related - , , */ public function remove_permission($label, $returnCurlHandle = null) { if (!$opt) $opt = array(); $opt['Label'] = $label; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('RemovePermission', $opt, $this->hostname); } /*%******************************************************************************************%*/ // HELPER/UTILITY METHODS /** * Method: get_queue_size() * Retrieves the approximate number of messages in the queue. * * Access: * public * * Parameters: * queue_name - _string_ (Required) The name of the queue to perform the action on. * * Returns: * _integer_ The Approximate number of messages in the queue. * * Examples: * example::sqs/6_get_queue_size.phpt: * * See Also: * Related - */ public function get_queue_size($queue_name) { $opt = array(); $opt['AttributeName'] = 'ApproximateNumberOfMessages'; $response = $this->authenticate('GetQueueAttributes', $opt, $this->hostname . '/' . $queue_name); if ($response->isOK() === false) { throw new SQS_Exception("Could not get queue size for $queue_name: " . $response->body->Error->Code); } return (integer) $response->body->GetQueueAttributesResult->Attribute->Value; } } cloudfusion-2.5.0/cloudfusion.class.php0000755000000000000000000006612211337016604016730 0ustar rootroot CloudFusion/2.5 (Cloud Computing Toolkit; http://getcloudfusion.com) Build/20090824000000 */ define('CLOUDFUSION_USERAGENT', CLOUDFUSION_NAME . '/' . CLOUDFUSION_VERSION . ' (Cloud Computing Toolkit; ' . CLOUDFUSION_URL . ') Build/' . CLOUDFUSION_BUILD); /** * Constant: DATE_FORMAT_RFC2616 * Define the RFC 2616-compliant date format */ define('DATE_FORMAT_RFC2616', 'D, d M Y H:i:s \G\M\T'); /** * Constant: DATE_FORMAT_ISO8601 * Define the ISO-8601-compliant date format */ define('DATE_FORMAT_ISO8601', 'Y-m-d\TH:i:s\Z'); /** * Constant: DATE_FORMAT_MYSQL * Define the MySQL-compliant date format */ define('DATE_FORMAT_MYSQL', 'Y-m-d H:i:s'); /** * Constant: HTTP_GET * HTTP method type: Get */ define('HTTP_GET', 'GET'); /** * Constant: HTTP_POST * HTTP method type: Post */ define('HTTP_POST', 'POST'); /** * Constant: HTTP_PUT * HTTP method type: Put */ define('HTTP_PUT', 'PUT'); /** * Constant: HTTP_DELETE * HTTP method type: Delete */ define('HTTP_DELETE', 'DELETE'); /** * Constant: HTTP_HEAD * HTTP method type: Head */ define('HTTP_HEAD', 'HEAD'); /*%******************************************************************************************%*/ // EXCEPTIONS /** * Exception: CloudFusion_Exception * Default CloudFusion Exception. */ class CloudFusion_Exception extends Exception {} /*%******************************************************************************************%*/ // CLASS /** * Class: CloudFusion * Container for all shared methods. This is not intended to be instantiated directly, but is extended by the service-specific classes. */ class CloudFusion { /** * Property: key * The Amazon API Key. This is inherited by all service-specific classes. */ var $key; /** * Property: secret_key * The Amazon API Secret Key. This is inherited by all service-specific classes. */ var $secret_key; /** * Property: account_id * The Amazon Account ID, sans hyphens. This is inherited by all service-specific classes. */ var $account_id; /** * Property: assoc_id * The Amazon Associates ID. This is inherited by all service-specific classes. */ var $assoc_id; /** * Property: util * Handle for the utility functions. This is inherited by all service-specific classes. */ var $util; /** * Property: service * An identifier for the current AWS service. This is inherited by all service-specific classes. */ var $service = null; /** * Property: api_version * The supported API version. This is inherited by all service-specific classes. */ var $api_version = null; /** * Property: utilities_class * The default class to use for Utilities (defaults to ). This is inherited by all service-specific classes. */ var $utilities_class = 'CFUtilities'; /** * Property: request_class * The default class to use for HTTP Requests (defaults to ). This is inherited by all service-specific classes. */ var $request_class = 'RequestCore'; /** * Property: response_class * The default class to use for HTTP Responses (defaults to ). This is inherited by all service-specific classes. */ var $response_class = 'ResponseCore'; /** * Property: adjust_offset * The number of seconds to adjust the request timestamp by (defaults to 0). This is inherited by all service-specific classes. */ var $adjust_offset = 0; /** * Property: enable_ssl * Whether SSL/HTTPS should be enabled by default. This is inherited by all service-specific classes. */ var $enable_ssl = true; /** * Property: set_proxy * Sets the proxy to use for connecting. This is inherited by all service-specific classes. */ var $set_proxy = null; /** * Property: devpay_tokens * Stores the Amazon DevPay tokens to use, if any. This is inherited by all service-specific classes. */ var $devpay_tokens; /** * Property: set_hostname * Stores the alternate hostname to use, if any. This is inherited by all service-specific classes. */ var $hostname = null; /*%******************************************************************************************%*/ // AUTO-LOADER /** * Method: autoloader() * Automatically load classes that aren't included. * * Access: * public static * * Parameters: * class_name - _string_ (Required) The classname to load. * * Returns: * void */ public static function autoloader($class) { $path = dirname(__FILE__) . DIRECTORY_SEPARATOR; if (strstr($class, 'Amazon')) { $path .= str_ireplace('Amazon', '', strtolower($class)) . '.class.php'; } elseif (strstr($class, 'CF')) { $path .= str_ireplace('CF', '_', strtolower($class)) . '.class.php'; } elseif (strstr($class, 'Cache')) { if (file_exists($ipath = 'lib' . DIRECTORY_SEPARATOR . 'cachecore' . DIRECTORY_SEPARATOR . 'icachecore.interface.php')) { require_once($ipath); } $path .= 'lib' . DIRECTORY_SEPARATOR . 'cachecore' . DIRECTORY_SEPARATOR . strtolower($class) . '.class.php'; } elseif (strstr($class, 'RequestCore') || strstr($class, 'ResponseCore')) { $path .= 'lib' . DIRECTORY_SEPARATOR . 'requestcore' . DIRECTORY_SEPARATOR . 'requestcore.class.php'; } if (file_exists($path) && !is_dir($path)) { require_once($path); } } /*%******************************************************************************************%*/ // CONSTRUCTOR /** * Method: __construct() * The constructor. You would not normally instantiate this class directly. Rather, you would instantiate a service-specific class. * * Access: * public * * Parameters: * key - _string_ (Optional) Your Amazon API Key. If blank, it will look for the constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * account_id - _string_ (Optional) Your Amazon account ID without the hyphens. Required for EC2. If blank, it will look for the constant. * assoc_id - _string_ (Optional) Your Amazon Associates ID. Required for AAWS. If blank, it will look for the constant. * * Returns: * boolean FALSE if no valid values are set, otherwise true. */ public function __construct($key = null, $secret_key = null, $account_id = null, $assoc_id = null) { // Instantiate the utilities class. $this->util = new $this->utilities_class(); // Determine the current service. $this->service = get_class($this); // Set default values $this->key = null; $this->secret_key = null; $this->account_id = null; $this->assoc_id = null; // Set the Account ID if ($account_id) { $this->account_id = $account_id; } elseif (defined('AWS_ACCOUNT_ID')) { $this->account_id = AWS_ACCOUNT_ID; } // Set the Associates ID if ($assoc_id) { $this->assoc_id = $assoc_id; } elseif (defined('AWS_ASSOC_ID')) { $this->assoc_id = AWS_ASSOC_ID; } // If both a key and secret key are passed in, use those. if ($key && $secret_key) { $this->key = $key; $this->secret_key = $secret_key; return true; } // If neither are passed in, look for the constants instead. else if (defined('AWS_KEY') && defined('AWS_SECRET_KEY')) { $this->key = AWS_KEY; $this->secret_key = AWS_SECRET_KEY; return true; } // Otherwise set the values to blank and return false. else { throw new CloudFusion_Exception('No valid credentials were used to authenticate with AWS.'); } } /*%******************************************************************************************%*/ // SET CUSTOM SETTINGS /** * Method: adjust_offset() * Allows you to adjust the current time, for occasions when your server is out of sync with Amazon's servers. * This method is inherited by all service-specific classes. You would call this from those classes, not CloudFusion(). * * Access: * public * * Parameters: * seconds - _integer_ (Required) The number of seconds to adjust the sent timestamp by. * * Returns: * void * * Examples: * example::cloudfusion/adjust_offset.phpt: */ public function adjust_offset($seconds) { $this->adjust_offset = $seconds; } /** * Method: set_proxy() * Set the proxy settings to use for connecting. * This method is inherited by all service-specific classes. You would call this from those classes, not CloudFusion(). * * Access: * public * * Parameters: * proxy - _string_ (Required) Accepts proxy credentials in the following format: proxy://user:pass@hostname:port * * Returns: * void * * Examples: * example::cloudfusion/set_proxy.phpt: */ public function set_proxy($proxy) { $this->set_proxy = $proxy; } /** * Method: set_hostname() * Set the hostname to use for connecting. This is useful for alternate services that are API-compatible with AWS, but run from a different hostname. * This method is inherited by all service-specific classes. You would call this from those classes, not CloudFusion(). * * Access: * public * * Parameters: * hostname - _string_ (Required) The alternate hostname to use in place of the default one. Useful for API-compatible applications living on different hostnames. * * Returns: * void * * Examples: * example::cloudfusion/set_hostname.phpt: */ public function set_hostname($hostname) { $this->hostname = $hostname; } /** * Method: disable_ssl() * Disables SSL/HTTPS connections for hosts that don't support them. Some services, however, still REQUIRE SSL support. * This method is inherited by all service-specific classes. You would call this from those classes, not CloudFusion(). * * Access: * public * * Returns: * void * * Examples: * example::cloudfusion/disable_ssl.phpt: */ public function disable_ssl() { $this->enable_ssl = false; } /*%******************************************************************************************%*/ // SET CUSTOM CLASSES /** * Method: set_utilities_class() * Set a custom class for this functionality. Perfect for extending/overriding existing classes with new functionality. * This method is inherited by all service-specific classes. You would call this from those classes, not CloudFusion(). * * Access: * public * * Parameters: * class - _string_ (Optional) The name of the new class to use for this functionality. Defaults to the default class. * * Returns: * void * * Examples: * example::cloudfusion/set_utilities_class.phpt: */ function set_utilities_class($class = 'CFUtilities') { $this->utilities_class = $class; $this->util = new $this->utilities_class(); } /** * Method: set_request_class() * Set a custom class for this functionality. Perfect for extending/overriding existing classes with new functionality. * This method is inherited by all service-specific classes. You would call this from those classes, not CloudFusion(). * * Access: * public * * Parameters: * class - _string_ (Optional) The name of the new class to use for this functionality. Defaults to the default class. * * Returns: * void * * Examples: * example::cloudfusion/set_request_class.phpt: */ function set_request_class($class = 'RequestCore') { $this->request_class = $class; } /** * Method: set_response_class() * Set a custom class for this functionality. Perfect for extending/overriding existing classes with new functionality. * This method is inherited by all service-specific classes. You would call this from those classes, not CloudFusion(). * * Access: * public * * Parameters: * class - _string_ (Optional) The name of the new class to use for this functionality. Defaults to the default class. * * Returns: * void * * Examples: * example::cloudfusion/set_response_class.phpt: */ function set_response_class($class = 'ResponseCore') { $this->response_class = $class; } /*%******************************************************************************************%*/ // AUTHENTICATION /** * Method: authenticate() * Default, shared method for authenticating a connection to AWS. Overridden on a class-by-class basis as necessary. * This method is inherited by all service-specific classes. This should not be used directly unless you're writing custom methods for this class. * * Access: * public * * Parameters: * action - _string_ (Required) Indicates the action to perform. * opt - _array_ (Optional) Associative array of parameters for authenticating. See the individual methods for allowed keys. * domain - _string_ (Optional) The URL of the queue to perform the action on. * message - _string_ (Optional) This parameter is only used by the send_message() method. * * Returns: * object */ public function authenticate($action, $opt = null, $domain = null, $message = null) { $return_curl_handle = false; $key_prepend = 'AWSAccessKeyId=' . $this->key . '&'; // Manage the key-value pairs that are used in the query. $query['Action'] = $action; $query['SignatureMethod'] = 'HmacSHA256'; $query['SignatureVersion'] = 2; $query['Timestamp'] = gmdate(DATE_FORMAT_ISO8601, time() + $this->adjust_offset); $query['Version'] = $this->api_version; // Merge in any options that were passed in if (is_array($opt)) { $query = array_merge($query, $opt); } $return_curl_handle = isset($query['returnCurlHandle']) ? $query['returnCurlHandle'] : false; unset($query['returnCurlHandle']); // Do a case-insensitive, natural order sort on the array keys. uksort($query, 'strcasecmp'); // Create the string that needs to be hashed. $canonical_query_string = $key_prepend . $this->util->to_signable_string($query); // Set the proper verb. $verb = HTTP_GET; if ($message) $verb = HTTP_POST; // Remove the default scheme from the domain. $domain = str_replace(array('http://', 'https://'), '', $domain); // Parse our request. $parsed_url = parse_url('http://' . $domain); // Set the proper host header. $host_header = strtolower($parsed_url['host']); // Set the proper request URI. $request_uri = isset($parsed_url['path']) ? $parsed_url['path'] : '/'; // Prepare the string to sign $stringToSign = "$verb\n$host_header\n$request_uri\n$canonical_query_string"; // Hash the AWS secret key and generate a signature for the request. $query['Signature'] = $this->util->hex_to_base64(hash_hmac('sha256', $stringToSign, $this->secret_key)); // Generate the querystring from $query $querystring = $key_prepend . $this->util->to_query_string($query); // Gather information to pass along to other classes. $helpers = array( 'utilities' => $this->utilities_class, 'request' => $this->request_class, 'response' => $this->response_class, ); // Compose the request. $request_url = (($this->enable_ssl) ? 'https://' : 'http://') . $domain; $request_url .= !isset($parsed_url['path']) ? '/' : ''; $request_url .= '?' . $querystring; $request = new $this->request_class($request_url, $this->set_proxy, $helpers); $request->set_useragent(CLOUDFUSION_USERAGENT); // Set DevPay tokens if we have them. if ($this->devpay_tokens) { $request->add_header('x-amz-security-token', $this->devpay_tokens); } // Tweak some things if we have a message (i.e. AmazonSQS::send_message()). if ($message) { $request->add_header('Content-Type', 'text/plain'); $request->set_method(HTTP_POST); $request->set_body($message); } // If we have a "true" value for returnCurlHandle, do that instead of completing the request. if ($return_curl_handle) { return $request->prep_request(); } // Send! $request->send_request(); // Prepare the response. $headers = $request->get_response_header(); $headers['x-cloudfusion-requesturl'] = $request_url; $headers['x-cloudfusion-stringtosign'] = $stringToSign; if ($message) $headers['x-cloudfusion-body'] = $message; $data = new $this->response_class($headers, new SimpleXMLElement($request->get_response_body()), $request->get_response_code()); // Return! return $data; } /*%******************************************************************************************%*/ // CACHING LAYER /** * Method: cache_response() * Caches a ResponseCore object using the preferred caching method. * This method is inherited by all service-specific classes. You would call this from those classes, not CloudFusion(). * * Access: * public * * Parameters: * method - _string_ (Required) The method of the current object that you want to execute and cache the response for. If the method is not in the $this scope, pass in an array where the correct scope is in the [0] position and the method name is in the [1] position. * location - _string_ (Required) The location to store the cache object in. This may vary by cache method. See below. * expires - _integer_ (Required) The number of seconds until a cache object is considered stale. * params - _array_ (Optional) An indexed array of parameters to pass to the aforementioned method, where array[0] represents the first parameter, array[1] is the second, etc. * gzip - _boolean_ (Optional) Whether data should be gzipped before being stored. Defaults to true. * * Example values for $location: * File - Local file system paths such as ./cache (relative) or /tmp/cache/cloudfusion (absolute). Location must be server-writable. * APC - Pass in 'apc' to use this lightweight cache. You must have the APC extension installed. * XCache - Pass in 'xcache' to use this lightweight cache. You must have the XCache extension installed. * Memcached - Pass in an indexed array of associative arrays. Each associative array should have a 'host' and a 'port' value representing a Memcached server to connect to. * PDO - A URL-style string (e.g. pdo.mysql://user:pass@localhost/cloudfusion_cache) or a standard DSN-style string (e.g. pdo.sqlite:/sqlite/cloudfusion_cache.db). MUST be prefixed with 'pdo.'. See and for more details. * * Returns: * object * * Examples: * example::cloudfusion/cache_response_apc.phpt: * example::cloudfusion/cache_response_file.phpt: * example::cloudfusion/cache_response_memcached.phpt: * example::cloudfusion/cache_response_pdo_sqlite.phpt: * example::cloudfusion/cache_response_multi_apc.phpt: * example::cloudfusion/cache_response_multi_file.phpt: */ public function cache_response($method, $location, $expires, $params = null, $gzip = true) { if (!is_array($params)) { $params = array(); } $_this = $this; if (is_array($method)) { $_this = $method[0]; $method = $method[1]; } // If we have an array, we're probably passing in Memcached servers and ports. if (is_array($location)) { $CacheMethod = 'CacheMC'; } else { // I would expect locations like '/tmp/cache', 'pdo.mysql://user:pass@hostname:port', 'pdo.sqlite:memory:', and 'apc'. $type = strtolower(substr($location, 0, 3)); switch ($type) { case 'apc': $CacheMethod = 'CacheAPC'; break; case 'xca': // First three letters of 'xcache' $CacheMethod = 'CacheXCache'; break; case 'pdo': $CacheMethod = 'CachePDO'; $location = substr($location, 4); break; default: $CacheMethod = 'CacheFile'; break; } } // Once we've determined the preferred caching method, instantiate a new cache. if (isset($_this->key)) { $cache_uuid = $method . '-' . $_this->key . '-' . sha1($method . serialize($params)); } else { $cache_uuid = $method . '-' . 'nokey' . '-' . sha1($method . serialize($params)); } $cache = new $CacheMethod($cache_uuid, $location, $expires, $gzip); // If the data exists... if ($data = $cache->read()) { // It exists, but is it expired? if ($cache->is_expired()) { // If so, fetch new data from Amazon. if ($data = call_user_func_array(array($_this, $method), $params)) { if (is_array($data)) { $copy = array(); for ($i = 0, $max = sizeof($data); $i < $max; $i++) { // We need to convert the SimpleXML data back to real XML before the cache methods serialize it. $copy[$i] = is_object($data[$i]) ? clone($data[$i]) : $data[$i]; } // Cache the data $cache->update($copy); // Free the unused memory. $copy = null; unset($copy); } else { // We need to convert the SimpleXML data back to real XML before the cache methods serialize it. $copy = is_object($data) ? clone($data) : $data; if (isset($copy->body) && get_class($copy->body) == 'SimpleXMLElement') { $copy->body = $copy->body->asXML(); } // Cache the data $cache->update($copy); // Free the unused memory. $copy = null; unset($copy); } } // We did not get back good data from Amazon... else { // ...so we'll reset the freshness of the cache and use it again (if supported by the caching method). $cache->reset(); } } // It exists and is still fresh. Let's use it. else { if (is_array($data)) { for ($i = 0, $len = sizeof($data); $i < $len; $i++) { if (isset($data[$i]->body)) { $data[$i]->body = new SimpleXMLElement($data[$i]->body); } } } else { if (isset($data->body)) { $data->body = new SimpleXMLElement($data->body); } } } } // The data does not already exist in the cache. else { // Fetch it. if ($data = call_user_func_array(array($_this, $method), $params)) { if (is_array($data)) { $copy = array(); for ($i = 0, $max = sizeof($data); $i < $max; $i++) { // We need to convert the SimpleXML data back to real XML before the cache methods serialize it. $copy[$i] = is_object($data[$i]) ? clone($data[$i]) : $data[$i]; } // Cache the data $cache->create($copy); // Free the unused memory. $copy = null; unset($copy); } else { // We need to convert the SimpleXML data back to real XML before the cache methods serialize it. $copy = is_object($data) ? clone($data) : $data; if (isset($copy->body) && get_class($copy->body) == 'SimpleXMLElement') { $copy->body = $copy->body->asXML(); } // Cache the data $cache->create($copy); // Free the unused memory. $copy = null; unset($copy); } } } // We're done. Return the data. Huzzah! return $data; } /** * Method: delete_cache_response() * Deletes a cached ResponseCore object using the preferred caching method. * * Access: * public * * Parameters: * method - _string_ (Required) The same method you used while caching initially. * location - _string_ (Required) The same location you used while caching initially. * params - _array_ (Optional) The same parameters that you used while caching initially. * * Example values for $location: * File - Local file system paths such as ./cache (relative) or /tmp/cache/tarzan (absolute). Location must be server-writable. * APC - Pass in 'apc' to use this lightweight cache. You must have the APC extension installed. * XCache - Pass in 'xcache' to use this lightweight cache. You must have the XCache extension installed. * Memcached - Pass in an indexed array of associative arrays. Each associative array should have a 'host' and a 'port' value representing a Memcached server to connect to. * PDO - A URL-style string (e.g. pdo.mysql://user:pass@localhost/tarzan_cache) or a standard DSN-style string (e.g. pdo.sqlite:/sqlite/tarzan_cache.db). MUST be prefixed with 'pdo.'. See and for more details. * * Returns: * boolean TRUE if cached object exists and is successfully deleted, otherwise FALSE * * Examples: * example::cloudfusion/delete_cache_response_apc.phpt: * example::cloudfusion/delete_cache_response_file.phpt: * example::cloudfusion/delete_cache_response_memcached.phpt: * example::cloudfusion/delete_cache_response_pdo_sqlite.phpt: */ public function delete_cache_response($method, $location, $params = null) { if (!is_array($params)) { $params = array(); } $_this = $this; if (is_array($method)) { $_this = $method[0]; $method = $method[1]; } // If we have an array, we're probably passing in Memcached servers and ports. if (is_array($location)) { $CacheMethod = 'CacheMC'; } else { // I would expect locations like '/tmp/cache', 'pdo.mysql://user:pass@hostname:port', 'pdo.sqlite:memory:', and 'apc'. $type = strtolower(substr($location, 0, 3)); switch ($type) { case 'apc': $CacheMethod = 'CacheAPC'; break; case 'xca': // First three letters of 'xcache' $CacheMethod = 'CacheXCache'; break; case 'pdo': $CacheMethod = 'CachePDO'; $location = substr($location, 4); break; default: $CacheMethod = 'CacheFile'; break; } } // Once we've determined the preferred caching method, instantiate a new cache. if (isset($_this->key)) { $cache_uuid = $method . '-' . $_this->key . '-' . sha1($method . serialize($params)); } else { $cache_uuid = $method . '-' . 'nokey' . '-' . sha1($method . serialize($params)); } $cache = new $CacheMethod($cache_uuid, $location, 0); // Try and delete, returns true if cached object exists and is successfully deleted, otherwise false return $cache->delete(); } } // Register the autoloader. spl_autoload_register(array('CloudFusion', 'autoloader')); cloudfusion-2.5.0/cloudwatch.class.php0000644000000000000000000001615711337016604016533 0ustar rootroot constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * * Returns: * _boolean_ false if no valid values are set, otherwise true. */ public function __construct($key = null, $secret_key = null) { $this->api_version = '2009-05-15'; $this->hostname = CW_DEFAULT_URL; if (!$key && !defined('AWS_KEY')) { throw new CloudWatch_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.'); } if (!$secret_key && !defined('AWS_SECRET_KEY')) { throw new CloudWatch_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.'); } return parent::__construct($key, $secret_key); } /*%******************************************************************************************%*/ // METHODS /** * Method: list_metrics() * Returns a list of up to 500 valid metrics for which there is recorded data available to a you and a NextToken string that can be used to query for the next set of results. * * Access: * public * * Parameters: * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * NextToken - _string_ (Optional) Allows you to retrieve the next set of results for your ListMetrics query. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::cloudwatch/list_metrics.phpt: * example::cloudwatch/list_metrics2.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/index.html?API-ListMetrics.html */ public function list_metrics($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('ListMetrics', $opt, $this->hostname); } /** * Method: get_metric_statistics() * Returns data for one or more statistics of given a metric. * * Access: * public * * Parameters: * measure_name - _string_ (Required) The measure name that corresponds to the measure for the gathered metric. See http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/index.html?arch-AmazonCloudWatch-metricscollected.html for a list of available measurements. * statistics - _string_|_array_ (Required) The statistics to be returned for the given metric. You can pass a string for a single statistic, or an indexed array for multiple statistics. See http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/index.html?arch-Amazon-CloudWatch-statistics.html for a list of available statistics. * unit - _string_ (Required) The standard unit of measurement for a given Measure. See http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/index.html?DT_StandardUnit.htmlfor a list of available units. * start_time - _string_ (Required) A time stamp representing the beginning of the period to get results for. Looks for an ISO-8601 formatted time stamp, but can convert any understandable time stamp into the correct format automatically. * end_time - _string_ (Required) A time stamp representing the end of the period to get results for. Looks for an ISO-8601 formatted time stamp, but can convert any understandable time stamp into the correct format automatically. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * CustomUnit - _array_ (Optional) The user-defined CustomUnit applied to a Measure. * Dimensions - _array_ (Optional) Allows you to specify one Dimension to further filter metric data on. If you don't specify a dimension, the service returns the aggregate of all the measures with the given measure name and time range. See http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/index.html?arch-Amazon-CloudWatch-dimensions.html for a list of available dimensions. * Namespace - _array_ (Optional) The namespace corresponding to the service of interest. For example, "AWS/EC2" represents Amazon EC2. * Period - _integer_ (Required) The granularity (in seconds) of the returned datapoints. Must be a multiple of 60. Defaults to 60. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * Examples: * example::cloudwatch/get_metric_statistics.phpt: * example::cloudwatch/get_metric_statistics2.phpt: * example::cloudwatch/get_metric_statistics3.phpt: * * See Also: * AWS Method - http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/index.html?API_GetMetricStatistics.html */ public function get_metric_statistics($measure_name, $statistics, $unit, $start_time, $end_time, $opt = null) { if (!$opt) $opt = array(); $opt['MeasureName'] = $measure_name; $opt['Unit'] = $unit; $opt['StartTime'] = $this->util->convert_date_to_iso8601($start_time); $opt['EndTime'] = $this->util->convert_date_to_iso8601($end_time); if (is_array($statistics)) { for ($i = 0, $max = count($statistics); $i < $max; $i++) { $opt['Statistics.member.' . ($i + 1)] = $statistics[$i]; } } else { $opt['Statistics.member.1'] = $statistics; } if (!isset($opt['Period'])) { $opt['Period'] = 60; } return $this->authenticate('GetMetricStatistics', $opt, $this->hostname); } } cloudfusion-2.5.0/ec2.class.php0000755000000000000000000017271311337016604015053 0ustar rootroot constant. * secret_key - _string_ (Optional) Your Amazon API Secret Key. If blank, it will look for the constant. * account_id - _string_ (Optional) Your Amazon Account ID, without hyphens. If blank, it will look for the constant. * * Returns: * _boolean_ false if no valid values are set, otherwise true. * * See Also: * Example Usage - http://getcloudfusion.com/docs/examples/ec2/__construct.phps */ public function __construct($key = null, $secret_key = null, $account_id = null) { $this->api_version = '2008-12-01'; $this->hostname = EC2_DEFAULT_URL; if (!$key && !defined('AWS_KEY')) { throw new EC2_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.'); } if (!$secret_key && !defined('AWS_SECRET_KEY')) { throw new EC2_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.'); } if (!$account_id && !defined('AWS_ACCOUNT_ID')) { throw new EC2_Exception('No Amazon account ID was passed into the constructor, nor was it set in the AWS_ACCOUNT_ID constant.'); } return parent::__construct($key, $secret_key, $account_id); } /*%******************************************************************************************%*/ // MISCELLANEOUS /** * Method: set_locale() * By default EC2 will self-select the most appropriate locale. This allows you to explicitly sets the locale for EC2 to use. * * Access: * public * * Parameters: * locale - _string_ (Required) The locale to explicitly set for EC2. Available options are and . * * Returns: * void * * See Also: * Example Usage - http://getcloudfusion.com/docs/examples/ec2/set_locale.phps */ public function set_locale($locale) { $this->hostname = $locale . EC2_DEFAULT_URL; } /*%******************************************************************************************%*/ // AVAILABILITY ZONES /** * Method: describe_availability_zones() * Describes availability zones that are currently available to the account and their states. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * ZoneName.n - _string_ (Optional) Name of an availability zone. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeAvailabilityZones.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/describe_availability_zones.phps */ public function describe_availability_zones($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeAvailabilityZones', $opt, $this->hostname); } /*%******************************************************************************************%*/ // ELASTIC IP ADDRESSES /** * Method: allocate_address() * Acquires an elastic IP address for use with your account. * * Access: * public * * Parameters: * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-AllocateAddress.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/elastic_ip.phps * Related - , , , */ public function allocate_address($returnCurlHandle = null) { $opt = array(); $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('AllocateAddress', $opt, $this->hostname); } /** * Method: associate_address() * Associates an elastic IP address with an instance. * * If the IP address is currently assigned to another instance, the IP address is assigned to the new instance. This is an idempotent operation. If you enter it more than once, Amazon EC2 does not return an error. * * Access: * public * * Parameters: * instance_id - _string_ (Required) The instance to which the IP address is assigned. * public_ip - _string_ (Required) IP address that you are assigning to the instance, retrieved from . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-AssociateAddress.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/elastic_ip.phps * Related - , , , */ public function associate_address($instance_id, $public_ip, $returnCurlHandle = null) { $opt = array(); $opt['InstanceId'] = $instance_id; $opt['PublicIp'] = $public_ip; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('AssociateAddress', $opt, $this->hostname); } /** * Method: describe_addresses() * Lists elastic IP addresses assigned to your account. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * PublicIp.1 - _string_ (Required but can be empty) One Elastic IP addresses to describe. * PublicIp.n - _string_ (Optional) More than one Elastic IP addresses to describe. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeAddresses.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/elastic_ip.phps * Related - , , , */ public function describe_addresses($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeAddresses', $opt, $this->hostname); } /** * Method: disassociate_address() * Disassociates the specified elastic IP address from the instance to which it is assigned. * * This is an idempotent operation. If you enter it more than once, Amazon EC2 does not return an error. * * Access: * public * * Parameters: * public_ip - _string_ (Required) IP address that you are disassociating from the instance. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DisassociateAddress.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/elastic_ip.phps * Related - , , , */ public function disassociate_address($public_ip, $returnCurlHandle = null) { $opt = array(); $opt['PublicIp'] = $public_ip; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DisassociateAddress', $opt, $this->hostname); } /** * Method: release_address() * Releases an elastic IP address associated with your account. If you run this operation on an elastic IP address that is already released, the address might be assigned to another account which will cause Amazon EC2 to return an error. * * Releasing an IP address automatically disassociates it from any instance with which it is associated. For more information, see . * * After releasing an elastic IP address, it is released to the IP address pool and might no longer be available to your account. Make sure to update your DNS records and any servers or devices that communicate with the address. * * Access: * public * * Parameters: * public_ip - _string_ (Required) IP address that you are releasing from your account. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-ReleaseAddress.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/elastic_ip.phps * Related - , , , */ public function release_address($public_ip, $returnCurlHandle = null) { if (!$opt) $opt = array(); $opt['PublicIp'] = $public_ip; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('ReleaseAddress', $opt, $this->hostname); } /*%******************************************************************************************%*/ // EBS SNAPSHOTS TO S3 /** * Method: create_snapshot() * Creates a snapshot of an Amazon EBS volume and stores it in Amazon S3. You can use snapshots for backups, to launch instances from identical snapshots, and to save data before shutting down an instance. For more information, see Amazon Elastic Block Store. * * Access: * public * * Parameters: * volume_id - _string_ (Required) The ID of the Amazon EBS volume to snapshot. Must be a volume that you own. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-CreateSnapshot.html * Related - , */ public function create_snapshot($volume_id, $returnCurlHandle = null) { $opt = array(); $opt['VolumeId'] = $volume_id; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('CreateSnapshot', $opt, $this->hostname); } /** * Method: describe_snapshots() * Describes the status of Amazon EBS snapshots. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * SnapshotId.n - _string_ (Optional) The ID of the Amazon EBS snapshot. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeSnapshots.html * Related - , */ public function describe_snapshots($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeSnapshots', $opt, $this->hostname); } /** * Method: delete_snapshot() * Deletes a snapshot of an Amazon EBS volume that is stored in Amazon S3. * * Access: * public * * Parameters: * snapshot_id - _string_ (Optional) The ID of the Amazon EBS snapshot to delete. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DeleteSnapshot.html * Related - , */ public function delete_snapshot($snapshot_id, $returnCurlHandle = null) { $opt = array(); $opt['SnapshotId'] = $snapshot_id; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DeleteSnapshot', $opt, $this->hostname); } /*%******************************************************************************************%*/ // EBS VOLUMES /** * Method: create_volume() * Creates a new Amazon EBS volume that you can mount from any Amazon EC2 instance. You must specify an availability zone when creating a volume. The volume and any instance to which it attaches must be in the same availability zone. * * Access: * public * * Parameters: * sizesnapid - _mixed_ (Required) Either the size of the volume in GB as an integer (from 1 to 1024), or the ID of the snapshot from which to create the new volume as a string. * zone - _string_ (Required) The availability zone in which to create the new volume. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-CreateVolume.html * Related - , , , */ public function create_volume($sizesnapid, $zone, $returnCurlHandle = null) { $opt = array(); $opt['AvailabilityZone'] = $zone; $opt['returnCurlHandle'] = $returnCurlHandle; if (is_numeric($sizesnapid)) { $opt['Size'] = $sizesnapid; } else { $opt['SnapshotId'] = $sizesnapid; } return $this->authenticate('CreateVolume', $opt, $this->hostname); } /** * Method: describe_volumes() * Lists one or more Amazon EBS volumes that you own. If you do not specify any volumes, Amazon EBS returns all volumes that you own. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * VolumeId.n - _string_ (Optional) The ID of the volume to list. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeVolumes.html * Related - , , , */ public function describe_volumes($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeVolumes', $opt, $this->hostname); } /** * Method: attach_volume() * Attaches an Amazon EBS volume to an instance. * * Access: * public * * Parameters: * volume_id - _string_ (Required) The ID of the Amazon EBS volume. * instance_id - _string_ (Required) The ID of the instance to which the volume attaches. * device - _string_ (Required) Specifies how the device is exposed to the instance (e.g., /dev/sdh). For information on standard storage locations, see Storage Locations. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-AttachVolume.html * Storage Locations - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/instance-storage.html#storage-locations * Related - , , , */ public function attach_volume($volume_id, $instance_id, $device, $returnCurlHandle = null) { $opt = array(); $opt['VolumeId'] = $volume_id; $opt['InstanceId'] = $instance_id; $opt['Device'] = $device; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('AttachVolume', $opt, $this->hostname); } /** * Method: detach_volume() * Detaches an Amazon EBS volume from an instance. * * Access: * public * * Parameters: * volume_id - _string_ (Required) The ID of the Amazon EBS volume. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * InstanceId - _string_ (Optional) The ID of the instance from which the volume will detach. * Device - _string_ (Optional) The name of the device. * Force - _boolean_ (Optional) Forces detachment if the previous detachment attempt did not occur cleanly (logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach an instance from a failed instance. The instance will not have an opportunity to flush file system caches nor file system meta data. If you use this option, you must perform file system check and repair procedures. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DetachVolume.html * Related - , , , */ public function detach_volume($volume_id, $opt = null) { if (!$opt) $opt = array(); $opt['VolumeId'] = $volume_id; return $this->authenticate('DetachVolume', $opt, $this->hostname); } /** * Method: delete_volume() * Deletes an Amazon EBS volume. * * Access: * public * * Parameters: * volume_id - _string_ (Required) The ID of the Amazon EBS volume. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DeleteVolume.html * Related - , , , */ public function delete_volume($volume_id, $returnCurlHandle = null) { $opt = array(); $opt['VolumeId'] = $volume_id; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DeleteVolume', $opt, $this->hostname); } /*%******************************************************************************************%*/ // MISCELLANEOUS /** * Method: get_console_output() * Retrieves console output for the specified instance. Instance console output is buffered and posted shortly after instance boot, reboot, and termination. Amazon EC2 preserves the most recent 64 KB output which will be available for at least one hour after the most recent post. * * Access: * public * * Parameters: * instance_id - _string_ (Required) An instance ID returned from a previous call to . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-GetConsoleOutput.html * Related - */ public function get_console_output($instance_id, $returnCurlHandle = null) { $opt = array(); $opt['InstanceId'] = $instance_id; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('GetConsoleOutput', $opt, $this->hostname); } /** * Method: reboot_instances() * Requests a reboot of one or more instances. This operation is asynchronous; it only queues a request to reboot the specified instance(s). The operation will succeed if the instances are valid and belong to the user. Requests to reboot terminated instances are ignored. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * InstanceId.1 - _string_ (Required) One instance ID returned from previous calls to . * InstanceId.n - _string_ (Optional) More than one instance IDs returned from previous calls to . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-RebootInstances.html * Related - */ public function reboot_instances($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('RebootInstances', $opt, $this->hostname); } /*%******************************************************************************************%*/ // IMAGES /** * Method: deregister_image() * De-registers an AMI. Once de-registered, instances of the AMI may no longer be launched. * * Access: * public * * Parameters: * image_id - _string_ (Required) Unique ID of a machine image, returned by a call to or . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DeregisterImage.html * Related - , */ public function deregister_image($image_id, $returnCurlHandle = null) { $opt = array(); $opt['ImageId'] = $image_id; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DeregisterImage', $opt, $this->hostname); } /** * Method: describe_images() * The DescribeImages operation returns information about AMIs, AKIs, and ARIs available to the user. Information returned includes image type, product codes, architecture, and kernel and RAM disk IDs. Images available to the user include public images available for any user to launch, private images owned by the user making the request, and private images owned by other users for which the user has explicit launch permissions. * * Launch permissions fall into three categories: (a) 'public' where the owner of the AMI granted launch permissions for the AMI to the all group. All users have launch permissions for these AMIs. (b) 'explicit' where the owner of the AMI granted launch permissions to a specific user. (c) 'implicit' where a user has implicit launch permissions for all AMIs he or she owns. * * The list of AMIs returned can be modified by specifying AMI IDs, AMI owners, or users with launch permissions. If no options are specified, Amazon EC2 returns all AMIs for which the user has launch permissions. * * If you specify one or more AMI IDs, only AMIs that have the specified IDs are returned. If you specify an invalid AMI ID, a fault is returned. If you specify an AMI ID for which you do not have access, it will not be included in the returned results. * * If you specify one or more AMI owners, only AMIs from the specified owners and for which you have access are returned. The results can include the account IDs of the specified owners, amazon for AMIs owned by Amazon or self for AMIs that you own. * * If you specify a list of executable users, only users that have launch permissions for the AMIs are returned. You can specify account IDs (if you own the AMI(s)), self for AMIs for which you own or have explicit permissions, or all for public AMIs. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * ExecutableBy.n - _string_ (Optional) Describe AMIs that the specified users have launch permissions for. Accepts Amazon account ID, 'self', or 'all' for public AMIs. * ImageId.n - _string_ (Optional) A list of image descriptions. * Owner.n - _string_ (Optional) Owners of AMIs to describe. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeImages.html * Related - , */ public function describe_images($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeImages', $opt, $this->hostname); } /** * Method: register_image() * Registers an AMI with Amazon EC2. Images must be registered before they can be launched. For more information, see . * * Each AMI is associated with an unique ID which is provided by the Amazon EC2 service through the operation. During registration, Amazon EC2 retrieves the specified image manifest from Amazon S3 and verifies that the image is owned by the user registering the image. * * The image manifest is retrieved once and stored within the Amazon EC2. Any modifications to an image in Amazon S3 invalidates this registration. If you make changes to an image, deregister the previous image and register the new image. For more information, see . * * Access: * public * * Parameters: * image_location - _string_ (Required) Full path to your AMI manifest in Amazon S3 storage (i.e. mybucket/myimage.manifest.xml). * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-RegisterImage.html * Related - , */ public function register_image($image_location, $returnCurlHandle = null) { $opt = array(); $opt['ImageLocation'] = $image_location; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('RegisterImage', $opt, $this->hostname); } /*%******************************************************************************************%*/ // IMAGE ATTRIBUTES /** * Method: describe_image_attribute() * Returns information about an attribute of an AMI. Only one attribute may be specified per call. * * Access: * public * * Parameters: * image_id - _string_ (Required) ID of the AMI for which an attribute will be described, returned by a call to or . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeImageAttribute.html * Related - , */ public function describe_image_attribute($image_id, $returnCurlHandle = null) { $opt = array(); $opt['ImageId'] = $image_id; $opt['returnCurlHandle'] = $returnCurlHandle; // This is the only supported value in the current release. $opt['Attribute'] = 'launchPermission'; return $this->authenticate('DescribeImageAttribute', $opt, $this->hostname); } /** * Method: modify_image_attribute() * Modifies an attribute of an AMI. * * Access: * public * * Parameters: * image_id - _string_ (Required) AMI ID to modify an attribute on. * attribute - _string_ (Required) Specifies the attribute to modify. Supports 'launchPermission' and 'productCodes'. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * OperationType - _string_ (Required for 'launchPermission' Attribute) Specifies the operation to perform on the attribute. Supports 'add' and 'remove'. * UserId.n - _string_ (Required for 'launchPermission' Attribute) User IDs to add to or remove from the 'launchPermission' attribute. * UserGroup.n - _string_ (Required for 'launchPermission' Attribute) User groups to add to or remove from the 'launchPermission' attribute. Currently, only the 'all' group is available, specifiying all Amazon EC2 users. * ProductCode.n - _string_ (Required for 'productCodes' Attribute) Attaches product codes to the AMI. Currently only one product code may be associated with an AMI. Once set, the product code can not be changed or reset. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-ModifyImageAttribute.html * Related - , */ public function modify_image_attribute($image_id, $attribute, $opt = null) { if (!$opt) $opt = array(); $opt['ImageId'] = $image_id; $opt['Attribute'] = $attribute; return $this->authenticate('ModifyImageAttribute', $opt, $this->hostname); } /** * Method: reset_image_attribute() * Resets an attribute of an AMI to its default value (the productCodes attribute cannot be reset). * * Access: * public * * Parameters: * image_id - _string_ (Required) ID of the AMI for which an attribute will be described, returned by a call to or . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-ResetImageAttribute.html * Related - , */ public function reset_image_attribute($image_id, $returnCurlHandle = null) { $opt = array(); $opt['ImageId'] = $image_id; $opt['returnCurlHandle'] = $returnCurlHandle; // This is the only supported value in the current release. $opt['Attribute'] = 'launchPermission'; return $this->authenticate('ResetImageAttribute', $opt, $this->hostname); } /*%******************************************************************************************%*/ // INSTANCES /** * Method: confirm_product_instance() * Returns true if the given product code is attached to the instance with the given instance ID. The operation returns false if the product code is not attached to the instance. * * Can only be executed by the owner of the AMI. This feature is useful when an AMI owner is providing support and wants to verify whether a user's instance is eligible. * * Access: * public * * Parameters: * product_code - _string_ (Required) The product code to confirm is attached to the instance. * instance_id - _string_ (Required) The instance for which to confirm the product code. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-ConfirmProductInstance.html * Related - , , */ public function confirm_product_instance($product_code, $instance_id, $returnCurlHandle = null) { $opt = array(); $opt['ProductCode'] = $product_code; $opt['InstanceId'] = $instance_id; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('ConfirmProductInstance', $opt, $this->hostname); } /** * Method: describe_instances() * Returns information about instances owned by the user making the request. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * InstanceId.n - _string_ (Required) Set of instances IDs to get the status of. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeInstances.html * Related - , , */ public function describe_instances($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeInstances', $opt, $this->hostname); } /** * Method: run_instances() * The RunInstances operation launches a specified number of instances. The Query version of only allows instances of a single AMI to be launched in one call. This is different from the SOAP API version of the call, but similar to the ec2-run-instances command line tool. * * If Amazon EC2 cannot launch the minimum number AMIs you request, no instances launch. If there is insufficient capacity to launch the maximum number of AMIs you request, Amazon EC2 launches as many as possible to satisfy the requested maximum values. * * Every instance is launched in a security group. If you do not specify a security group at launch, the instances start in your default security group. For more information on creating security groups, see . * * You can provide an optional key pair ID for each image in the launch request (for more information, see ). All instances that are created from images that use this key pair will have access to the associated public key at boot. You can use this key to provide secure access to an instance of an image on a per-instance basis. Amazon EC2 public images use this feature to provide secure access without passwords. IMPORTANT: Launching public images without a key pair ID will leave them inaccessible. * * The public key material is made available to the instance at boot time by placing it in the openssh_id.pub file on a logical device that is exposed to the instance as /dev/sda2 (the instance store). The format of this file is suitable for use as an entry within ~/.ssh/authorized_keys (the OpenSSH format). This can be done at boot (e.g., as part of rc.local) allowing for secure access without passwords. * * Optional user data can be provided in the launch request. All instances that collectively comprise the launch request have access to this data For more information, see Instance Metadata. NOTE: If any of the AMIs have a product code attached for which the user has not subscribed, the call will fail. * * IMPORTANT: We strongly recommend using the 2.6.18 Xen stock kernel with the c1.medium and c1.xlarge instances. Although the default Amazon EC2 kernels will work, the new kernels provide greater stability and performance for these instance types. For more information about kernels, see Kernels, RAM Disks, and Block Device Mappings. * * Access: * public * * Parameters: * image_id - _string_ (Required) ID of the AMI to launch instances based on. * min_count - _integer_ (Required) Minimum number of instances to launch. * max_count - _integer_ (Required) Maximum number of instances to launch. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * BlockDeviceMapping.n.DeviceName - _string_ (Optional; Required if BlockDeviceMapping.n.VirtualName is used) Specifies the device to which you are mapping a virtual name. For example: sdb. * BlockDeviceMapping.n.VirtualName - _string_ (Optional; Required if BlockDeviceMapping.n.DeviceName is used) Specifies the virtual name to map to the corresponding device name. For example: instancestore0. * InstanceType - _string_ (Optional) Specifies the instance type. Options include 'm1.small', 'm1.large', 'm1.xlarge', 'c1.medium', and 'c1.xlarge'. Defaults to 'm1.small'. * KernelId - _string_ (Optional) The ID of the kernel with which to launch the instance. For information on finding available kernel IDs, see ec2-describe-images. * KeyName - _string_ (Optional) Name of the keypair to launch instances with. * Placement.AvailabilityZone - _string_ (Optional) Specifies the availability zone in which to launch the instance(s). To display a list of availability zones in which you can launch the instances, use the operation. Default is determined by Amazon EC2. * RamdiskId - _string_ (Optional) The ID of the RAM disk with which to launch the instance. Some kernels require additional drivers at launch. Check the kernel requirements for information on whether you need to specify a RAM disk. To find kernel requirements, go to the Resource Center and search for the kernel ID. * SecurityGroup.n - _string_ (Optional) Names of the security groups to associate the instances with. * UserData - _string_ (Optional) The user data available to the launched instances. This should be base64-encoded. See the UserDataType data type for encoding details. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-RunInstances.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/elastic_ip.phps * Related - , , */ public function run_instances($image_id, $min_count, $max_count, $opt = null) { if (!$opt) $opt = array(); $opt['ImageId'] = $image_id; $opt['MinCount'] = $min_count; $opt['MaxCount'] = $max_count; return $this->authenticate('RunInstances', $opt, $this->hostname); } /** * Method: terminate_instances() * Shuts down one or more instances. This operation is idempotent and terminating an instance that is in the process of shutting down (or already terminated) will succeed. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * InstanceId.1 - _string_ (Required) One instance ID returned from previous calls to . * InstanceId.n - _string_ (Optional) More than one instance IDs returned from previous calls to . * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-TerminateInstances.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/elastic_ip.phps * Related - , , */ public function terminate_instances($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('TerminateInstances', $opt, $this->hostname); } /*%******************************************************************************************%*/ // KEYPAIRS /** * Method: create_key_pair() * Creates a new 2048 bit RSA key pair and returns a unique ID that can be used to reference this key pair when launching new instances. For more information, see . * * Access: * public * * Parameters: * key_name - _string_ (Required) A unique name for the key pair. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-CreateKeyPair.html * Related - , */ public function create_key_pair($key_name, $returnCurlHandle = null) { $opt = array(); $opt['KeyName'] = $key_name; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('CreateKeyPair', $opt, $this->hostname); } /** * Method: delete_key_pair() * Deletes a keypair. * * Access: * public * * Parameters: * key_name - _string_ (Required) Unique name for this key. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DeleteKeyPair.html * Related - , */ public function delete_key_pair($key_name, $returnCurlHandle = null) { $opt = array(); $opt['KeyName'] = $key_name; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DeleteKeyPair', $opt, $this->hostname); } /** * Method: describe_key_pairs() * Returns information about key pairs available to you. If you specify key pairs, information about those key pairs is returned. Otherwise, information for all registered key pairs is returned. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * KeyName.n - _string_ (Optional) One or more keypair IDs to describe. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeKeyPairs.html * Related - , */ public function describe_key_pairs($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeKeyPairs', $opt, $this->hostname); } /*%******************************************************************************************%*/ // SECURITY GROUPS /** * Method: authorize_security_group_ingress() * Adds permissions to a security group. * * Permissions are specified in terms of the IP protocol (TCP, UDP or ICMP), the source of the request (by IP range or an Amazon EC2 user-group pair), source and destination port ranges (for TCP and UDP), and ICMP codes and types (for ICMP). When authorizing ICMP, -1 may be used as a wildcard in the type and code fields. * * Permission changes are propagated to instances within the security group being modified as quickly as possible. However, a small delay is likely, depending on the number of instances that are members of the indicated group. * * When authorizing a user/group pair permission, group_name, SourceSecurityGroupName and SourceSecurityGroupOwnerId must be specified. When authorizing a CIDR IP permission, GroupName, IpProtocol, FromPort, ToPort and CidrIp must be specified. Mixing these two types of parameters is not allowed. * * Access: * public * * Parameters: * group_name - _string_ (Required) Name of the security group to modify. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * CidrIp - _string_ (Required when authorizing CIDR IP permission) CIDR IP range to authorize access to when operating on a CIDR IP. * FromPort - _integer_ (Required when authorizing CIDR IP permission) Bottom of port range to authorize access to when operating on a CIDR IP. This contains the ICMP type if ICMP is being authorized. * ToPort - _integer_ (Required when authorizing CIDR IP permission) Top of port range to authorize access to when operating on a CIDR IP. This contains the ICMP code if ICMP is being authorized. * IpProtocol - _string_ (Required when authorizing CIDR IP permission) IP protocol to authorize access to when operating on a CIDR IP. Valid values are 'tcp', 'udp' and 'icmp'. * SourceSecurityGroupName - _string_ (Required when authorizing user/group pair permission) Name of security group to authorize access to when operating on a user/group pair. * SourceSecurityGroupOwnerId - _string_ (Required when authorizing user/group pair permission) Owner of security group to authorize access to when operating on a user/group pair. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-AuthorizeSecurityGroupIngress.html * Related - , , , */ public function authorize_security_group_ingress($group_name, $opt = null) { if (!$opt) $opt = array(); $opt['GroupName'] = $group_name; return $this->authenticate('AuthorizeSecurityGroupIngress', $opt, $this->hostname); } /** * Method: create_security_group() * Every instance is launched in a security group. If none is specified as part of the launch request then instances are launched in the default security group. Instances within the same security group have unrestricted network access to one another. Instances will reject network access attempts from other instances in a different security group. As the owner of instances you may grant or revoke specific permissions using the and operations. * * Access: * public * * Parameters: * group_name - _string_ (Required) Name for the new security group. * group_description - _string_ (Required) Description of the new security group. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-CreateSecurityGroup.html * Related - , , , */ public function create_security_group($group_name, $group_description, $returnCurlHandle = null) { $opt = array(); $opt['GroupName'] = $group_name; $opt['GroupDescription'] = $group_description; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('CreateSecurityGroup', $opt, $this->hostname); } /** * Method: delete_security_group() * Deletes a security group. * * If you attempt to delete a security group that contains instances, a fault is returned. If you attempt to delete a security group that is referenced by another security group, a fault is returned. For example, if security group B has a rule that allows access from security group A, security group A cannot be deleted until the allow rule is removed. * * Access: * public * * Parameters: * group_name - _string_ (Required) Name for the security group. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DeleteSecurityGroup.html * Related - , , , */ public function delete_security_group($group_name, $returnCurlHandle = null) { $opt = array(); $opt['GroupName'] = $group_name; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('DeleteSecurityGroup', $opt, $this->hostname); } /** * Method: describe_security_groups() * Returns information about security groups owned by the user making the request. An optional list of security group names may be provided to request information for those security groups only. If no security group names are provided, information of all security groups will be returned. If a group is specified that does not exist a fault is returned. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * GroupName.n - _string_ (Optional) List of security groups to describe. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeSecurityGroups.html * Related - , , , */ public function describe_security_groups($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeSecurityGroups', $opt, $this->hostname); } /** * Method: revoke_security_group_ingress() * Revokes existing permissions that were previously granted to a security group. The permissions to revoke must be specified using the same values originally used to grant the permission. * * Permissions are specified in terms of the IP protocol (TCP, UDP or ICMP), the source of the request (by IP range or an Amazon EC2 user-group pair), source and destination port ranges (for TCP and UDP), and ICMP codes and types (for ICMP). When authorizing ICMP, -1 may be used as a wildcard in the type and code fields. * * Permission changes are propagated to instances within the security group being modified as quickly as possible. However, a small delay is likely, depending on the number of instances that are members of the indicated group. * * When revoking a user/group pair permission, group_name, SourceSecurityGroupName and SourceSecurityGroupOwnerId must be specified. When authorizing a CIDR IP permission, GroupName, IpProtocol, FromPort, ToPort and CidrIp must be specified. Mixing these two types of parameters is not allowed. * * Access: * public * * Parameters: * group_name - _string_ (Required) Name of the security group to modify. * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * CidrIp - _string_ (Required when revoking CIDR IP permission) CIDR IP range to authorize access to when operating on a CIDR IP. * FromPort - _integer_ (Required when revoking CIDR IP permission) Bottom of port range to authorize access to when operating on a CIDR IP. This contains the ICMP type if ICMP is being authorized. * ToPort - _integer_ (Required when revoking CIDR IP permission) Top of port range to authorize access to when operating on a CIDR IP. This contains the ICMP code if ICMP is being authorized. * IpProtocol - _string_ (Required when revoking CIDR IP permission) IP protocol to authorize access to when operating on a CIDR IP. Valid values are 'tcp', 'udp' and 'icmp'. * SourceSecurityGroupName - _string_ (Required when revoking user/group pair permission) Name of security group to authorize access to when operating on a user/group pair. * SourceSecurityGroupOwnerId - _string_ (Required when revoking user/group pair permission) Owner of security group to authorize access to when operating on a user/group pair. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-RevokeSecurityGroupIngress.html * Related - , , , */ public function revoke_security_group_ingress($group_name, $opt = null) { if (!$opt) $opt = array(); $opt['GroupName'] = $group_name; return $this->authenticate('RevokeSecurityGroupIngress', $opt, $this->hostname); } /*%******************************************************************************************%*/ // BUNDLE WINDOWS AMIS /** * Method: bundle_instance() * Bundles an Amazon EC2 instance running Windows. For more information, see Bundling an AMI in Windows. This operation is for Windows instances only. * * Access: * public * * Parameters: * instanceId - _string_ (Required) The ID of the instance to bundle. * opt - _array_ (Required) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * Bucket - _string_ (Required) The bucket in which to store the AMI. * Prefix - _string_ (Required) The prefix to append to the AMI. * UploadPolicy - _array_ (Optional) The upload policy gives Amazon EC2 limited permission to upload items into your Amazon S3 bucket. See example for documentation. If an Upload Policy is not provided, this method will generate one from the provided information setting ONLY the required values, and will set an expiration of 12 hours. * AWSAccessKeyId - _string_ (Optional) The Access Key ID of the owner of the Amazon S3 bucket. Defaults to the AWS Key used to authenticate the request. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-BundleInstance.html * Upload Policy - http://docs.amazonwebservices.com/AmazonS3/latest/HTTPPOSTExamples.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/bundle_windows.phps * Related - , , */ public function bundle_instance($instance_id, $opt = null) { if (!$opt) $opt = array(); // Instance ID $opt['instanceId'] = $instance_id; // Storage.S3.Bucket if (isset($opt['Bucket'])) { $opt['Storage.S3.Bucket'] = $opt['Bucket']; unset($opt['Bucket']); } // Storage.S3.Prefix if (isset($opt['Prefix'])) { $opt['Storage.S3.Prefix'] = $opt['Prefix']; unset($opt['Prefix']); } // Storage.S3.AWSAccessKeyId if (isset($opt['AWSAccessKeyId'])) { $opt['Storage.S3.AWSAccessKeyId'] = $opt['AWSAccessKeyId']; unset($opt['AWSAccessKeyId']); } else { $opt['Storage.S3.AWSAccessKeyId'] = $this->key; } // Storage.S3.UploadPolicy if (isset($opt['UploadPolicy'])) { $opt['Storage.S3.UploadPolicy'] = base64_encode($this->util->json_encode($opt['UploadPolicy'])); unset($opt['UploadPolicy']); } else { $opt['Storage.S3.UploadPolicy'] = base64_encode($this->util->json_encode(array( 'expiration' => gmdate(DATE_FORMAT_ISO8601, strtotime('+12 hours')), 'conditions' => array( array('bucket' => $opt['Storage.S3.Bucket']), array('acl' => 'ec2-bundle-read') ) ))); } // Storage.S3.UploadPolicySignature $opt['Storage.S3.UploadPolicySignature'] = $this->util->hex_to_base64(hash_hmac('sha1', base64_encode($opt['Storage.S3.UploadPolicy']), $this->secret_key)); return $this->authenticate('BundleInstance', $opt, $this->hostname); } /** * Method: cancel_bundle_task() * Cancels an Amazon EC2 bundling operation. For more information on bundling instances, see Bundling an AMI in Windows. This operation is for Windows instances only. * * Access: * public * * Parameters: * bundle_id - _string_ (Required) The ID of the bundle task to cancel. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-CancelBundleTask.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/bundle_windows.phps * Related - , , */ public function cancel_bundle_task($bundle_id, $returnCurlHandle = null) { $opt = array(); $opt['bundleId'] = $bundle_id; $opt['returnCurlHandle'] = $returnCurlHandle; return $this->authenticate('CancelBundleTask', $opt, $this->hostname); } /** * Method: describe_bundle_tasks() * Describes current bundling tasks. For more information on bundling instances, see Bundling an AMI in Windows. This operation is for Windows instances only. * * Access: * public * * Parameters: * opt - _array_ (Optional) Associative array of parameters which can have the following keys: * * Keys for the $opt parameter: * bundleId - _string_ (Optional) The ID of the bundle task to describe. If no ID is specified, all bundle tasks are described. * returnCurlHandle - _boolean_ (Optional) A private toggle that will return the CURL handle for the request rather than actually completing the request. This is useful for MultiCURL requests. * * Returns: * object * * See Also: * AWS Method - http://docs.amazonwebservices.com/AWSEC2/latest/DeveloperGuide/ApiReference-Query-DescribeBundleTasks.html * Example Usage - http://getcloudfusion.com/docs/examples/ec2/bundle_windows.phps * Related - , , */ public function describe_bundle_tasks($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeBundleTasks', $opt, $this->hostname); } } cloudfusion-2.5.0/config-sample.inc.php0000644000000000000000000000356511337016604016565 0ustar rootroot */ define('AWS_KEY', ''); /** * Constant: AWS_SECRET_KEY * Amazon Web Services Secret Key. */ define('AWS_SECRET_KEY', ''); /** * Constant: AWS_ACCOUNT_ID * Amazon Account ID without dashes. Used for identification with Amazon EC2. */ define('AWS_ACCOUNT_ID', ''); /** * Constant: AWS_ASSOC_ID * Amazon Associates ID. Used for crediting referrals via Amazon AAWS. */ define('AWS_ASSOC_ID', ''); /** * Constant: AWS_DEFAULT_LOCALE * Locale that all PAS methods should default to. Can be overridden per-instance. Valid values are 'us', 'uk', 'ca', 'fr', 'de', or 'jp'. */ define('AWS_DEFAULT_LOCALE', ''); /** * Constant: AWS_CANONICAL_ID * Your CanonicalUser ID. Used for setting access control settings in AmazonS3. Must be fetched from the server. Call get_canonical_user_id()); ?> to view. */ define('AWS_CANONICAL_ID', ''); /** * Constant: AWS_CANONICAL_NAME * Your CanonicalUser DisplayName. Used for setting access control settings in AmazonS3. Must be fetched from the server. Call get_canonical_user_id()); ?> to view. */ define('AWS_CANONICAL_NAME', ''); cloudfusion-2.5.0/lib/0000755000000000000000000000000011337017005013311 5ustar rootrootcloudfusion-2.5.0/lib/cachecore/0000755000000000000000000000000011337017023015225 5ustar rootrootcloudfusion-2.5.0/lib/cachecore/cachemc.class.php0000755000000000000000000000774211337016664020454 0ustar rootrootid = $this->name; $this->memcache = new Memcache(); if ($this->gzip) { $this->gzip = MEMCACHE_COMPRESSED; } if (isset($location) && sizeof($location) > 0) { foreach ($location as $loc) { if (isset($loc['port']) && !empty($loc['port'])) { $this->memcache->addServer($loc['host'], $loc['port']); } else { $this->memcache->addServer($loc['host']); } } } return; } /** * Method: create() * Creates a new cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function create($data) { return $this->memcache->add($this->id, $data, $this->gzip, $this->expires); } /** * Method: read() * Reads a cache. * * Access: * public * * Returns: * _mixed_ Either the content of the cache object, or _boolean_ false. */ public function read() { return $this->memcache->get($this->id, $this->gzip); } /** * Method: update() * Updates an existing cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function update($data) { return $this->memcache->replace($this->id, $data, $this->gzip, $this->expires); } /** * Method: delete() * Deletes a cache. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function delete() { return $this->memcache->delete($this->id); } /** * Method: is_expired() * Defined here, but always returns false. Memcache manages it's own expirations. * * Access: * public * * Returns: * _boolean_ Whether the cache is expired or not. */ public function is_expired() { return false; } /** * Method: timestamp() * Implemented here, but always returns false. Memcache manages it's own expirations. * * Access: * public * * Returns: * _mixed_ Either the Unix time stamp of the cache creation, or _boolean_ false. */ public function timestamp() { return false; } /** * Method: reset() * Implemented here, but always returns false. Memcache manages it's own expirations. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function reset() { return false; } } cloudfusion-2.5.0/lib/cachecore/README0000644000000000000000000000341211337016664016117 0ustar rootroot== CACHECORE == A simple caching system for PHP5 that provides a single interface for a variety of storage types. == LINKS == http://cachecore.googlecode.com == LICENSE == This code has been released under the Simplified (aka "New") BSD license (1999) as follows: Copyright (c) 2006-2009 LifeNexus Digital, Inc., and contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of LifeNexus Digital nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. cloudfusion-2.5.0/lib/cachecore/_sql/0000755000000000000000000000000011337016664016175 5ustar rootrootcloudfusion-2.5.0/lib/cachecore/_sql/README0000644000000000000000000000043211337016664017054 0ustar rootrootThe .sql files in this directory contain the code to create the tables for database caching. If you're not using database caching, you can safely ignore these. If you ARE using database caching, simply load the correct *.sql file into your database to set up the required tables. cloudfusion-2.5.0/lib/cachecore/_sql/sqlite3.sql0000644000000000000000000000014311337016664020300 0ustar rootrootCREATE TABLE cache (id TEXT, expires NUMERIC, data BLOB); CREATE UNIQUE INDEX idx ON cache(id ASC);cloudfusion-2.5.0/lib/cachecore/_sql/pgsql.sql0000644000000000000000000000021111337016664020036 0ustar rootrootCREATE TABLE "cache" ( expires timestamp without time zone NOT NULL, id character(40) NOT NULL, data text NOT NULL ) WITH (OIDS=TRUE);cloudfusion-2.5.0/lib/cachecore/_sql/mysql.sql0000644000000000000000000000037111337016664020064 0ustar rootrootCREATE TABLE `cache` ( `id` char(40) NOT NULL default '', `expires` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, `data` longtext, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8cloudfusion-2.5.0/lib/cachecore/icachecore.interface.php0000644000000000000000000000625511337016664022004 0ustar rootroot for more information. * * Access: * public * * Parameters: * name - _string_ (Required) A name to uniquely identify the cache object. * location - _string_ (Required) The location to store the cache object in. This may vary by cache method. * expires - _integer_ (Required) The number of seconds until a cache object is considered stale. * gzip - _boolean_ (Optional) Whether data should be gzipped before being stored. Defaults to true. * * Returns: * _object_ Reference to the cache object. */ public function __construct($name, $location, $expires, $gzip = true) { // Make sure the name is no longer than 40 characters. $name = sha1($name); // Call parent constructor and set id. parent::__construct($name, $location, $expires, $gzip); $this->id = $this->name; $options = array(); // Check if the location contains :// (e.g. mysql://user:pass@hostname:port/table) if (stripos($location, '://') === false) { // No? Just pass it through. $this->dsn = parse_url($location); $this->dsn_string = $location; } else { // Yes? Parse and set the DSN $this->dsn = parse_url($location); $this->dsn_string = $this->dsn['scheme'] . ':host=' . $this->dsn['host'] . ((isset($this->dsn['port'])) ? ';port=' . $this->dsn['port'] : '') . ';dbname=' . substr($this->dsn['path'], 1); } // Make sure that user/pass are defined. $user = isset($this->dsn['user']) ? $this->dsn['user'] : null; $pass = isset($this->dsn['pass']) ? $this->dsn['pass'] : null; // Set persistence for databases that support it. switch ($this->dsn['scheme']) { case 'mysql': // MySQL case 'pgsql': // PostgreSQL $options[PDO::ATTR_PERSISTENT] = true; break; } // Instantiate a new PDO object with a persistent connection. $this->pdo = new PDO($this->dsn_string, $user, $pass, $options); // Define prepared statements for improved performance. $this->create = $this->pdo->prepare("INSERT INTO cache (id, expires, data) VALUES (:id, :expires, :data)"); $this->read = $this->pdo->prepare("SELECT id, expires, data FROM cache WHERE id = :id"); $this->reset = $this->pdo->prepare("UPDATE cache SET expires = :expires WHERE id = :id"); $this->delete = $this->pdo->prepare("DELETE FROM cache WHERE id = :id"); } /** * Method: create() * Creates a new cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function create($data) { $data = serialize($data); $data = $this->gzip ? gzcompress($data) : $data; $this->create->bindParam(':id', $this->id); $this->create->bindParam(':data', $data); $this->create->bindParam(':expires', $this->generate_timestamp()); return (bool) $this->create->execute(); } /** * Method: read() * Reads a cache. * * Access: * public * * Returns: * _mixed_ Either the content of the cache object, or _boolean_ false. */ public function read() { if (!$this->store_read) { $this->read->bindParam(':id', $this->id); $this->read->execute(); $this->store_read = $this->read->fetch(PDO::FETCH_ASSOC); } if ($this->store_read) { $data = $this->store_read['data']; $data = $this->gzip ? gzuncompress($data) : $data; return unserialize($data); } return false; } /** * Method: update() * Updates an existing cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function update($data) { $this->delete(); return $this->create($data); } /** * Method: delete() * Deletes a cache. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function delete() { $this->delete->bindParam(':id', $this->id); return $this->delete->execute(); } /** * Method: timestamp() * Retrieves the timestamp of the cache. * * Access: * public * * Returns: * _mixed_ Either the Unix timestamp of the cache creation, or _boolean_ false. */ public function timestamp() { if (!$this->store_read) { $this->read->bindParam(':id', $this->id); $this->read->execute(); $this->store_read = $this->read->fetch(PDO::FETCH_ASSOC); } if ($this->store_read) { $value = $this->store_read['expires']; // If 'expires' isn't yet an integer, convert it into one. if (!is_numeric($value)) { $value = strtotime($value); } $this->timestamp = date('U', $value); return $this->timestamp; } return false; } /** * Method: reset() * Resets the freshness of the cache. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function reset() { $this->reset->bindParam(':id', $this->id); $this->reset->bindParam(':expires', $this->generate_timestamp()); return (bool) $this->reset->execute(); } /** * Method: is_expired() * Checks whether the cache object is expired or not. * * Access: * public * * Returns: * _boolean_ Whether the cache is expired or not. */ public function is_expired() { if ($this->timestamp() + $this->expires < time()) { return true; } return false; } /** * Method: get_drivers() * Returns a list of supported PDO database drivers. Identical to PDO::getAvailableDrivers(). * * Access: * public * * Returns: * _array_ The list of supported database drivers. * * See Also: * PHP Method - http://php.net/pdo.getavailabledrivers */ public function get_drivers() { return PDO::getAvailableDrivers(); } /** * Method: generate_timestamp() * Returns a timestamp value apropriate to the current database type. * * Access: * private * * Returns: * _mixed_ Timestamp for MySQL and PostgreSQL, integer value for SQLite. */ private function generate_timestamp() { // Define 'expires' settings differently. switch ($this->dsn['scheme']) { // These support timestamps. case 'mysql': // MySQL case 'pgsql': // PostgreSQL $expires = date(DATE_FORMAT_MYSQL, time()); break; // These support integers. case 'sqlite': // SQLite 3 case 'sqlite2': // SQLite 2 $expires = time(); break; } return $expires; } } cloudfusion-2.5.0/lib/cachecore/cacheapc.class.php0000644000000000000000000000721711337016664020612 0ustar rootrootid = $this->name; } /** * Method: create() * Creates a new cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function create($data) { $data = serialize($data); $data = $this->gzip ? gzcompress($data) : $data; return apc_add($this->id, $data, $this->expires); } /** * Method: read() * Reads a cache. * * Access: * public * * Returns: * _mixed_ Either the content of the cache object, or _boolean_ false. */ public function read() { if ($data = apc_fetch($this->id)) { $data = $this->gzip ? gzuncompress($data) : $data; return unserialize($data); } return false; } /** * Method: update() * Updates an existing cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function update($data) { $data = serialize($data); $data = $this->gzip ? gzcompress($data) : $data; return apc_store($this->id, $data, $this->expires); } /** * Method: delete() * Deletes a cache. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function delete() { return apc_delete($this->id); } /** * Method: is_expired() * Implemented here, but always returns false. APC manages it's own expirations. * * Access: * public * * Returns: * _boolean_ Whether the cache is expired or not. */ public function is_expired() { return false; } /** * Method: timestamp() * Implemented here, but always returns false. APC manages it's own expirations. * * Access: * public * * Returns: * _mixed_ Either the Unix time stamp of the cache creation, or _boolean_ false. */ public function timestamp() { return false; } /** * Method: reset() * Implemented here, but always returns false. APC manages it's own expirations. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function reset() { return false; } } cloudfusion-2.5.0/lib/cachecore/cachefile.class.php0000644000000000000000000001110411337016664020754 0ustar rootrootid = $this->location . '/' . $this->name . '.cache'; } /** * Method: create() * Creates a new cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function create($data) { if (file_exists($this->id)) { return false; } elseif (file_exists($this->location) && is_writeable($this->location)) { $data = serialize($data); $data = $this->gzip ? gzcompress($data) : $data; return (bool) file_put_contents($this->id, $data); } return false; } /** * Method: read() * Reads a cache. * * Access: * public * * Returns: * _mixed_ Either the content of the cache object, or _boolean_ false. */ public function read() { if (file_exists($this->id) && is_readable($this->id)) { $data = file_get_contents($this->id); $data = $this->gzip ? gzuncompress($data) : $data; $data = unserialize($data); if ($data === false) { /** * This should only happen when someone changes the gzip settings and there is existing data or someone has been * mucking about in the cache folder manually. Delete the bad entry since the file cache doesn't clean up after * itself and then return false so fresh data will be retrieved. */ $this->delete(); return false; } return $data; } return false; } /** * Method: update() * Updates an existing cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function update($data) { if (file_exists($this->id) && is_writeable($this->id)) { $data = serialize($data); $data = $this->gzip ? gzcompress($data) : $data; return (bool) file_put_contents($this->id, $data); } return false; } /** * Method: delete() * Deletes a cache. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function delete() { if (file_exists($this->id)) { return unlink($this->id); } return false; } /** * Method: timestamp() * Retrieves the timestamp of the cache. * * Access: * public * * Returns: * _mixed_ Either the Unix timestamp of the cache creation, or _boolean_ false. */ public function timestamp() { clearstatcache(); if (file_exists($this->id)) { $this->timestamp = filemtime($this->id); return $this->timestamp; } return false; } /** * Method: reset() * Resets the freshness of the cache. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function reset() { if (file_exists($this->id)) { return touch($this->id); } return false; } /** * Method: is_expired() * Checks whether the cache object is expired or not. * * Access: * public * * Returns: * _boolean_ Whether the cache is expired or not. */ public function is_expired() { if ($this->timestamp() + $this->expires < time()) { return true; } return false; } } cloudfusion-2.5.0/lib/cachecore/cachecore.class.php0000644000000000000000000000715011337016664020773 0ustar rootrootname = $name; $this->location = $location; $this->expires = $expires; $this->gzip = $gzip; return $this; } /** * Method: response_manager() * Provides a simple, straightforward cache-logic mechanism. Useful for non-complex response caches. * * Access: * public * * Parameters: * callback - _string_ (Required) The name of the function to fire when we need to fetch new data to cache. * params - _array_ (Optional) Parameters to pass into the callback function, as an array. * * Returns: * _array_ The cached data being requested. */ public function response_manager($callback, $params = null) { // Automatically handle $params values. if (is_array($params)) {} elseif (is_string($params)) { $params = array($params); } else { $params = array($params); } if ($data = $this->read()) { if ($this->is_expired()) { if ($data = call_user_func_array($callback, $params)) { $this->update($data); } else { $this->reset(); $data = $this->read(); } } } else { if ($data = call_user_func_array($callback, $params)) { $this->create($data); } } return $data; } } cloudfusion-2.5.0/lib/cachecore/cachexcache.class.php0000644000000000000000000000760611337016664021304 0ustar rootrootid = $this->name; } /** * Method: create() * Creates a new cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function create($data) { $data = serialize($data); $data = $this->gzip ? gzcompress($data) : $data; return xcache_set($this->id, $data, $this->expires); } /** * Method: read() * Reads a cache. * * Access: * public * * Returns: * _mixed_ Either the content of the cache object, or _boolean_ false. */ public function read() { if ($data = xcache_get($this->id)) { $data = $this->gzip ? gzuncompress($data) : $data; return unserialize($data); } return false; } /** * Method: update() * Updates an existing cache. * * Access: * public * * Parameters: * data - _mixed_ (Required) The data to cache. * * Returns: * _boolean_ Whether the operation was successful. */ public function update($data) { $data = serialize($data); $data = $this->gzip ? gzcompress($data) : $data; return xcache_set($this->id, $data, $this->expires); } /** * Method: delete() * Deletes a cache. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function delete() { return xcache_unset($this->id); } /** * Method: is_expired() * Defined here, but always returns false. XCache manages it's own expirations. It's worth * mentioning that if the server is configured for a long xcache.var_gc_interval then it IS * possible for expired data to remain in the var cache, though it is not possible to access * it. * * Access: * public * * Returns: * _boolean_ Whether the cache is expired or not. */ public function is_expired() { return false; } /** * Method: timestamp() * Implemented here, but always returns false. XCache manages it's own expirations. * * Access: * public * * Returns: * _mixed_ Either the Unix time stamp of the cache creation, or _boolean_ false. */ public function timestamp() { return false; } /** * Method: reset() * Implemented here, but always returns false. XCache manages it's own expirations. * * Access: * public * * Returns: * _boolean_ Whether the operation was successful. */ public function reset() { return false; } } cloudfusion-2.5.0/lib/requestcore/0000755000000000000000000000000011337017066015661 5ustar rootrootcloudfusion-2.5.0/lib/requestcore/README0000644000000000000000000000344111337016670016543 0ustar rootroot== REQUESTCORE == RequestCore is a lightweight cURL-based HTTP request/response class that leverages MultiCurl for parallel requests. == LINKS == http://requestcore.googlecode.com == LICENSE == This code has been released under the Simplified (aka "New") BSD license (1999) as follows: Copyright (c) 2006-2009 LifeNexus Digital, Inc., and contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of LifeNexus Digital nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. cloudfusion-2.5.0/lib/requestcore/requestcore.class.php0000644000000000000000000004450711337016670022051 0ustar rootroot). */ var $request_class = 'RequestCore'; /** * Property: response_class * The default class to use for HTTP Responses (defaults to ). */ var $response_class = 'ResponseCore'; /** * Property: useragent * Default useragent string to use. */ var $useragent = 'RequestCore/1.1'; /*%******************************************************************************************%*/ // CONSTRUCTOR /** * Method: __construct() * The constructor * * Access: * public * * Parameters: * url - _string_ (Optional) The URL to request or service endpoint to query. * proxy - _string_ (Optional) The faux-url to use for proxy settings. Takes the following format: proxy://user:pass@hostname:port * helpers - _array_ (Optional) An associative array of classnames to use for request, and response functionality. Gets passed in automatically by the calling class. * * Returns: * $this */ public function __construct($url = null, $proxy = null, $helpers = null) { // Set some default values. $this->request_url = $url; $this->method = HTTP_GET; $this->request_headers = array(); $this->request_body = ''; // Set a new Request class if one was set. if (isset($helpers['request']) && !empty($helpers['request'])) { $this->request_class = $helpers['request']; } // Set a new Request class if one was set. if (isset($helpers['response']) && !empty($helpers['response'])) { $this->response_class = $helpers['response']; } if ($proxy) { $this->set_proxy($proxy); } return $this; } /*%******************************************************************************************%*/ // REQUEST METHODS /** * Method: set_credentials() * Sets the credentials to use for authentication. * * Access: * public * * Parameters: * user - _string_ (Required) The username to authenticate with. * pass - _string_ (Required) The password to authenticate with. * * Returns: * $this */ public function set_credentials($user, $pass) { $this->username = $user; $this->password = $pass; return $this; } /** * Method: add_header() * Adds a custom HTTP header to the cURL request. * * Access: * public * * Parameters: * key - _string_ (Required) The custom HTTP header to set. * value - _mixed_ (Required) The value to assign to the custom HTTP header. * * Returns: * $this */ public function add_header($key, $value) { $this->request_headers[$key] = $value; return $this; } /** * Method: remove_header() * Removes an HTTP header from the cURL request. * * Access: * public * * Parameters: * key - _string_ (Required) The custom HTTP header to set. * * Returns: * $this */ public function remove_header($key) { if (isset($this->request_headers[$key])) { unset($this->request_headers[$key]); } return $this; } /** * Method: set_method() * Set the method type for the request. * * Access: * public * * Parameters: * method - _string_ (Required) One of the following constants: , , , , . * * Returns: * $this */ public function set_method($method) { $this->method = strtoupper($method); return $this; } /** * Method: set_useragent() * Sets a custom useragent string for the class. * * Access: * public * * Parameters: * method - _string_ (Required) The useragent string to use. * * Returns: * $this */ public function set_useragent($ua) { $this->useragent = $ua; return $this; } /** * Method: set_body() * Set the body to send in the request. * * Access: * public * * Parameters: * body - _string_ (Required) The textual content to send along in the body of the request. * * Returns: * $this */ public function set_body($body) { $this->request_body = $body; return $this; } /** * Method: set_request_url() * Set the URL to make the request to. * * Access: * public * * Parameters: * body - _string_ (Required) The textual content to send along in the body of the request. * * Returns: * $this */ public function set_request_url($url) { $this->request_url = $url; return $this; } /** * Method: set_curlopts() * Set additional CURLOPT settings. These will merge with the default settings, and override if there is a duplicate. * * Access: * public * * Parameters: * curlopts - _array_ (Optional) A set of key-value pairs that set CURLOPT options. These will merge with the existing CURLOPTs, and ones passed here will override the defaults. Keys should be the CURLOPT_* constants, not strings. * * Returns: * $this */ public function set_curlopts($curlopts) { $this->curlopts = $curlopts; return $this; } /** * Method: set_proxy() * Set the proxy to use for making requests. * * Access: * public * * Parameters: * proxy - _string_ (Optional) The faux-url to use for proxy settings. Takes the following format: proxy://user:pass@hostname:port * * Returns: * $this */ public function set_proxy($proxy) { $proxy = parse_url($proxy); $proxy['user'] = isset($proxy['user']) ? $proxy['user'] : null; $proxy['pass'] = isset($proxy['pass']) ? $proxy['pass'] : null; $proxy['port'] = isset($proxy['port']) ? $proxy['port'] : null; $this->proxy = $proxy; return $this; } /*%******************************************************************************************%*/ // PREPARE, SEND, AND PROCESS REQUEST /** * Method: prep_request() * Prepares and adds the details of the cURL request. This can be passed along to a curl_multi_exec() function. * * Access: * public * * Returns: * The handle for the cURL object. */ public function prep_request() { $this->add_header('Expect', '100-continue'); $this->add_header('Connection', 'close'); $curl_handle = curl_init(); // Set default options. curl_setopt($curl_handle, CURLOPT_URL, $this->request_url); curl_setopt($curl_handle, CURLOPT_FILETIME, true); curl_setopt($curl_handle, CURLOPT_FRESH_CONNECT, false); curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, true); curl_setopt($curl_handle, CURLOPT_CLOSEPOLICY, CURLCLOSEPOLICY_LEAST_RECENTLY_USED); curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl_handle, CURLOPT_MAXREDIRS, 5); curl_setopt($curl_handle, CURLOPT_HEADER, true); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_handle, CURLOPT_TIMEOUT, 5184000); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 120); curl_setopt($curl_handle, CURLOPT_NOSIGNAL, true); curl_setopt($curl_handle, CURLOPT_REFERER, $this->request_url); curl_setopt($curl_handle, CURLOPT_USERAGENT, $this->useragent); // Merge in the CURLOPTs if (isset($this->curlopts) && sizeof($this->curlopts) > 0) { foreach ($this->curlopts as $k => $v) { curl_setopt($curl_handle, $k, $v); } } // Enable a proxy connection if requested. if ($this->proxy) { curl_setopt($curl_handle, CURLOPT_HTTPPROXYTUNNEL, true); $host = $this->proxy['host']; $host .= ($this->proxy['port']) ? ':' . $this->proxy['port'] : ''; curl_setopt($curl_handle, CURLOPT_PROXY, $host); if (isset($this->proxy['user']) && isset($this->proxy['pass'])) { curl_setopt($curl_handle, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']); } } // Set credentials for HTTP Basic/Digest Authentication. if ($this->username && $this->password) { curl_setopt($curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($curl_handle, CURLOPT_USERPWD, $this->username . ':' . $this->password); } // Handle the encoding if we can. if (extension_loaded('zlib')) { curl_setopt($curl_handle, CURLOPT_ENCODING, ''); } // Process custom headers if (isset($this->request_headers) && count($this->request_headers)) { $temp_headers = array(); foreach ($this->request_headers as $k => $v) { $temp_headers[] = $k . ': ' . $v; } curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $temp_headers); } switch ($this->method) { case HTTP_PUT: curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body); break; case HTTP_POST: curl_setopt($curl_handle, CURLOPT_POST, true); curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body); break; case HTTP_HEAD: curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, HTTP_HEAD); curl_setopt($curl_handle, CURLOPT_NOBODY, 1); break; default: curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, $this->method); curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body); break; } return $curl_handle; } /** * Method: process_response() * Take the post-processed cURL data and break it down into useful header/body/info chunks. Uses the data stored in the and properties unless replacement data is passed in via parameters. * * Access: * public * * Parameters: * curl_handle - _string_ (Optional) The reference to the already executed cURL request. * response - _string_ (Optional) The actual response content itself that needs to be parsed. * * Returns: * object */ public function process_response($curl_handle = null, $response = null) { // Accept a custom one if it's passed. if ($curl_handle && $response) { $this->curl_handle = $curl_handle; $this->response = $response; } // As long as this came back as a valid resource... if (is_resource($this->curl_handle)) { // Determine what's what. $header_size = curl_getinfo($this->curl_handle, CURLINFO_HEADER_SIZE); $this->response_headers = substr($this->response, 0, $header_size); $this->response_body = substr($this->response, $header_size); $this->response_code = curl_getinfo($this->curl_handle, CURLINFO_HTTP_CODE); $this->response_info = curl_getinfo($this->curl_handle); // Parse out the headers $this->response_headers = explode("\r\n\r\n", trim($this->response_headers)); $this->response_headers = array_pop($this->response_headers); $this->response_headers = explode("\r\n", $this->response_headers); array_shift($this->response_headers); // Loop through and split up the headers. $header_assoc = array(); foreach ($this->response_headers as $header) { $kv = explode(': ', $header); $header_assoc[strtolower($kv[0])] = $kv[1]; } // Reset the headers to the appropriate property. $this->response_headers = $header_assoc; $this->response_headers['_info'] = $this->response_info; $this->response_headers['_info']['method'] = $this->method; if ($curl_handle && $response) { return new $this->response_class($this->response_headers, $this->response_body, $this->response_code); } } // Return false return false; } /** * Method: send_request() * Sends the request, calling necessary utility functions to update built-in properties. * * Access: * public * * Parameters: * parse - _boolean_ (Optional) Whether to parse the response with ResponseCore or not. * * Returns: * _string_ The resulting unparsed data from the request. */ public function send_request($parse = false) { $curl_handle = $this->prep_request(); $this->response = curl_exec($curl_handle); $parsed_response = $this->process_response($curl_handle, $this->response); curl_close($curl_handle); if ($parse) { return $parsed_response; } return $this->response; } /** * Method: send_multi_request() * Sends the request using curl_multi_exec(), enabling parallel requests. * * Access: * public * * Parameters: * handles - _array_ (Required) An indexed array of cURL handles to process simultaneously. * * Returns: * _array_ Post-processed cURL responses. */ public function send_multi_request($handles) { // Initialize MultiCURL $multi_handle = curl_multi_init(); // Loop through each of the CURL handles and add them to the MultiCURL request. foreach ($handles as $handle) { curl_multi_add_handle($multi_handle, $handle); } $count = 0; // Execute do { $status = curl_multi_exec($multi_handle, $active); } while ($status == CURLM_CALL_MULTI_PERFORM || $active); // Define this. $handles_post = array(); // Retrieve each handle response foreach ($handles as $handle) { if (curl_errno($handle) == CURLE_OK) { $http = new $this->request_class(null); $handles_post[] = $http->process_response($handle, curl_multi_getcontent($handle)); } else { throw new RequestCore_Exception(curl_error($handle)); } // Explicitly close each cURL handle. curl_multi_remove_handle($multi_handle, $handle); curl_close($handle); } return $handles_post; } /*%******************************************************************************************%*/ // RESPONSE METHODS /** * Method: get_response_header() * Get the HTTP response headers from the request. * * Access: * public * * Parameters: * header - _string_ (Optional) A specific header value to return. Defaults to all headers. * * Returns: * _string_|_array_ All or selected header values. */ public function get_response_header($header = null) { if ($header) { return $this->response_headers[strtolower($header)]; } return $this->response_headers; } /** * Method: get_response_body() * Get the HTTP response body from the request. * * Access: * public * * Returns: * _string_ The response body. */ public function get_response_body() { return $this->response_body; } /** * Method: get_response_code() * Get the HTTP response code from the request. * * Access: * public * * Returns: * _string_ The HTTP response code. */ public function get_response_code() { return $this->response_code; } } /** * Class: ResponseCore * Container for all response-related methods. */ class ResponseCore { /** * Property: header * Stores the HTTP header information. */ var $header; /** * Property: body * Stores the SimpleXML response. */ var $body; /** * Property: status * Stores the HTTP response code. */ var $status; /** * Method: __construct() * The constructor * * Access: * public * * Parameters: * header - _array_ (Required) Associative array of HTTP headers (typically returned by ). * body - _string_ (Required) XML-formatted response from AWS. * status - _integer_ (Optional) HTTP response status code from the request. * * Returns: * _object_ Contains an _array_ 'header' property (HTTP headers as an associative array), a _SimpleXMLElement_ or _string_ 'body' property, and an _integer_ 'status' code. */ public function __construct($header, $body, $status = null) { $this->header = $header; $this->body = $body; $this->status = $status; return $this; } /** * Method: isOK() * Did we receive the status code we expected? * * Access: * public * * Parameters: * codes - _integer|array_ (Optional) The status code(s) to expect. Pass an _integer_ for a single acceptable value, or an _array_ of integers for multiple acceptable values. Defaults to _array_ 200|204. * * Returns: * _boolean_ Whether we received the expected status code or not. */ public function isOK($codes = array(200, 201, 204)) { if (is_array($codes)) { return in_array($this->status, $codes); } else { return ($this->status == $codes); } } }