diff --git a/.gitignore b/.gitignore index 3a96cbde..45dbdd30 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ composer.phar composer.lock .DS_Store +.idea amazon-config.php test.php log.txt diff --git a/.travis.yml b/.travis.yml index f60bbe00..1b447874 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,10 +4,10 @@ php: - 5.4 - 5.5 - 5.6 - - hhvm + - 7 before_script: - travis_retry composer self-update - travis_retry composer install --prefer-source --no-interaction --dev -script: phpunit +script: cd test-cases && phpunit --bootstrap bootstrap.php \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..b7e5a9e1 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,38 @@ +# CHANGELOG + + +### 2020-10-30 - Version 4.1.0 + +- [[PR #52](https://github.com/sonnenglas/amazon-mws-laravel/pull/52)] Fix Relationships in AmazonProduct class +- [[PR #26](https://github.com/sonnenglas/amazon-mws-laravel/pull/26)] Fix in AmazonFeed class +- [[PR #23](https://github.com/sonnenglas/amazon-mws-laravel/pull/23)] Added getThrottleCountForLastRequest() to AmazonCore class to track throttling +- [[PR #22](https://github.com/sonnenglas/amazon-mws-laravel/pull/22)] Added support for Subscriptions +- [[PR #15](https://github.com/sonnenglas/amazon-mws-laravel/pull/52)] Fix prepareCategories() in AmazonProductInfo class +- Fixed bug with getProduct() in class AmazonProduct + +### 2020-10-22 - Version 4.0.1 + +- added tax registration details to AmazonOrder class + +### 2020-09-27 - Version 4.0.0 + +- Added support for Laravel 6.x + +### 2018-11-08 - Version 3.0.5.1 + +### 2018-11-08 - Version 3.0.5 + +- [[PR #17](https://github.com/sonnenglas/amazon-mws-laravel/pull/17)] Fix to include relationships including additional ns2 attributes +- [[PR #16](https://github.com/sonnenglas/amazon-mws-laravel/pull/16)] Fixed timestamp format to truly follow ISO8601 +- [[PR #13](https://github.com/sonnenglas/amazon-mws-laravel/pull/13)] Fix ineffective muteLog config setting +- [[PR #9](https://github.com/sonnenglas/amazon-mws-laravel/pull/9)] added proxy support and some fixes + +### 2018-07-25 - Version 3.0.4 + +- added `setMarketPlaceId()` to AmazonFulfillmentOrderCreator class + +### 2018-07-24 - Version 3.0.3 + +- [[PR #11](https://github.com/sonnenglas/amazon-mws-laravel/pull/11/)] added all missing order / orderitem fields that were declared in the API spec +- [[PR #8](https://github.com/sonnenglas/amazon-mws-laravel/pull/8/)] added `authToken` to configuration file. MWSAuthToken is used to make requests on behalf of other amazon users +- [[PR #7](https://github.com/sonnenglas/amazon-mws-laravel/pull/7/)] Backported Financial APIs from https://github.com/CPIGroup/phpAmazonMWS \ No newline at end of file diff --git a/INSTALL.md b/INSTALL.md deleted file mode 100644 index 1da0fff4..00000000 --- a/INSTALL.md +++ /dev/null @@ -1,53 +0,0 @@ -## Installing -To install, simply add the library to your project. Composer is the default installation tool for this library. -If you do not use Composer for your project, you can still auto-load classes by including the file **includes/classes.php** in the page or function. - -Before you use any commands, you need to create an **amazon-config.php** file with your account credentials. Start by copying the template provided (*amazon-config.default.php*) and renaming the file. - -If you are operating outside of the United States, be sure to change the Amazon Service URL to the one matching your region. - -You can also link the built-in logging system to your own system by putting the logging function's name in the *$logfunction* parameter. - -The default location for the built-in log file is in the library's main directory. In the event that PHP does not have the correct permissions to create a file in there, you will have to create the log file as "log.txt" and give PHP permission to edit it. - -## Usage -All of the technical details required by the API are handled behind the scenes, -so users can easily build code for sending requests to Amazon -without having to jump hurdles such as parameter URL formatting and token management. -The general work flow for using one of the objects is this: - -1. Create an object for the task you need to perform. -2. Load it up with parameters, depending on the object, using *set____* methods. -3. Submit the request to Amazon. The methods to do this are usually named *fetch____* or *submit____* and have no parameters. -4. Reference the returned data, whether as single values or in bulk, using *get____* methods. -5. Monitor the performance of the library using the built-in logging system. - -Note that if you want to act on more than one Amazon store, you will need a separate object for each store. - -Also note that the objects perform best when they are not treated as reusable. Otherwise, you may end up grabbing old response data if a new request fails. - -## Examples -Here is an example of a function used to get all warehouse-fulfilled orders from Amazon updated in the past 24 hours: -```php -function getAmazonOrders() { - $amz = new AmazonOrderList("myStore"); //store name matches the array key in the config file - $amz->setLimits('Modified', "- 24 hours"); - $amz->setFulfillmentChannelFilter("MFN"); //no Amazon-fulfilled orders - $amz->setOrderStatusFilter( - array("Unshipped", "PartiallyShipped", "Canceled", "Unfulfillable") - ); //no shipped or pending - $amz->setUseToken(); //Amazon sends orders 100 at a time, but we want them all - $amz->fetchOrders(); - return $amz->getList(); -} -``` -This example shows a function used to send a previously-created XML feed to Amazon to update Inventory numbers: -```php -function sendInventoryFeed($feed) { - $amz=new AmazonFeed("myStore"); //store name matches the array key in the config file - $amz->setFeedType("_POST_INVENTORY_AVAILABILITY_DATA_"); //feed types listed in documentation - $amz->setFeedContent($feed); - $amz->submitFeed(); - return $amz->getResponse(); -} -``` diff --git a/README.md b/README.md index 00e3f164..ee1f4cf3 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,43 @@ -phpAmazonMWS +amazon-mws-laravel ============ -A library to connect to Amazon's Merchant Web Services (MWS) in an object-oriented manner, with a focus on intuitive usage. +A PHP package to connect to Amazon's Merchant Web Services (MWS) in an object-oriented manner, with a focus on intuitive usage. + +Currently optimizing for Laravel Framework. This is __NOT__ for Amazon Web Services (AWS) - Cloud Computing Services. +## Installation + +1. `composer require sonnenglas/laravel5-amazon-mws` + +2. add the service provider to the providers array in config/app.php: +``` +Sonnenglas\AmazonMws\ServiceProvider::class, +``` + +There's no facades to add in config/app.php + +3. Copy amazon-mws.php configuration file from src/config/amazon-mws.php to Laravel's config directory. + +## Usage +All of the technical details required by the API are handled behind the scenes, +so users can easily build code for sending requests to Amazon +without having to jump hurdles such as parameter URL formatting and token management. +The general work flow for using one of the objects is this: + +1. Create an object for the task you need to perform. +2. Load it up with parameters, depending on the object, using *set____* methods. +3. Submit the request to Amazon. The methods to do this are usually named *fetch____* or *submit____* and have no parameters. +4. Reference the returned data, whether as single values or in bulk, using *get____* methods. +5. Monitor the performance of the library using the built-in logging system. + +Note that if you want to act on more than one Amazon store, you will need a separate object for each store. + +Also note that the objects perform best when they are not treated as reusable. Otherwise, you may end up grabbing old response data if a new request fails. ## Example Usage + Here are a couple of examples of the library in use. All of the technical details required by the API are handled behind the scenes, so users can easily build code for sending requests to Amazon @@ -14,6 +45,8 @@ without having to jump hurdles such as parameter URL formatting and token manage Here is an example of a function used to get all warehouse-fulfilled orders from Amazon updated in the past 24 hours: ```php +use Sonnenglas\AmazonMws\AmazonOrderList; + function getAmazonOrders() { $amz = new AmazonOrderList("myStore"); //store name matches the array key in the config file $amz->setLimits('Modified', "- 24 hours"); @@ -28,8 +61,10 @@ function getAmazonOrders() { ``` This example shows a function used to send a previously-created XML feed to Amazon to update Inventory numbers: ```php +use Sonnenglas\AmazonMws\AmazonOrderList; + function sendInventoryFeed($feed) { - $amz=new AmazonFeed("myStore"); //store name matches the array key in the config file + $amz = new AmazonFeed("myStore"); //store name matches the array key in the config file $amz->setFeedType("_POST_INVENTORY_AVAILABILITY_DATA_"); //feed types listed in documentation $amz->setFeedContent($feed); $amz->submitFeed(); diff --git a/amazon-config.default.php b/amazon-config.default.php deleted file mode 100644 index 0deb552b..00000000 --- a/amazon-config.default.php +++ /dev/null @@ -1,38 +0,0 @@ - diff --git a/composer.json b/composer.json index 5e346385..01cf6459 100644 --- a/composer.json +++ b/composer.json @@ -1,26 +1,33 @@ { - "name": "creacoon/amazon-mws", - "description": "An open-source library to connect to Amazon's MWS web services in an object-oriented manner, with a focus on intuitive usage.", - "license": "Apache-2.0", - "keywords": ["API", "Amazon", "PHP", "MWS", "Laravel"], - "authors": [ - { - "name": "Tom Coonen", - "email": "tom@creacoon.nl" - } - ], - "require": { - "php": ">=5.4.0", - "ext-curl": "*", - "illuminate/support": "4.2.*" - }, - "require-dev": { - "phpunit/phpunit": "3.7.*" - }, - "autoload": { - "psr-0": { - "Creacoon\\AmazonMws": "src/" - } - }, - "minimum-stability": "stable" + "name": "sonnenglas/laravel-amazon-mws", + "description": "Use Amazon's MWS web services with Laravel ^7.x. Based on creacoon/amazon-mws-laravel package and modified to make it compatible with latest Laravel releases (+ bugfixes).", + "license": "Apache-2.0", + "keywords": [ + "API", + "Amazon", + "PHP", + "MWS", + "Laravel" + ], + "authors": [ + { + "name": "Przemek Peron", + "email": "przemek@redkorn.pl" + } + ], + "require": { + "php": ">=5.5.9", + "ext-curl": "*", + "ext-simplexml": "*", + "illuminate/support": "6.*|7.*|8.*|9.*|10.*|11.*" + }, + "require-dev": { + "phpunit/phpunit": "5.*" + }, + "autoload": { + "psr-4": { + "Sonnenglas\\AmazonMws\\": "src" + } + }, + "minimum-stability": "stable" } diff --git a/environment.php b/environment.php index e221ff3f..727d7f98 100644 --- a/environment.php +++ b/environment.php @@ -23,7 +23,7 @@ */ //for User-Agent header(?) -$AMAZON_APPLICATION = 'phpAmazonMWS'; +$AMAZON_APPLICATION = 'LaravelAmazonMWS'; $AMAZON_APPVERSION = '1.0'; //Version numbers for cores @@ -35,6 +35,10 @@ $AMAZON_VERSION_PRODUCTS = '2011-10-01'; $AMAZON_VERSION_REPORTS = '2009-01-01'; $AMAZON_VERSION_SELLERS = '2011-07-01'; +$AMAZON_VERSION_FINANCE = '2015-05-01'; +//Recommendations +$THROTTLE_LIMIT_FINANCE = 30; +$THROTTLE_TIME_FINANCE = 2; //Amazon Throttle Values in seconds //Fetching Orders diff --git a/includes/classes.php b/includes/classes.php deleted file mode 100644 index fc7302f6..00000000 --- a/includes/classes.php +++ /dev/null @@ -1,29 +0,0 @@ - diff --git a/includes/classes/AmazonCore.php b/includes/classes/AmazonCore.php deleted file mode 100644 index 0e95959f..00000000 --- a/includes/classes/AmazonCore.php +++ /dev/null @@ -1,841 +0,0 @@ - - *
  • Create an object (or objects) of the desired type.
  • - *
  • Set the request parameters using "set_____" functions. - * Some classes allow you to set parameters when constructing the object. - * Some classes don't need any parameters, and a few don't have any at all.
  • - *
  • Send the request to Amazon using the class's unique function. (Usually "fetch___") - * If not enough parameters have been set, the request will not go through.
  • - *
  • Retrieve the data received with "get____" functions. Some classes can - * be iterated through using foreach.
  • - *
  • Repeat. Please note that performing Amazon actions sometimes alters or - * removes parameters previously set, so it is recommended that you set all of the - * desired parameters again before making a second action, or better yet, use a new object. - * The exception to this is follow-up actions, which rely on the data previously - * received from Amazon and do not require any parameters.
  • - * - * While there are a lot of functions, they all share one of the structures listed below. - * Once you know how to use one class, you should be able to use the other classes. - * - */ -abstract class AmazonCore{ - protected $urlbase; - protected $urlbranch; - protected $throttleLimit; - protected $throttleTime; - protected $throttleSafe; - protected $throttleGroup; - protected $throttleStop = false; - protected $storeName; - protected $options; - protected $config; - protected $mockMode = false; - protected $mockFiles; - protected $mockIndex = 0; - protected $logpath; - protected $env; - protected $rawResponses = array(); - - /** - * AmazonCore constructor sets up key information used in all Amazon requests. - * - * This constructor is called when initializing all objects in this library. - * The parameters are passed by the child objects' constructors. - * @param string $s

    Name for the store you want to use as seen in the config file. - * If this is not set to a valid name, none of these objects will work.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * When this is set to TRUE, the object will fetch responses from - * files you specify instead of sending the requests to Amazon. - * The log will indicate whether mock mode is on or off each time - * an object is initialized. This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode. - * When Mock Mode is enabled, the object will retrieve one of these files - * from the list to use as a response. See setMock for more information.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - protected function __construct($s, $mock=false, $m = null, $config = null){ - if (is_null($config)){ - $config = __DIR__.'/../../amazon-config.php'; - } - $this->setConfig($config); - $this->setStore($s); - $this->setMock($mock,$m); - - $this->env=__DIR__.'/../../environment.php'; - $this->options['SignatureVersion'] = 2; - $this->options['SignatureMethod'] = 'HmacSHA256'; - } - - /** - * Enables or disables Mock Mode for the object. - * - * Use this method when you want to test your object without sending - * actual requests to Amazon. When Mock Mode is enabled, responses are - * pulled from files you specify instead of sending the request. - * Be careful, as this means that the parameters you send will not - * necessarily match the response you get back. The files are pulled in order - * of the list, looping back to the first file after the last file is used. - * The log records every time a file is set or used, or if the file is missing. - * This method is also used to set response codes used by certain functions. - * Mock Mode is particularly useful when you need - * to test functions such as canceling orders or adding new products. - * @param boolean $b [optional]

    When set to TRUE, Mock Mode is - * enabled for the object. Defaults to TRUE.

    - * @param array|string|integer $files [optional]

    The list of files (or single file) - * to be used with Mock Mode. If a single string is given, this method will - * put it into an array. Integers can also be given, for use in fetchMockResponse. - * These numbers should only be response codes, such as 200 or 404.

    - */ - public function setMock($b = true,$files = null){ - if (is_bool($b)){ - $this->resetMock(true); - $this->mockMode = $b; - if ($b){ - $this->log("Mock Mode set to ON"); - } - - if (is_string($files)){ - $this->mockFiles = array(); - $this->mockFiles[0] = $files; - $this->log("Single Mock File set: $files"); - } else if (is_array($files)){ - $this->mockFiles = $files; - $this->log("Mock files array set."); - } else if (is_numeric($files)){ - $this->mockFiles = array(); - $this->mockFiles[0] = $files; - $this->log("Single Mock Response set: $files"); - } - } - } - - /** - * Fetches the given mock file, or attempts to. - * - * This method is only called when Mock Mode is enabled. This is where - * files from the mock file list are retrieved and passed back to the caller. - * The success or failure of the operation will be recorded in the log, - * including the name and path of the file involved. For retrieving response - * codes, see fetchMockResponse. - * @param boolean $load [optional]

    Set this to FALSE to prevent the - * method from loading the file's contents into a SimpleXMLObject. This is - * for when the contents of the file are not in XML format, or if you simply - * want to retrieve the raw string of the file.

    - * @return SimpleXMLObject|string|boolean

    A SimpleXMLObject holding the - * contents of the file, or a string of said contents if $load is set to - * FALSE. The return will be FALSE if the file cannot be - * fetched for any reason.

    - */ - protected function fetchMockFile($load = true){ - if(!is_array($this->mockFiles) || !array_key_exists(0, $this->mockFiles)){ - $this->log("Attempted to retrieve mock files, but no mock files present",'Warning'); - return false; - } - if(!array_key_exists($this->mockIndex, $this->mockFiles)){ - $this->log("End of Mock List, resetting to 0"); - $this->resetMock(); - } - //check for absolute/relative file paths - if (strpos($this->mockFiles[$this->mockIndex], '/') === 0 || strpos($this->mockFiles[$this->mockIndex], '..') === 0){ - $url = $this->mockFiles[$this->mockIndex]; - } else { - $url = 'mock/'.$this->mockFiles[$this->mockIndex]; - } - $this->mockIndex++; - - - if(file_exists($url)){ - - try{ - $this->log("Fetched Mock File: $url"); - if ($load){ - $return = simplexml_load_file($url); - } else { - $return = file_get_contents($url); - } - return $return; - } catch (Exception $e){ - $this->log("Error when opening Mock File: $url - ".$e->getMessage(),'Warning'); - return false; - } - - } else { - $this->log("Mock File not found: $url",'Warning'); - return false; - } - - } - - /** - * Sets mock index back to 0. - * - * This method is used for returning to the beginning of the mock file list. - * @param boolean $mute [optional]

    Set to TRUE to prevent logging.

    - */ - protected function resetMock($mute = false){ - $this->mockIndex = 0; - if (!$mute){ - $this->log("Mock List index reset to 0"); - } - } - - /** - * Generates a fake HTTP response using the mock file list. - * - * This method uses the response codes in the mock file list to generate an - * HTTP response. The success or failure of this operation will be recorded - * in the log, including the response code returned. This is only used by - * a few operations. The response array will contain the following fields: - * - * @return boolean|array An array containing the HTTP response, or simply - * the value FALSE if the response could not be found or does not - * match the list of valid responses. - */ - protected function fetchMockResponse(){ - if(!is_array($this->mockFiles) || !array_key_exists(0, $this->mockFiles)){ - $this->log("Attempted to retrieve mock responses, but no mock responses present",'Warning'); - return false; - } - if(!array_key_exists($this->mockIndex, $this->mockFiles)){ - $this->log("End of Mock List, resetting to 0"); - $this->resetMock(); - } - if (!is_numeric($this->mockFiles[$this->mockIndex])){ - $this->log("fetchMockResponse only works with response code numbers",'Warning'); - return false; - } - - $r = array(); - $r['head'] = 'HTTP/1.1 200 OK'; - $r['body'] = ''; - $r['code'] = $this->mockFiles[$this->mockIndex]; - $this->mockIndex++; - if ($r['code'] == 200){ - $r['answer'] = 'OK'; - $r['ok'] = 1; - } else if ($r['code'] == 404){ - $r['answer'] = 'Not Found'; - $r['error'] = 'Not Found'; - $r['ok'] = 0; - } else if ($r['code'] == 503){ - $r['answer'] = 'Service Unavailable'; - $r['error'] = 'Service Unavailable'; - $r['ok'] = 0; - } else if ($r['code'] == 400){ - $r['answer'] = 'Bad Request'; - $r['error'] = 'Bad Request'; - $r['ok'] = 0; - } - - if ($r['code'] != 200){ - $r['body'] = ' - - - Sender - '.$r['error'].' - '.$r['answer'].' - - 123 -'; - } - - - $r['headarray'] = array(); - $this->log("Returning Mock Response: ".$r['code']); - return $r; - } - - /** - * Checks whether or not the response is OK. - * - * Verifies whether or not the HTTP response has the 200 OK code. If the code - * is not 200, the incident and error message returned are logged. - * @param array $r

    The HTTP response array. Expects the array to have - * the fields code, body, and error.

    - * @return boolean TRUE if the status is 200 OK, FALSE otherwise. - */ - protected function checkResponse($r){ - if (!is_array($r) || !array_key_exists('code', $r)){ - $this->log("No Response found",'Warning'); - return false; - } - if ($r['code'] == 200){ - return true; - } else { - $xml = simplexml_load_string($r['body'])->Error; - $this->log("Bad Response! ".$r['code']." ".$r['error'].": ".$xml->Code." - ".$xml->Message,'Urgent'); - return false; - } - } - - /** - * Set the config file. - * - * This method can be used to change the config file after the object has - * been initiated. The file will not be set if it cannot be found or read. - * This is useful for testing, in cases where you want to use a different file. - * @param string $path

    The path to the config file.

    - * @throws Exception If the file cannot be found or read. - */ - public function setConfig($path){ - if (file_exists($path) && is_readable($path)){ - include($path); - $this->config = $path; - $this->setLogPath($logpath); - if (isset($AMAZON_SERVICE_URL)) - $this->urlbase = $AMAZON_SERVICE_URL; - } else { - throw new Exception("Config file does not exist or cannot be read! ($path)"); - } - } - - /** - * Set the log file path. - * - * Use this method to change the log file used. This method is called - * each time the config file is changed. - * @param string $path

    The path to the log file.

    - * @throws Exception If the file cannot be found or read. - */ - public function setLogPath($path){ - if (file_exists($path) && is_readable($path)){ - $this->logpath = $path; - } else { - throw new Exception("Log file does not exist or cannot be read! ($path)"); - } - - } - - /** - * Sets the store values. - * - * This method sets a number of key values from the config file. These values - * include your Merchant ID, Access Key ID, and Secret Key, and are critical - * for making requests with Amazon. If the store cannot be found in the - * config file, or if any of the key values are missing, - * the incident will be logged. - * @param string $s

    The store name to look for.

    - * @throws Exception If the file can't be found. - */ - public function setStore($s){ - if (file_exists($this->config)){ - include($this->config); - } else { - throw new Exception("Config file does not exist!"); - } - - if(array_key_exists($s, $store)){ - $this->storeName = $s; - if(array_key_exists('merchantId', $store[$s])){ - $this->options['SellerId'] = $store[$s]['merchantId']; - } else { - $this->log("Merchant ID is missing!",'Warning'); - } - if(array_key_exists('keyId', $store[$s])){ - $this->options['AWSAccessKeyId'] = $store[$s]['keyId']; - } else { - $this->log("Access Key ID is missing!",'Warning'); - } - if(!array_key_exists('secretKey', $store[$s])){ - $this->log("Secret Key is missing!",'Warning'); - } - - } else { - $this->log("Store $s does not exist!",'Warning'); - } - } - - /** - * Enables or disables the throttle stop. - * - * When the throttle stop is enabled, throttled requests will not be repeated. - * This setting is off by default. - * @param boolean $b

    Defaults to TRUE.

    - */ - public function setThrottleStop($b=true) { - $this->throttleStop=!empty($b); - } - - /** - * Writes a message to the log. - * - * This method adds a message line to the log file defined by the config. - * This includes the priority level, user IP, and a backtrace of the call. - * @param string $msg

    The message to write to the log.

    - * @param string $level [optional]

    The priority level of the message. - * This is merely for the benefit of the user and does not affect how - * the code runs. The values used in this library are "Info", "Warning", - * "Urgent", and "Throttle".

    - * @return boolean FALSE if the message is empty, NULL if logging is muted - * @throws Exception If the file can't be written to. - */ - protected function log($msg, $level = 'Info'){ - if ($msg != false) { - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - - if (file_exists($this->config)){ - include($this->config); - } else { - throw new Exception("Config file does not exist!"); - } - if (isset($logfunction) && $logfunction != '' && function_exists($logfunction)){ - switch ($level){ - case('Info'): $loglevel = LOG_INFO; break; - case('Throttle'): $loglevel = LOG_INFO; break; - case('Warning'): $loglevel = LOG_NOTICE; break; - case('Urgent'): $loglevel = LOG_ERR; break; - default: $loglevel = LOG_INFO; - } - call_user_func($logfunction,$msg,$loglevel); - } - - if (isset($muteLog) && $muteLog == true){ - return; - } - - if(isset($userName) && $userName != ''){ - $name = $userName; - }else{ - $name = 'guest'; - } - - if(isset($backtrace) && isset($backtrace[1]) && isset($backtrace[1]['file']) && isset($backtrace[1]['line']) && isset($backtrace[1]['function'])){ - $fileName = basename($backtrace[1]['file']); - $file = $backtrace[1]['file']; - $line = $backtrace[1]['line']; - $function = $backtrace[1]['function']; - }else{ - $fileName = basename($backtrace[0]['file']); - $file = $backtrace[0]['file']; - $line = $backtrace[0]['line']; - $function = $backtrace[0]['function']; - } - if(isset($_SERVER['REMOTE_ADDR'])){ - $ip = $_SERVER['REMOTE_ADDR']; - if($ip == '127.0.0.1')$ip = 'local';//save some char - }else{ - $ip = 'cli'; - } - if (!file_exists($this->logpath)) { - //attempt to create the file if it does not exist - file_put_contents($this->logpath, "This is the Amazon log, for Amazon classes to use.\n"); - } - if (file_exists($this->logpath) && is_writable($this->logpath)){ - $str = "[$level][" . date("Y/m/d h:i:s", mktime()) . " $name@$ip $fileName:$line $function] " . $msg; - $fd = fopen($this->logpath, "a+"); - fwrite($fd,$str . "\r\n"); - fclose($fd); - } else { - throw new Exception('Error! Cannot write to log! ('.$this->logpath.')'); - } - } else { - return false; - } - } - - /** - * Returns options array. - * - * Gets the options for the object, for debugging or recording purposes. - * Note that this also includes key information such as your Amazon Access Key ID. - * @return array All of the options for the object. - */ - public function getOptions(){ - return $this->options; - } - - /** - * Generates timestamp in ISO8601 format. - * - * This method creates a timestamp from the provided string in ISO8601 format. - * The string given is passed through strtotime before being used. The - * value returned is actually two minutes early, to prevent it from tripping up - * Amazon. If no time is given, the current time is used. - * @param string $time [optional]

    The time to use. Since this value is - * passed through strtotime first, values such as "-1 hour" are fine. - * Defaults to the current time.

    - * @return string Unix timestamp of the time, minus 2 minutes. - */ - protected function genTime($time=false){ - if (!$time){ - $time = time(); - } else { - $time = strtotime($time); - - } - return date('Y-m-d\TH:i:sO',$time-120); - - } - - /** - * Handles generation of the signed query string. - * - * This method uses the secret key from the config file to generate the - * signed query string. - * It also handles the creation of the timestamp option prior. - * @return string query string to send to cURL - * @throws Exception if config file or secret key is missing - */ - protected function genQuery(){ - if (file_exists($this->config)){ - include($this->config); - } else { - throw new Exception("Config file does not exist!"); - } - - if (array_key_exists($this->storeName, $store) && array_key_exists('secretKey', $store[$this->storeName])){ - $secretKey = $store[$this->storeName]['secretKey']; - } else { - throw new Exception("Secret Key is missing!"); - } - - unset($this->options['Signature']); - $this->options['Timestamp'] = $this->genTime(); - $this->options['Signature'] = $this->_signParameters($this->options, $secretKey); - return $this->_getParametersAsString($this->options); - } - - /** - * Sends a request to Amazon via cURL - * - * This method will keep trying if the request was throttled. - * @param string $url

    URL to feed to cURL

    - * @param array $param

    parameter array to feed to cURL

    - * @return array cURL response array - */ - protected function sendRequest($url,$param){ - $this->log("Making request to Amazon: ".$this->options['Action']); - $response = $this->fetchURL($url,$param); - - while ($response['code'] == '503' && $this->throttleStop==false){ - $this->sleep(); - $response = $this->fetchURL($url,$param); - } - - $this->rawResponses[]=$response; - return $response; - } - - /** - * Gives the latest response data received from Amazon. - * Response arrays contain the following keys: - * - * @param int $i [optional]

    If set, retrieves the specific response instead of the last one. - * If the index for the response is not used, FALSE will be returned.

    - * @return array associative array of HTTP response or FALSE if not set yet - */ - public function getLastResponse($i=NULL) { - if (!isset($i)) { - $i=count($this->rawResponses)-1; - } - if ($i >= 0 && isset($this->rawResponses[$i])) { - return $this->rawResponses[$i]; - } else { - return false; - } - } - - /** - * Gives all response code received from Amazon. - * @return array list of associative arrays of HTTP response or FALSE if not set yet - * @see getLastResponse - */ - public function getRawResponses() { - if (!empty($this->rawResponses)) { - return $this->rawResponses; - } else { - return false; - } - } - - /** - * Sleeps for the throttle time and records to the log. - */ - protected function sleep(){ - flush(); - $s = ($this->throttleTime == 1) ? '' : 's'; - $this->log("Request was throttled, Sleeping for ".$this->throttleTime." second$s",'Throttle'); - sleep($this->throttleTime); - } - - /** - * Checks for a token and changes the proper options - * @param SimpleXMLObject $xml

    response data

    - * @return boolean FALSE if no XML data - */ - protected function checkToken($xml){ - if (!$xml){ - return false; - } - if ($xml->NextToken){ - $this->tokenFlag = true; - $this->options['NextToken'] = (string)$xml->NextToken; - } else { - unset($this->options['NextToken']); - $this->tokenFlag = false; - } - } - - //Functions from Athena: - /** - * Get url or send POST data - * @param string $url - * @param array $param['Header'] - * $param['Post'] - * @return array $return['ok'] 1 - success, (0,-1) - fail - * $return['body'] - response - * $return['error'] - error, if "ok" is not 1 - * $return['head'] - http header - */ - function fetchURL ($url, $param) { - $return = array(); - - $ch = curl_init(); - - curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch,CURLOPT_TIMEOUT, 0); - curl_setopt($ch,CURLOPT_FORBID_REUSE, 1); - curl_setopt($ch,CURLOPT_FRESH_CONNECT, 1); - curl_setopt($ch,CURLOPT_HEADER, 1); - curl_setopt($ch,CURLOPT_URL,$url); - if (!empty($param)){ - if (!empty($param['Header'])){ - curl_setopt($ch,CURLOPT_HTTPHEADER, $param['Header']); - } - if (!empty($param['Post'])){ - curl_setopt($ch,CURLOPT_POSTFIELDS, $param['Post']); - } - } - - $data = curl_exec($ch); - if ( curl_errno($ch) ) { - $return['ok'] = -1; - $return['error'] = curl_error($ch); - return $return; - } - - if (is_numeric(strpos($data, 'HTTP/1.1 100 Continue'))) { - $data=str_replace('HTTP/1.1 100 Continue', '', $data); - } - $data = preg_split("/\r\n\r\n/",$data, 2, PREG_SPLIT_NO_EMPTY); - if (!empty($data)) { - $return['head'] = ( isset($data[0]) ? $data[0] : null ); - $return['body'] = ( isset($data[1]) ? $data[1] : null ); - } else { - $return['head'] = null; - $return['body'] = null; - } - - $matches = array(); - $data = preg_match("/HTTP\/[0-9.]+ ([0-9]+) (.+)\r\n/",$return['head'], $matches); - if (!empty($matches)) { - $return['code'] = $matches[1]; - $return['answer'] = $matches[2]; - } - - $data = preg_match("/meta http-equiv=.refresh. +content=.[0-9]*;url=([^'\"]*)/i",$return['body'], $matches); - if (!empty($matches)) { - $return['location'] = $matches[1]; - $return['code'] = '301'; - } - - if ( $return['code'] == '200' || $return['code'] == '302' ) { - $return['ok'] = 1; - } else { - $return['error'] = (($return['answer'] and $return['answer'] != 'OK') ? $return['answer'] : 'Something wrong!'); - $return['ok'] = 0; - } - - foreach (preg_split('/\n/', $return['head'], -1, PREG_SPLIT_NO_EMPTY) as $value) { - $data = preg_split('/:/', $value, 2, PREG_SPLIT_NO_EMPTY); - if (is_array($data) and isset($data['1'])) { - $return['headarray'][$data['0']] = trim($data['1']); - } - } - - curl_close($ch); - - return $return; - } - // End Functions from Athena - - // Functions from Amazon: - /** - * Reformats the provided string using rawurlencode while also replacing ~, copied from Amazon - * - * Almost the same as using rawurlencode - * @param string $value - * @return string - */ - protected function _urlencode($value) { - return rawurlencode($value); - return str_replace('%7E', '~', rawurlencode($value)); - } - - /** - * Fuses all of the parameters together into a string, copied from Amazon - * @param array $parameters - * @return string - */ - protected function _getParametersAsString(array $parameters) { - $queryParameters = array(); - foreach ($parameters as $key => $value) { - $queryParameters[] = $key . '=' . $this->_urlencode($value); - } - return implode('&', $queryParameters); - } - - /** - * validates signature and sets up signing of them, copied from Amazon - * @param array $parameters - * @param string $key - * @return string signed string - * @throws Exception - */ - protected function _signParameters(array $parameters, $key) { - $algorithm = $this->options['SignatureMethod']; - $stringToSign = null; - if (2 === $this->options['SignatureVersion']) { - $stringToSign = $this->_calculateStringToSignV2($parameters); -// var_dump($stringToSign); - } else { - throw new Exception("Invalid Signature Version specified"); - } - return $this->_sign($stringToSign, $key, $algorithm); - } - - /** - * generates the string to sign, copied from Amazon - * @param array $parameters - * @return type - */ - protected function _calculateStringToSignV2(array $parameters) { - $data = 'POST'; - $data .= "\n"; - $endpoint = parse_url ($this->urlbase.$this->urlbranch); - $data .= $endpoint['host']; - $data .= "\n"; - $uri = array_key_exists('path', $endpoint) ? $endpoint['path'] : null; - if (!isset ($uri)) { - $uri = "/"; - } - $uriencoded = implode("/", array_map(array($this, "_urlencode"), explode("/", $uri))); - $data .= $uriencoded; - $data .= "\n"; - uksort($parameters, 'strcmp'); - $data .= $this->_getParametersAsString($parameters); - return $data; - } - /** - * Runs the hash, copied from Amazon - * @param string $data - * @param string $key - * @param string $algorithm 'HmacSHA1' or 'HmacSHA256' - * @return string - * @throws Exception - */ - protected function _sign($data, $key, $algorithm) - { - if ($algorithm === 'HmacSHA1') { - $hash = 'sha1'; - } else if ($algorithm === 'HmacSHA256') { - $hash = 'sha256'; - } else { - throw new Exception ("Non-supported signing method specified"); - } - - return base64_encode( - hash_hmac($hash, $data, $key, true) - ); - } - - // -- End Functions from Amazon -- - -} - -?> diff --git a/includes/classes/AmazonFeedResult.php b/includes/classes/AmazonFeedResult.php deleted file mode 100644 index cd008455..00000000 --- a/includes/classes/AmazonFeedResult.php +++ /dev/null @@ -1,146 +0,0 @@ -Name for the store you want to use.

    - * @param string $id [optional]

    The Feed Submission ID to set for the object.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $id = null, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); - include($this->env); - - if($id){ - $this->options['FeedSubmissionId'] = $id; - } - - $this->options['Action'] = 'GetFeedSubmissionResult'; - - if(isset($THROTTLE_LIMIT_FEEDRESULT)) { - $this->throttleLimit = $THROTTLE_LIMIT_FEEDRESULT; - } - if(isset($THROTTLE_TIME_FEEDRESULT)) { - $this->throttleTime = $THROTTLE_TIME_FEEDRESULT; - } - $this->throttleGroup = 'GetFeedSubmissionResult'; - } - - /** - * Sets the feed submission ID for the next request. (Required) - * - * This method sets the feed submission ID to be sent in the next request. This - * parameter is required in order to retrieve a feed from Amazon. - * @param string|integer $n

    Must be numeric

    - * @return boolean FALSE if improper input - */ - public function setFeedId($n){ - if (is_numeric($n)){ - $this->options['FeedSubmissionId'] = $n; - } else { - return false; - } - } - - /** - * Sends a request to Amazon for a feed. - * - * Submits a GetFeedSubmissionResult request to Amazon. In order to - * do this, a feed submission ID is required. Amazon will send back the raw results - * of the feed as a response, which can be saved to a file using saveFeed. - * @return boolean FALSE if something goes wrong - */ - public function fetchFeedResult(){ - if (!array_key_exists('FeedSubmissionId',$this->options)){ - $this->log("Feed Submission ID must be set in order to fetch it!",'Warning'); - return false; - } - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $this->rawFeed = $this->fetchMockFile(false); - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $this->rawFeed = $response['body']; - } - - } - - /** - * Saves the raw report data to a path you specify. - * - * This method will record in the log whether or not the save was successful. - * @param string $path

    path for the file to save the feed data in

    - * @return boolean FALSE if something goes wrong - */ - public function saveFeed($path){ - if (!isset($this->rawFeed)){ - return false; - } - try{ - file_put_contents($path,$this->rawFeed); - $this->log("Successfully saved feed #".$this->options['FeedSubmissionId']." at $path"); - } catch (Exception $e){ - $this->log("Unable to save feed #".$this->options['FeedSubmissionId']." at $path: ".$e->getMessage(),'Urgent'); - return false; - } - } - - /** - * Returns the entire raw report data. - * - * This is useful for handling the report with an external file management system. - * @return string|boolean The raw report data as a string, or FALSE if there is no data - */ - public function getRawFeed() { - if (!isset($this->rawFeed)){ - return false; - } - return $this->rawFeed; - } - -} -?> \ No newline at end of file diff --git a/includes/classes/AmazonFeedsCore.php b/includes/classes/AmazonFeedsCore.php deleted file mode 100644 index 249d4456..00000000 --- a/includes/classes/AmazonFeedsCore.php +++ /dev/null @@ -1,49 +0,0 @@ -Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); - include($this->env); - - $this->urlbranch = ''; - if(isset($AMAZON_VERSION_FEEDS)) { - $this->options['Version'] = $AMAZON_VERSION_FEEDS; - } - } -} -?> diff --git a/includes/classes/AmazonFulfillmentOrder.php b/includes/classes/AmazonFulfillmentOrder.php deleted file mode 100644 index d0b099eb..00000000 --- a/includes/classes/AmazonFulfillmentOrder.php +++ /dev/null @@ -1,300 +0,0 @@ -AmazonFulfillmentPreview object. - */ -class AmazonFulfillmentOrder extends AmazonOutboundCore{ - private $order; - - /** - * AmazonFulfillmentOrder fetches a fulfillment order from Amazon. You need a Fulfillment Order ID. - * - * The parameters are passed to the parent constructor, which are - * in turn passed to the AmazonCore constructor. See it for more information - * on these parameters and common methods. - * Please note that an extra parameter comes before the usual Mock Mode parameters, - * so be careful when setting up the object. - * @param string $s

    Name for the store you want to use.

    - * @param string $id [optional]

    The Fulfillment Order ID to set for the object.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $id = null, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - - if($id){ - $this->setOrderId($id); - } - } - - /** - * Sets the fulfillment order ID. (Required) - * - * This method sets the Fulfillment Order ID to be sent in the next request. - * This parameter is required for fetching the fulfillment order from Amazon. - * @param string $s

    Maximum 40 characters.

    - * @return boolean FALSE if improper input - */ - public function setOrderId($s){ - if (is_string($s)){ - $this->options['SellerFulfillmentOrderId'] = $s; - } else { - return false; - } - } - - /** - * Fetches data on a fulfillment order from Amazon. - * - * Submits a GetFulfillmentOrder request to Amazon. In order to do this, - * a fulfillment order ID is required. Amazon will send - * the data back as a response, which can be retrieved using getOrder. - * @return boolean FALSE if something goes wrong - */ - public function fetchOrder(){ - if (!array_key_exists('SellerFulfillmentOrderId',$this->options)){ - $this->log("Fulfillment Order ID must be set in order to fetch it!",'Warning'); - return false; - } - - $this->options['Action'] = 'GetFulfillmentOrder'; - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->parseXML($xml); - } - - /** - * Parses XML response into array. - * - * This is what reads the response XML and converts it into an array. - * @param SimpleXMLObject $xml

    The XML response from Amazon.

    - * @return boolean FALSE if no XML data is found - */ - protected function parseXML($xml) { - if (!$xml){ - return false; - } - if (!$xml->FulfillmentOrder){ - return false; - } - if (!$xml->FulfillmentOrderItem){ - return false; - } - if (!$xml->FulfillmentShipment){ - return false; - } - //Section 1: ShipmentOrder - $d = $xml->FulfillmentOrder; - $this->order['Details']['SellerFulfillmentOrderId'] = (string)$d->SellerFulfillmentOrderId; - $this->order['Details']['DisplayableOrderId'] = (string)$d->DisplayableOrderId; - $this->order['Details']['DisplayableOrderDateTime'] = (string)$d->DisplayableOrderDateTime; - $this->order['Details']['DisplayableOrderComment'] = (string)$d->DisplayableOrderComment; - $this->order['Details']['ShippingSpeedCategory'] = (string)$d->ShippingSpeedCategory; - //Address - $this->order['Details']['DestinationAddress']['Name'] = (string)$d->DestinationAddress->Name; - $this->order['Details']['DestinationAddress']['Line1'] = (string)$d->DestinationAddress->Line1; - if (isset($d->DestinationAddress->Line2)){ - $this->order['Details']['DestinationAddress']['Line2'] = (string)$d->DestinationAddress->Line2; - } - if (isset($d->DestinationAddress->Line3)){ - $this->order['Details']['DestinationAddress']['Line3'] = (string)$d->DestinationAddress->Line3; - } - if (isset($d->DestinationAddress->DistrictOrCounty)){ - $this->order['Details']['DestinationAddress']['DistrictOrCounty'] = (string)$d->DestinationAddress->DistrictOrCounty; - } - $this->order['Details']['DestinationAddress']['City'] = (string)$d->DestinationAddress->City; - $this->order['Details']['DestinationAddress']['StateOrProvinceCode'] = (string)$d->DestinationAddress->StateOrProvinceCode; - $this->order['Details']['DestinationAddress']['CountryCode'] = (string)$d->DestinationAddress->CountryCode; - if (isset($d->DestinationAddress->PostalCode)){ - $this->order['Details']['DestinationAddress']['PostalCode'] = (string)$d->DestinationAddress->PostalCode; - } - if (isset($d->DestinationAddress->PhoneNumber)){ - $this->order['Details']['DestinationAddress']['PhoneNumber'] = (string)$d->DestinationAddress->PhoneNumber; - } - //End of Address - if (isset($d->FulfillmentPolicy)){ - $this->order['Details']['FulfillmentPolicy'] = (string)$d->FulfillmentPolicy; - } - if (isset($d->FulfillmentMethod)){ - $this->order['Details']['FulfillmentMethod'] = (string)$d->FulfillmentMethod; - } - $this->order['Details']['ReceivedDateTime'] = (string)$d->ReceivedDateTime; - $this->order['Details']['FulfillmentOrderStatus'] = (string)$d->FulfillmentOrderStatus; - $this->order['Details']['StatusUpdatedDateTime'] = (string)$d->StatusUpdatedDateTime; - if (isset($d->NotificationEmailList)){ - $i = 0; - foreach($d->NotificationEmailList->children() as $x){ - $this->order['Details']['NotificationEmailList'][$i++] = (string)$x; - } - } - - //Section 2: Order Items - $i = 0; - foreach($xml->FulfillmentOrderItem->children() as $x){ - $this->order['Items'][$i]['SellerSKU'] = (string)$x->SellerSKU; - $this->order['Items'][$i]['SellerFulfillmentOrderItemId'] = (string)$x->SellerFulfillmentOrderItemId; - $this->order['Items'][$i]['Quantity'] = (string)$x->Quantity; - if (isset($x->GiftMessage)){ - $this->order['Items'][$i]['GiftMessage'] = (string)$x->GiftMessage; - } - if (isset($x->DisplayableComment)){ - $this->order['Items'][$i]['DisplayableComment'] = (string)$x->DisplayableComment; - } - if (isset($x->FulfillmentNetworkSKU)){ - $this->order['Items'][$i]['FulfillmentNetworkSKU'] = (string)$x->FulfillmentNetworkSKU; - } - if (isset($x->OrderItemDisposition)){ - $this->order['Items'][$i]['OrderItemDisposition'] = (string)$x->OrderItemDisposition; - } - $this->order['Items'][$i]['CancelledQuantity'] = (string)$x->CancelledQuantity; - $this->order['Items'][$i]['UnfulfillableQuantity'] = (string)$x->UnfulfillableQuantity; - if (isset($x->EstimatedShipDateTime)){ - $this->order['Items'][$i]['EstimatedShipDateTime'] = (string)$x->EstimatedShipDateTime; - } - if (isset($x->EstimatedArrivalDateTime)){ - $this->order['Items'][$i]['EstimatedArrivalDateTime'] = (string)$x->EstimatedArrivalDateTime; - } - if (isset($x->PerUnitDeclaredValue)){ - $this->order['Items'][$i]['PerUnitDeclaredValue']['CurrencyCode'] = (string)$x->PerUnitDeclaredValue->CurrencyCode; - $this->order['Items'][$i]['PerUnitDeclaredValue']['Value'] = (string)$x->PerUnitDeclaredValue->Value; - } - $i++; - } - - //Section 3: Order Shipments - $i = 0; - foreach($xml->FulfillmentShipment->children() as $x){ - $this->order['Shipments'][$i]['AmazonShipmentId'] = (string)$x->AmazonShipmentId; - $this->order['Shipments'][$i]['FulfillmentCenterId'] = (string)$x->FulfillmentCenterId; - $this->order['Shipments'][$i]['FulfillmentShipmentStatus'] = (string)$x->FulfillmentShipmentStatus; - if (isset($x->ShippingDateTime)){ - $this->order['Shipments'][$i]['ShippingDateTime'] = (string)$x->ShippingDateTime; - } - if (isset($x->EstimatedArrivalDateTime)){ - $this->order['Shipments'][$i]['EstimatedArrivalDateTime'] = (string)$x->EstimatedArrivalDateTime; - } - //FulfillmentShipmentItem - $j = 0; - foreach ($x->FulfillmentShipmentItem->children() as $y){ - if (isset($y->SellerSKU)){ - $this->order['Shipments'][$i]['FulfillmentShipmentItem'][$j]['SellerSKU'] = (string)$y->SellerSKU; - } - $this->order['Shipments'][$i]['FulfillmentShipmentItem'][$j]['SellerFulfillmentOrderItemId'] = (string)$y->SellerFulfillmentOrderItemId; - $this->order['Shipments'][$i]['FulfillmentShipmentItem'][$j]['Quantity'] = (string)$y->Quantity; - if (isset($y->PackageNumber)){ - $this->order['Shipments'][$i]['FulfillmentShipmentItem'][$j]['PackageNumber'] = (string)$y->PackageNumber; - } - $j++; - } - if (isset($x->FulfillmentShipmentPackage)){ - $j = 0; - foreach ($x->FulfillmentShipmentPackage->children() as $y){ - $this->order['Shipments'][$i]['FulfillmentShipmentPackage'][$j]['PackageNumber'] = (string)$y->PackageNumber; - $this->order['Shipments'][$i]['FulfillmentShipmentPackage'][$j]['CarrierCode'] = (string)$y->CarrierCode; - if (isset($y->TrackingNumber)){ - $this->order['Shipments'][$i]['FulfillmentShipmentPackage'][$j]['TrackingNumber'] = (string)$y->TrackingNumber; - } - if (isset($y->EstimatedArrivalDateTime)){ - $this->order['Shipments'][$i]['FulfillmentShipmentPackage'][$j]['EstimatedArrivalDateTime'] = (string)$y->EstimatedArrivalDateTime; - } - $j++; - } - } - - $i++; - } - } - - /** - * Cancels a fulfillment order on Amazon. - * - * Submits a CancelFulfillmentOrder request to Amazon. In order to do this, - * a fulfillment order ID is required. Amazon will send back an HTTP response, - * so there is no data to retrieve afterwards. - * @return boolean TRUE if the cancellation was successful, FALSE if something goes wrong - */ - public function cancelOrder(){ - if (!array_key_exists('SellerFulfillmentOrderId',$this->options)){ - $this->log("Fulfillment Order ID must be set in order to cancel it!",'Warning'); - return false; - } - - $this->options['Action'] = 'CancelFulfillmentOrder'; - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $response = $this->fetchMockResponse(); - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - } - if (!$this->checkResponse($response)){ - return false; - } else { - $this->log("Successfully deleted Fulfillment Order ".$this->options['SellerFulfillmentOrderId']); - return true; - } - } - - /** - * Returns the full order information. - * - * This method will return FALSE if the data has not yet been filled. - * The array returned will have the following fields: - * - * @return array|boolean data array, or FALSE if data not filled yet - */ - public function getOrder(){ - if (isset($this->order)){ - return $this->order; - } else { - return false; - } - } -} -?> diff --git a/includes/classes/AmazonFulfillmentOrderCreator.php b/includes/classes/AmazonFulfillmentOrderCreator.php deleted file mode 100644 index f1993d14..00000000 --- a/includes/classes/AmazonFulfillmentOrderCreator.php +++ /dev/null @@ -1,435 +0,0 @@ -AmazonFulfillmentPreview object. - */ -class AmazonFulfillmentOrderCreator extends AmazonOutboundCore{ - - /** - * AmazonFulfillmentOrderCreator creates a fulfillment order. You need a fulfillment order ID. - * - * The parameters are passed to the parent constructor, which are - * in turn passed to the AmazonCore constructor. See it for more information - * on these parameters and common methods. - * @param string $s

    Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - - $this->options['Action'] = 'CreateFulfillmentOrder'; - } - - /** - * Sets the fulfillment order ID. (Required) - * - * This method sets the Fulfillment Order ID to be sent in the next request. - * This parameter is required for creating a fulfillment order with Amazon. - * A fulfillment order ID can be generated using the AmazonFulfillmentPreview object. - * @param string $s

    Maximum 40 characters.

    - * @return boolean FALSE if improper input - */ - public function setFulfillmentOrderId($s){ - if (is_string($s)){ - $this->options['SellerFulfillmentOrderId'] = $s; - } else { - return false; - } - } - - /** - * Sets the displayed order ID. (Required) - * - * This method sets the Displayable Order ID to be sent in the next request. - * This parameter is required for creating a fulfillment order with Amazon. - * This is your own order ID, and is the ID that is displayed on the packing slip. - * @param string $s

    Must be alpha-numeric or ISO-8559-1 compliant. Maximum 40 characters.

    - * @return boolean FALSE if improper input - */ - public function setDisplayableOrderId($s){ - if (is_string($s)){ - $this->options['DisplayableOrderId'] = $s; - } else { - return false; - } - } - - /** - * Sets the displayed timestamp. (Required) - * - * This method sets the displayed timestamp to be sent in the next request. - * This parameter is required for creating a fulfillment order with Amazon. - * The parameter is passed through strtotime, so values such as "-1 hour" are fine. - * @param string $s

    Time string.

    - * @return boolean FALSE if improper input - */ - public function setDate($s){ - if (is_string($s)){ - $time = $this->genTime($s); - $this->options['DisplayableOrderDateTime'] = $time; - } else { - return false; - } - } - - /** - * Sets the displayed comment. (Required) - * - * This method sets the displayed order comment to be sent in the next request. - * This parameter is required for creating a fulfillment order with Amazon. - * @param string $s

    Maximum 1000 characters.

    - * @return boolean FALSE if improper input - */ - public function setComment($s){ - if (is_string($s)){ - $this->options['DisplayableOrderComment'] = $s; - } else { - return false; - } - } - - /** - * Sets the shipping speed. (Required) - * - * This method sets the shipping speed to be sent in the next request. - * This parameter is required for creating a fulfillment order with Amazon. - * @param string $s

    "Standard", "Expedited", or "Priority"

    - * @return boolean FALSE if improper input - */ - public function setShippingSpeed($s){ - if (is_string($s)){ - if ($s == 'Standard' || $s == 'Expedited' || $s == 'Priority'){ - $this->options['ShippingSpeedCategory'] = $s; - } else { - $this->log("Tried to set shipping status to invalid value",'Warning'); - return false; - } - } else { - return false; - } - } - - /** - * Sets the address. (Required) - * - * This method sets the destination address to be sent in the next request. - * This parameter is required for creating a fulfillment order with Amazon. - * The array provided should have the following fields: - * - * @param array $a

    See above.

    - * @return boolean FALSE if improper input - */ - public function setAddress($a){ - if (is_null($a) || is_string($a) || !$a){ - $this->log("Tried to set address to invalid values",'Warning'); - return false; - } - $this->resetAddress(); - $this->options['DestinationAddress.Name'] = $a['Name']; - $this->options['DestinationAddress.Line1'] = $a['Line1']; - if (array_key_exists('Line2', $a)){ - $this->options['DestinationAddress.Line2'] = $a['Line2']; - } else { - $this->options['DestinationAddress.Line2'] = null; - } - if (array_key_exists('Line3', $a)){ - $this->options['DestinationAddress.Line3'] = $a['Line3']; - } else { - $this->options['DestinationAddress.Line3'] = null; - } - if (array_key_exists('DistrictOrCounty', $a)){ - $this->options['DestinationAddress.DistrictOrCounty'] = $a['DistrictOrCounty']; - } else { - $this->options['DestinationAddress.DistrictOrCounty'] = null; - } - $this->options['DestinationAddress.City'] = $a['City']; - $this->options['DestinationAddress.StateOrProvidenceCode'] = $a['StateOrProvidenceCode']; - $this->options['DestinationAddress.CountryCode'] = $a['CountryCode']; - $this->options['DestinationAddress.PostalCode'] = $a['PostalCode']; - if (array_key_exists('PhoneNumber', $a)){ - $this->options['DestinationAddress.PhoneNumber'] = $a['PhoneNumber']; - } else { - $this->options['DestinationAddress.PhoneNumber'] = null; - } - } - - /** - * Resets the address options. - * - * Since address is a required parameter, these options should not be removed - * without replacing them, so this method is not public. - */ - protected function resetAddress(){ - unset($this->options['DestinationAddress.Name']); - unset($this->options['DestinationAddress.Line1']); - unset($this->options['DestinationAddress.Line2']); - unset($this->options['DestinationAddress.Line3']); - unset($this->options['DestinationAddress.DistrictOrCounty']); - unset($this->options['DestinationAddress.City']); - unset($this->options['DestinationAddress.StateOrProvidenceCode']); - unset($this->options['DestinationAddress.CountryCode']); - unset($this->options['DestinationAddress.PostalCode']); - unset($this->options['DestinationAddress.PhoneNumber']); - } - - /** - * Sets the fulfillment policy. (Optional) - * - * This method sets the Fulfillment Policy to be sent in the next request. - * If this parameter is not set, Amazon will assume a FillOrKill policy. - * Here is a quick description of the policies: - * - * @param string $s

    "FillOrKill", "FillAll", or "FillAllAvailable"

    - * @return boolean FALSE if improper input - */ - public function setFulfillmentPolicy($s){ - if (is_string($s)){ - if ($s == 'FillOrKill' || $s == 'FillAll' || $s == 'FillAllAvailable'){ - $this->options['FulfillmentPolicy'] = $s; - } else { - $this->log("Tried to set fulfillment policy to invalid value",'Warning'); - return false; - } - } else { - return false; - } - } - - /** - * Sets the fulfillment method. (Optional) - * - * This method sets the Fulfillment Method to be sent in the next request. - * If this parameter is not set, Amazon will assume a Consumer method. - * Here is a quick description of the methods: - * - * @param string $s

    "Consumer" or "Removal"

    - * @return boolean FALSE if improper input - */ - public function setFulfillmentMethod($s){ - if (is_string($s)){ - if ($s == 'Consumer' || $s == 'Removal'){ - $this->options['FulfillmentMethod'] = $s; - } else { - $this->log("Tried to set fulfillment method to invalid value",'Warning'); - return false; - } - } else { - return false; - } - } - - /** - * Sets the email(s). (Optional) - * - * This method sets the list of Email addresses to be sent in the next request. - * Setting this parameter tells Amazon who to send emails to regarding the - * completion of the shipment. - * @param array|string $s

    A list of email addresses, or a single email address. (max: 64 chars each)

    - * @return boolean FALSE if improper input - */ - public function setEmails($s){ - if (is_string($s)){ - $this->resetEmails(); - $this->options['NotificationEmailList.member.1'] = $s; - } else if (is_array($s) && $s){ - $this->resetEmails(); - $i = 1; - foreach ($s as $x){ - $this->options['NotificationEmailList.member.'.$i] = $x; - $i++; - } - } else { - return false; - } - } - - /** - * Removes email options. - * - * Use this in case you change your mind and want to remove the email - * parameters you previously set. - */ - public function resetEmails(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#NotificationEmailList#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets the items. (Required) - * - * This method sets the Fulfillment Order ID to be sent in the next request. - * This parameter is required for creating a fulfillment order with Amazon. - * The array provided should contain a list of arrays, each with the following fields: - * - * @param array $a

    See above.

    - * @return boolean FALSE if improper input - */ - public function setItems($a){ - if (is_null($a) || is_string($a) || !$a){ - $this->log("Tried to set Items to invalid values",'Warning'); - return false; - } - $this->resetItems(); - $i = 1; - foreach ($a as $x){ - if (is_array($x) && array_key_exists('SellerSKU', $x) && array_key_exists('SellerFulfillmentOrderItemId', $x) && array_key_exists('Quantity', $x)){ - $this->options['Items.member.'.$i.'.SellerSKU'] = $x['SellerSKU']; - $this->options['Items.member.'.$i.'.SellerFulfillmentOrderItemId'] = $x['SellerFulfillmentOrderItemId']; - $this->options['Items.member.'.$i.'.Quantity'] = $x['Quantity']; - if (array_key_exists('GiftMessage', $x)){ - $this->options['Items.member.'.$i.'.GiftMessage'] = $x['GiftMessage']; - } - if (array_key_exists('Comment', $x)){ - $this->options['Items.member.'.$i.'.DisplayableComment'] = $x['Comment']; - } - if (array_key_exists('FulfillmentNetworkSKU', $x)){ - $this->options['Items.member.'.$i.'.FulfillmentNetworkSKU'] = $x['FulfillmentNetworkSKU']; - } - if (array_key_exists('OrderItemDisposition', $x)){ - $this->options['Items.member.'.$i.'.OrderItemDisposition'] = $x['OrderItemDisposition']; - } - if (array_key_exists('PerUnitDeclaredValue', $x)){ - $this->options['Items.member.'.$i.'.PerUnitDeclaredValue.CurrencyCode'] = $x['PerUnitDeclaredValue']['CurrencyCode']; - $this->options['Items.member.'.$i.'.PerUnitDeclaredValue.Value'] = $x['PerUnitDeclaredValue']['Value']; - } - - $i++; - } else { - $this->resetItems(); - $this->log("Tried to set Items with invalid array",'Warning'); - return false; - } - } - } - - /** - * Resets the item options. - * - * Since the list of items is a required parameter, these options should not be removed - * without replacing them, so this method is not public. - */ - protected function resetItems(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#Items#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Creates a Fulfillment Order with Amazon. - * - * Submits a CreateFulfillmentOrder request to Amazon. In order to do this, - * a number of parameters are required. Amazon will send back an HTTP response, - * so there is no data to retrieve afterwards. The following parameters are required: - * fulfillment order ID, displayed order ID, displayed timestamp, comment, - * shipping speed, address, items. - * @return boolean TRUE if the order creation was successful, FALSE if something goes wrong - */ - public function createOrder(){ - if (!array_key_exists('SellerFulfillmentOrderId',$this->options)){ - $this->log("Seller Fulfillment OrderID must be set in order to create an order",'Warning'); - return false; - } - if (!array_key_exists('DisplayableOrderId',$this->options)){ - $this->log("Displayable Order ID must be set in order to create an order",'Warning'); - return false; - } - if (!array_key_exists('DisplayableOrderDateTime',$this->options)){ - $this->log("Date must be set in order to create an order",'Warning'); - return false; - } - if (!array_key_exists('DisplayableOrderComment',$this->options)){ - $this->log("Comment must be set in order to create an order",'Warning'); - return false; - } - if (!array_key_exists('ShippingSpeedCategory',$this->options)){ - $this->log("Shipping Speed must be set in order to create an order",'Warning'); - return false; - } - if (!array_key_exists('DestinationAddress.Name',$this->options)){ - $this->log("Address must be set in order to create an order",'Warning'); - return false; - } - if (!array_key_exists('Items.member.1.SellerSKU',$this->options)){ - $this->log("Items must be set in order to create an order",'Warning'); - return false; - } - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $response = $this->fetchMockResponse(); - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - } - if (!$this->checkResponse($response)){ - return false; - } else { - $this->log("Successfully created Fulfillment Order ".$this->options['SellerFulfillmentOrderId']." / ".$this->options['DisplayableOrderId']); - return true; - } - } - -} -?> diff --git a/includes/classes/AmazonFulfillmentOrderList.php b/includes/classes/AmazonFulfillmentOrderList.php deleted file mode 100644 index c89b8d85..00000000 --- a/includes/classes/AmazonFulfillmentOrderList.php +++ /dev/null @@ -1,341 +0,0 @@ -Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - - $this->options['Action'] = 'ListAllFulfillmentOrders'; - } - - /** - * Sets the start time. (Optional) - * - * This method sets the earliest time frame to be sent in the next request. - * If this parameter is set, Amazon will only return fulfillment orders that - * were last updated after the time set. If this parameter is not set, Amazon - * will only return orders that were updated in the past 36 hours. - * The parameter is passed through strtotime, so values such as "-1 hour" are fine. - * @param string $s

    Time string.

    - * @return boolean FALSE if improper input - */ - public function setStartTime($s){ - if (is_string($s)){ - $time = $this->genTime($s); - $this->options['QueryStartDateTime'] = $time; - } else { - return false; - } - } - - /** - * Sets the fulfillment method filter. (Optional) - * - * This method sets the Fulfillment Method to be sent in the next request. - * If this parameter is set, Amazon will return fulfillment orders using the given method. - * If this parameter is not set, Amazon will only return fulfillment orders - * with a Consumer method. - * Here is a quick description of the methods: - * - * @param string $s

    "Consumer" or "Removal"

    - * @return boolean FALSE if improper input - */ - public function setMethodFilter($s){ - if ($s == 'Consumer' || $s == 'Removal'){ - $this->options['FulfillmentMethod'] = $s; - } else { - return false; - } - } - - /** - * Returns whether or not a token is available. - * @return boolean - */ - public function hasToken(){ - return $this->tokenFlag; - } - - /** - * Sets whether or not the object should automatically use tokens if it receives one. - * - * If this option is set to TRUE, the object will automatically perform - * the necessary operations to retrieve the rest of the list using tokens. If - * this option is off, the object will only ever retrieve the first section of - * the list. - * @param boolean $b [optional]

    Defaults to TRUE

    - * @return boolean FALSE if improper input - */ - public function setUseToken($b = true){ - if (is_bool($b)){ - $this->tokenUseFlag = $b; - } else { - return false; - } - } - - /** - * Fetches the fulfillment order list from Amazon. - * - * Submits a ListAllFulfillmentOrders request to Amazon. Amazon will send - * the list back as a response, which can be retrieved using getOrder. - * This operation can potentially involve tokens. - * @param boolean

    When set to FALSE, the function will not recurse, defaults to TRUE

    - * @return boolean FALSE if something goes wrong - */ - public function fetchOrderList($r = true){ - $this->prepareToken(); - - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->parseXML($xml->FulfillmentOrders); - - $this->checkToken($xml); - - if ($this->tokenFlag && $this->tokenUseFlag && $r === true){ - while ($this->tokenFlag){ - $this->log("Recursively fetching more Orders"); - $this->fetchOrderList(false); - } - - } - - } - - /** - * Sets up options for using tokens. - * - * This changes key options for switching between simply fetching a list and - * fetching the rest of a list using a token. Please note: because the - * operation for using tokens does not use any other parameters, all other - * parameters will be removed. - */ - protected function prepareToken(){ - if ($this->tokenFlag && $this->tokenUseFlag){ - $this->options['Action'] = 'ListAllFulfillmentOrdersByNextToken'; - unset($this->options['QueryStartDateTime']); - unset($this->options['FulfillmentMethod']); - } else { - $this->options['Action'] = 'ListAllFulfillmentOrders'; - unset($this->options['NextToken']); - $this->orderList = array(); - $this->index = 0; - } - } - - /** - * Parses XML response into array. - * - * This is what reads the response XML and converts it into an array. - * @param SimpleXMLObject $xml

    The XML response from Amazon.

    - * @return boolean FALSE if no XML data is found - */ - protected function parseXML($xml){ - if (!$xml){ - return false; - } - foreach($xml->children() as $x){ - $i = $this->index; - $this->orderList[$i]['SellerFulfillmentOrderId'] = (string)$x->SellerFulfillmentOrderId; - $this->orderList[$i]['DisplayableOrderId'] = (string)$x->DisplayableOrderId; - $this->orderList[$i]['DisplayableOrderDateTime'] = (string)$x->DisplayableOrderDateTime; - $this->orderList[$i]['DisplayableOrderComment'] = (string)$x->DisplayableOrderComment; - $this->orderList[$i]['ShippingSpeedCategory'] = (string)$x->ShippingSpeedCategory; - if (isset($x->DestinationAddress)){ - $this->orderList[$i]['DestinationAddress']['Name'] = (string)$x->DestinationAddress->Name; - $this->orderList[$i]['DestinationAddress']['Line1'] = (string)$x->DestinationAddress->Line1; - if (isset($x->DestinationAddress->Line2)){ - $this->orderList[$i]['DestinationAddress']['Line2'] = (string)$x->DestinationAddress->Line2; - } - if (isset($x->DestinationAddress->Line3)){ - $this->orderList[$i]['DestinationAddress']['Line3'] = (string)$x->DestinationAddress->Line3; - } - if (isset($x->DestinationAddress->DistrictOrCounty)){ - $this->orderList[$i]['DestinationAddress']['DistrictOrCounty'] = (string)$x->DestinationAddress->DistrictOrCounty; - } - $this->orderList[$i]['DestinationAddress']['City'] = (string)$x->DestinationAddress->City; - $this->orderList[$i]['DestinationAddress']['StateOrProvinceCode'] = (string)$x->DestinationAddress->StateOrProvinceCode; - $this->orderList[$i]['DestinationAddress']['CountryCode'] = (string)$x->DestinationAddress->CountryCode; - if (isset($x->DestinationAddress->PostalCode)){ - $this->orderList[$i]['DestinationAddress']['PostalCode'] = (string)$x->DestinationAddress->PostalCode; - } - if (isset($x->DestinationAddress->PhoneNumber)){ - $this->orderList[$i]['DestinationAddress']['PhoneNumber'] = (string)$x->DestinationAddress->PhoneNumber; - } - } - if (isset($x->FulfillmentPolicy)){ - $this->orderList[$i]['FulfillmentPolicy'] = (string)$x->FulfillmentPolicy; - } - if (isset($x->FulfillmentMethod)){ - $this->orderList[$i]['FulfillmentPolicy'] = (string)$x->FulfillmentMethod; - } - $this->orderList[$i]['ReceivedDateTime'] = (string)$x->ReceivedDateTime; - $this->orderList[$i]['FulfillmentOrderStatus'] = (string)$x->FulfillmentOrderStatus; - $this->orderList[$i]['StatusUpdatedDateTime'] = (string)$x->StatusUpdatedDateTime; - if (isset($x->NotificationEmailList)){ - $j = 0; - foreach($x->NotificationEmailList->children() as $y){ - $this->orderList[$i]['NotificationEmailList'][$j++] = (string)$y; - } - } - $this->index++; - } - } - - /** - * Creates a list of full order objects from the list. (Warning: could take a while.) - * - * This method automatically creates an array of AmazonFulfillmentOrder objects - * and fetches all of their full information from Amazon. Because of throttling, this - * could take a while if the list has more than a few orders. - * @return array|boolean array of AmazonFulfillmentOrder objects, or FALSE if list not filled yet - */ - public function getFullList(){ - if (!isset($this->orderList)){ - return false; - } - $list = array(); - $i = 0; - foreach($this->orderList as $x){ - $list[$i] = new AmazonFulfillmentOrder($this->storeName,$x['SellerFulfillmentOrderId'],$this->mockMode,$this->mockFiles,$this->config); - $list[$i]->mockIndex = $this->mockIndex; - $list[$i]->fetchOrder(); - $i++; - } - return $list; - } - - /** - * Returns the specified fulfillment order, or all of them. - * - * This method will return FALSE if the list has not yet been filled. - * The array for a single fulfillment order will have the following fields: - * - * @param int $i [optional]

    List index to retrieve the value from. - * If none is given, the entire list will be returned. Defaults to NULL.

    - * @return array|boolean array, multi-dimensional array, or FALSE if list not filled yet - */ - public function getOrder($i = null){ - if (!isset($this->orderList)){ - return false; - } - if (is_numeric($i)){ - return $this->orderList[$i]; - } else { - return $this->orderList; - } - } - - /** - * Iterator function - * @return type - */ - public function current(){ - return $this->orderList[$this->i]; - } - - /** - * Iterator function - */ - public function rewind(){ - $this->i = 0; - } - - /** - * Iterator function - * @return type - */ - public function key() { - return $this->i; - } - - /** - * Iterator function - */ - public function next() { - $this->i++; - } - - /** - * Iterator function - * @return type - */ - public function valid() { - return isset($this->orderList[$this->i]); - } - -} -?> diff --git a/includes/classes/AmazonInventoryCore.php b/includes/classes/AmazonInventoryCore.php deleted file mode 100644 index f8245d09..00000000 --- a/includes/classes/AmazonInventoryCore.php +++ /dev/null @@ -1,57 +0,0 @@ -Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); - include($this->env); - - if(isset($AMAZON_VERSION_INVENTORY)){ - $this->urlbranch = 'FulfillmentInventory/'.$AMAZON_VERSION_INVENTORY; - $this->options['Version'] = $AMAZON_VERSION_INVENTORY; - } - - if(isset($THROTTLE_LIMIT_INVENTORY)) { - $this->throttleLimit = $THROTTLE_LIMIT_INVENTORY; - } - if(isset($THROTTLE_TIME_INVENTORY)) { - $this->throttleTime = $THROTTLE_TIME_INVENTORY; - } - $this->throttleGroup = 'Inventory'; - } -} -?> diff --git a/includes/classes/AmazonInventoryList.php b/includes/classes/AmazonInventoryList.php deleted file mode 100644 index 8e65f93b..00000000 --- a/includes/classes/AmazonInventoryList.php +++ /dev/null @@ -1,572 +0,0 @@ -Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - } - - /** - * Returns whether or not a token is available. - * @return boolean - */ - public function hasToken(){ - return $this->tokenFlag; - } - - /** - * Sets whether or not the object should automatically use tokens if it receives one. - * - * If this option is set to TRUE, the object will automatically perform - * the necessary operations to retrieve the rest of the list using tokens. If - * this option is off, the object will only ever retrieve the first section of - * the list. - * @param boolean $b [optional]

    Defaults to TRUE

    - * @return boolean FALSE if improper input - */ - public function setUseToken($b = true){ - if (is_bool($b)){ - $this->tokenUseFlag = $b; - } else { - return false; - } - } - - /** - * Sets the start time. (Required*) - * - * This method sets the earliest time frame to be sent in the next request. - * Setting this parameter tells Amazon to only return inventory supplies that - * were updated after the given time. - * If this parameters is set, seller SKUs cannot be set. - * The parameter is passed through strtotime, so values such as "-1 hour" are fine. - * @param string $s

    Time string.

    - * @return boolean FALSE if improper input - */ - public function setStartTime($t = null){ - if (is_string($t) && $t){ - $after = $this->genTime($t); - } else { - $after = $this->genTime('- 2 min'); - } - $this->options['QueryStartDateTime'] = $after; - $this->resetSkus(); - - } - - /** - * Sets the feed seller SKU(s). (Required*) - * - * This method sets the list of seller SKUs to be sent in the next request. - * Setting this parameter tells Amazon to only return inventory supplies that match - * the IDs in the list. If this parameter is set, Start Time cannot be set. - * @param array|string $s

    A list of Seller SKUs, or a single ID string.

    - * @return boolean FALSE if improper input - */ - public function setSellerSkus($a){ - if (is_string($a)){ - $this->resetSkus(); - $this->options['SellerSkus.member.1'] = $a; - } else if (is_array($a)){ - $this->resetSkus(); - $i = 1; - foreach($a as $x){ - $this->options['SellerSkus.member.'.$i] = $x; - $i++; - } - } else { - return false; - } - unset($this->options['QueryStartDateTime']); - } - - /** - * Resets the seller SKU options. - * - * Since seller SKU is a required parameter, these options should not be removed - * without replacing them, so this method is not public. - */ - private function resetSkus(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#SellerSkus.member.#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets whether or not to get detailed results back. (Optional) - * - * If this parameter is set to "Detailed", the list returned will contain - * extra information regarding availability. If this parameter is not set, - * Amazon will return a Basic response. - * @param string $s

    "Basic" or "Detailed"

    - * @return boolean FALSE if improper input - */ - public function setResponseGroup($s){ - if ($s == 'Basic' || $s == 'Detailed'){ - $this->options['ResponseGroup'] = $s; - } else { - return false; - } - } - - /** - * Fetches the inventory supply list from Amazon. - * - * Submits a ListInventorySupply request to Amazon. Amazon will send - * the list back as a response, which can be retrieved using getSupply. - * Other methods are available for fetching specific values from the list. - * This operation can potentially involve tokens. - * @param boolean

    When set to FALSE, the function will not recurse, defaults to TRUE

    - * @return boolean FALSE if something goes wrong - */ - public function fetchInventoryList($r = true){ - if (!isset($this->options['QueryStartDateTime']) && !isset($this->options['SellerSkus.member.1'])){ - $this->setStartTime(); - } - $this->prepareToken(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->parseXML($xml->InventorySupplyList); - - $this->checkToken($xml); - - if ($this->tokenFlag && $this->tokenUseFlag && $r === true){ - while ($this->tokenFlag){ - $this->log("Recursively fetching more Inventory Supplies"); - $this->fetchInventoryList(false); - } - - } - - } - - /** - * Sets up options for using tokens. - * - * This changes key options for switching between simply fetching a list and - * fetching the rest of a list using a token. Please note: because the - * operation for using tokens does not use any other parameters, all other - * parameters will be removed. - */ - private function prepareToken(){ - if ($this->tokenFlag && $this->tokenUseFlag){ - $this->options['Action'] = 'ListInventorySupplyByNextToken'; - unset($this->options['QueryStartDateTime']); - unset($this->options['ResponseGroup']); - $this->resetSkus(); - } else { - $this->options['Action'] = 'ListInventorySupply'; - unset($this->options['NextToken']); - $this->index = 0; - $this->supplyList = array(); - } - } - - /** - * Parses XML response into array. - * - * This is what reads the response XML and converts it into an array. - * @param SimpleXMLObject $xml

    The XML response from Amazon.

    - * @return boolean FALSE if no XML data is found - */ - protected function parseXML($xml){ - if (!$xml){ - return false; - } - foreach($xml->children() as $x){ - $this->supplyList[$this->index]['SellerSKU'] = (string)$x->SellerSKU; - $this->supplyList[$this->index]['ASIN'] = (string)$x->ASIN; - $this->supplyList[$this->index]['TotalSupplyQuantity'] = (string)$x->TotalSupplyQuantity; - $this->supplyList[$this->index]['FNSKU'] = (string)$x->FNSKU; - $this->supplyList[$this->index]['Condition'] = (string)$x->Condition; - $this->supplyList[$this->index]['InStockSupplyQuantity'] = (string)$x->InStockSupplyQuantity; - if ((int)$x->TotalSupplyQuantity > 0){ - if ($x->EarliestAvailability->TimepointType == 'DateTime'){ - $this->supplyList[$this->index]['EarliestAvailability'] = (string)$x->EarliestAvailability->DateTime; - } else { - $this->supplyList[$this->index]['EarliestAvailability'] = (string)$x->EarliestAvailability->TimepointType; - } - } - if (isset($this->options['ResponseGroup']) && $this->options['ResponseGroup'] == 'Detailed'){ - $j = 0; - foreach($x->SupplyDetail->children() as $z){ - if ((string)$z->EarliestAvailableToPick->TimepointType == 'DateTime'){ - $this->supplyList[$this->index]['SupplyDetail'][$j]['EarliestAvailableToPick'] = (string)$z->EarliestAvailableToPick->DateTime; - } else { - $this->supplyList[$this->index]['SupplyDetail'][$j]['EarliestAvailableToPick'] = (string)$z->EarliestAvailableToPick->TimepointType; - } - if ((string)$z->LatestAvailableToPick->TimepointType == 'DateTime'){ - $this->supplyList[$this->index]['SupplyDetail'][$j]['LatestAvailableToPick'] = (string)$z->LatestAvailableToPick->DateTime; - } else { - $this->supplyList[$this->index]['SupplyDetail'][$j]['LatestAvailableToPick'] = (string)$z->LatestAvailableToPick->TimepointType; - } - $this->supplyList[$this->index]['SupplyDetail'][$j]['Quantity'] = (string)$z->Quantity; - $this->supplyList[$this->index]['SupplyDetail'][$j]['SupplyType'] = (string)$z->SupplyType; - $j++; - } - } - $this->index++; - } - } - - /** - * Returns the specified fulfillment order, or all of them. - * - * This method will return FALSE if the list has not yet been filled. - * The array for a single fulfillment order will have the following fields: - * - * @param int $i [optional]

    List index to retrieve the value from. - * If none is given, the entire list will be returned. Defaults to NULL.

    - * @return array|boolean array, multi-dimensional array, or FALSE if list not filled yet - */ - public function getSupply($i = null){ - if (!isset($this->supplyList)){ - return false; - } - if (is_numeric($i)){ - return $this->supplyList[$i]; - } else { - return $this->supplyList; - } - } - - /** - * Returns the seller SKU for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getSellerSku($i = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i)){ - return $this->supplyList[$i]['SellerSKU']; - } else { - return false; - } - } - - /** - * Returns the ASIN for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getASIN($i = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i)){ - return $this->supplyList[$i]['ASIN']; - } else { - return false; - } - } - - /** - * Returns the total supply quantity for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getTotalSupplyQuantity($i = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i)){ - return $this->supplyList[$i]['TotalSupplyQuantity']; - } else { - return false; - } - } - - /** - * Returns the fulfillment network SKU for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getFNSKU($i = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i)){ - return $this->supplyList[$i]['FNSKU']; - } else { - return false; - } - } - - /** - * Returns the item condition for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getCondition($i = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i)){ - return $this->supplyList[$i]['Condition']; - } else { - return false; - } - } - - /** - * Returns the in-stock supply quantity for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getInStockSupplyQuantity($i = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i)){ - return $this->supplyList[$i]['InStockSupplyQuantity']; - } else { - return false; - } - } - - /** - * Returns the earliest availability for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getEarliestAvailability($i = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i) && array_key_exists('EarliestAvailability', $this->supplyList[$i])){ - return $this->supplyList[$i]['EarliestAvailability']; - } else { - return false; - } - } - - /** - * Returns the ASIN for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * If $j is specified, it will return a single supply detail. Otherwise - * it will return a list of all details for a given supply. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @param int $j [optional]

    Detail index to retrieve the value from. Defaults to NULL.

    - * @return array|boolean array of arrays, single detail array, or FALSE if Non-numeric index - */ - public function getSupplyDetails($i = 0, $j = null){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i) && array_key_exists('SupplyDetail', $this->supplyList[$i])){ - if (is_numeric($j)) { - return $this->supplyList[$i]['SupplyDetail'][$j]; - } else { - return $this->supplyList[$i]['SupplyDetail']; - } - } else { - return false; - } - } - - /** - * Returns the earliest pick timeframe for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @param int $j [optional]

    Detail index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getEarliestAvailableToPick($i = 0, $j = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i) && is_numeric($j) && array_key_exists('SupplyDetail', $this->supplyList[$i])){ - return $this->supplyList[$i]['SupplyDetail'][$j]['EarliestAvailableToPick']; - } else { - return false; - } - } - - /** - * Returns the latest pick timeframe for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @param int $j [optional]

    Detail index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getLatestAvailableToPick($i = 0, $j = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i) && is_numeric($j) && array_key_exists('SupplyDetail', $this->supplyList[$i])){ - return $this->supplyList[$i]['SupplyDetail'][$j]['LatestAvailableToPick']; - } else { - return false; - } - } - - /** - * Returns the detail quantity for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @param int $j [optional]

    Detail index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getQuantity($i = 0, $j = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i) && is_numeric($j) && array_key_exists('SupplyDetail', $this->supplyList[$i])){ - return $this->supplyList[$i]['SupplyDetail'][$j]['Quantity']; - } else { - return false; - } - } - - /** - * Returns the supply type for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @param int $j [optional]

    Detail index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getSupplyType($i = 0, $j = 0){ - if (!isset($this->supplyList)){ - return false; - } - if (is_int($i) && is_numeric($j) && array_key_exists('SupplyDetail', $this->supplyList[$i])){ - return $this->supplyList[$i]['SupplyDetail'][$j]['SupplyType']; - } else { - return false; - } - } - - /** - * Iterator function - * @return type - */ - public function current(){ - return $this->supplyList[$this->i]; - } - - /** - * Iterator function - */ - public function rewind(){ - $this->i = 0; - } - - /** - * Iterator function - * @return type - */ - public function key() { - return $this->i; - } - - /** - * Iterator function - */ - public function next() { - $this->i++; - } - - /** - * Iterator function - * @return type - */ - public function valid() { - return isset($this->supplyList[$this->i]); - } -} -?> diff --git a/includes/classes/AmazonOrder.php b/includes/classes/AmazonOrder.php deleted file mode 100644 index adbdf463..00000000 --- a/includes/classes/AmazonOrder.php +++ /dev/null @@ -1,676 +0,0 @@ -Name for the store you want to use.

    - * @param string $id [optional]

    The Order ID to set for the object.

    - * @param SimpleXMLElement $data [optional]

    XML data from Amazon to be parsed.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $id = null, $data = null, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); - include($this->env); - - if($id){ - $this->setOrderId($id); - } - if ($data) { - $this->parseXML($data); - } - - $this->options['Action'] = 'GetOrder'; - - if(isset($THROTTLE_LIMIT_ORDER)) { - $this->throttleLimit = $THROTTLE_LIMIT_ORDER; - } - if(isset($THROTTLE_TIME_ORDER)) { - $this->throttleTime = $THROTTLE_TIME_ORDER; - } - $this->throttleGroup = 'GetOrder'; - } - - /** - * Sets the Amazon Order ID. (Required) - * - * This method sets the Amazon Order ID to be sent in the next request. - * This parameter is required for fetching the order from Amazon. - * @param string $s

    either string or number

    - * @return boolean FALSE if improper input - */ - public function setOrderId($id){ - if (is_string($id) || is_numeric($id)){ - $this->options['AmazonOrderId.Id.1'] = $id; - } else { - $this->log("Attempted to set AmazonOrderId to invalid value",'Warning'); - return false; - } - } - - /** - * Fetches the specified order from Amazon. - * - * Submits a GetOrder request to Amazon. In order to do this, - * an Amazon order ID is required. Amazon will send - * the data back as a response, which can be retrieved using getData. - * Other methods are available for fetching specific values from the order. - * @return boolean FALSE if something goes wrong - */ - public function fetchOrder(){ - if (!array_key_exists('AmazonOrderId.Id.1',$this->options)){ - $this->log("Order ID must be set in order to fetch it!",'Warning'); - return false; - } - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $xml = $this->fetchMockFile(); - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body']); - } - - $this->parseXML($xml->GetOrderResult->Orders->Order); - - } - - /** - * Fetches items for the order from Amazon. - * - * See the AmazonOrderItemList class for more information on the returned object. - * @param boolean $token [optional]

    whether or not to automatically use item tokens in the request

    - * @return AmazonOrderItemList container for order's items - */ - public function fetchItems($token = false){ - if (!isset($this->data['AmazonOrderId'])){ - return false; - } - if (!is_bool($token)){ - $token = false; - } - $items = new AmazonOrderItemList($this->storeName,$this->data['AmazonOrderId'],$this->mockMode,$this->mockFiles,$this->config); - $items->setLogPath($this->logpath); - $items->mockIndex = $this->mockIndex; - $items->setUseToken($token); - $items->fetchItems(); - return $items; - } - - /** - * Parses XML response into array. - * - * This is what reads the response XML and converts it into an array. - * @param SimpleXMLObject $xml

    The XML response from Amazon.

    - * @return boolean FALSE if no XML data is found - */ - protected function parseXML($xml){ - if (!$xml){ - return false; - } - $d = array(); - $d['AmazonOrderId'] = (string)$xml->AmazonOrderId; - if (isset($xml->SellerOrderId)){ - $d['SellerOrderId'] = (string)$xml->SellerOrderId; - } - $d['PurchaseDate'] = (string)$xml->PurchaseDate; - $d['LastUpdateDate'] = (string)$xml->LastUpdateDate; - $d['OrderStatus'] = (string)$xml->OrderStatus; - if (isset($xml->FulfillmentChannel)){ - $d['FulfillmentChannel'] = (string)$xml->FulfillmentChannel; - } - if (isset($xml->SalesChannel)){ - $d['SalesChannel'] = (string)$xml->SalesChannel; - } - if (isset($xml->OrderChannel)){ - $d['OrderChannel'] = (string)$xml->OrderChannel; - } - if (isset($xml->ShipServiceLevel)){ - $d['ShipServiceLevel'] = (string)$xml->ShipServiceLevel; - } - if (isset($xml->ShippingAddress)){ - $d['ShippingAddress'] = array(); - $d['ShippingAddress']['Name'] = (string)$xml->ShippingAddress->Name; - $d['ShippingAddress']['AddressLine1'] = (string)$xml->ShippingAddress->AddressLine1; - $d['ShippingAddress']['AddressLine2'] = (string)$xml->ShippingAddress->AddressLine2; - $d['ShippingAddress']['AddressLine3'] = (string)$xml->ShippingAddress->AddressLine3; - $d['ShippingAddress']['City'] = (string)$xml->ShippingAddress->City; - $d['ShippingAddress']['County'] = (string)$xml->ShippingAddress->County; - $d['ShippingAddress']['District'] = (string)$xml->ShippingAddress->District; - $d['ShippingAddress']['StateOrRegion'] = (string)$xml->ShippingAddress->StateOrRegion; - $d['ShippingAddress']['PostalCode'] = (string)$xml->ShippingAddress->PostalCode; - $d['ShippingAddress']['CountryCode'] = (string)$xml->ShippingAddress->CountryCode; - $d['ShippingAddress']['Phone'] = (string)$xml->ShippingAddress->Phone; - } - if (isset($xml->OrderTotal)){ - $d['OrderTotal'] = array(); - $d['OrderTotal']['Amount'] = (string)$xml->OrderTotal->Amount; - $d['OrderTotal']['CurrencyCode'] = (string)$xml->OrderTotal->CurrencyCode; - } - if (isset($xml->NumberOfItemsShipped)){ - $d['NumberOfItemsShipped'] = (string)$xml->NumberOfItemsShipped; - } - if (isset($xml->NumberOfItemsUnshipped)){ - $d['NumberOfItemsUnshipped'] = (string)$xml->NumberOfItemsUnshipped; - } - if (isset($xml->PaymentExecutionDetail)){ - $d['PaymentExecutionDetail'] = array(); - - $i = 0; - foreach($xml->PaymentExecutionDetail->children() as $x){ - $d['PaymentExecutionDetail'][$i]['Amount'] = (string)$x->Payment->Amount; - $d['PaymentExecutionDetail'][$i]['CurrencyCode'] = (string)$x->Payment->CurrencyCode; - $d['PaymentExecutionDetail'][$i]['SubPaymentMethod'] = (string)$x->SubPaymentMethod; - $i++; - } - } - if (isset($xml->PaymentMethod)){ - $d['PaymentMethod'] = (string)$xml->PaymentMethod; - } - $d['MarketplaceId'] = (string)$xml->MarketplaceId; - if (isset($xml->BuyerName)){ - $d['BuyerName'] = (string)$xml->BuyerName; - } - if (isset($xml->BuyerEmail)){ - $d['BuyerEmail'] = (string)$xml->BuyerEmail; - } - if (isset($xml->ShipServiceLevelCategory)){ - $d['ShipServiceLevelCategory'] = (string)$xml->ShipServiceLevelCategory; - } - if (isset($xml->EarliestShipDate)){ - $d['EarliestShipDate'] = (string)$xml->EarliestShipDate; - } - if (isset($xml->LatestShipDate)){ - $d['LatestShipDate'] = (string)$xml->LatestShipDate; - } - if (isset($xml->EarliestDeliveryDate)){ - $d['EarliestDeliveryDate'] = (string)$xml->EarliestDeliveryDate; - } - if (isset($xml->LatestDeliveryDate)){ - $d['LatestDeliveryDate'] = (string)$xml->LatestDeliveryDate; - } - - $this->data = $d; - } - - /** - * Returns the full set of data for the order. - * - * This method will return FALSE if the order data has not yet been filled. - * The array returned will have the following fields: - * - * @return array|boolean array of data, or FALSE if data not filled yet - */ - public function getData(){ - if (isset($this->data) && $this->data){ - return $this->data; - } else { - return false; - } - } - - /** - * Returns the Amazon Order ID for the Order. - * - * This method will return FALSE if the order ID has not been set yet. - * @return string|boolean single value, or FALSE if order ID not set yet - */ - public function getAmazonOrderId(){ - if (isset($this->data['AmazonOrderId'])){ - return $this->data['AmazonOrderId']; - } else { - return false; - } - } - - /** - * Returns the seller-defined ID for the Order. - * - * This method will return FALSE if the order ID has not been set yet. - * @return string|boolean single value, or FALSE if order ID not set yet - */ - public function getSellerOrderId(){ - if (isset($this->data['SellerOrderId'])){ - return $this->data['SellerOrderId']; - } else { - return false; - } - } - - /** - * Returns the purchase date of the Order. - * - * This method will return FALSE if the timestamp has not been set yet. - * @return string|boolean timestamp, or FALSE if timestamp not set yet - */ - public function getPurchaseDate(){ - if (isset($this->data['PurchaseDate'])){ - return $this->data['PurchaseDate']; - } else { - return false; - } - } - - /** - * Returns the timestamp of the last modification date. - * - * This method will return FALSE if the timestamp has not been set yet. - * @return string|boolean timestamp, or FALSE if timestamp not set yet - */ - public function getLastUpdateDate(){ - if (isset($this->data['LastUpdateDate'])){ - return $this->data['LastUpdateDate']; - } else { - return false; - } - } - - /** - * Returns the status of the Order. - * - * This method will return FALSE if the order status has not been set yet. - * Possible Order Statuses are: - * - * @return string|boolean single value, or FALSE if status not set yet - */ - public function getOrderStatus(){ - if (isset($this->data['OrderStatus'])){ - return $this->data['OrderStatus']; - } else { - return false; - } - } - - /** - * Returns the Fulfillment Channel. - * - * This method will return FALSE if the fulfillment channel has not been set yet. - * @return string|boolean "AFN" or "MFN", or FALSE if channel not set yet - */ - public function getFulfillmentChannel(){ - if (isset($this->data['FulfillmentChannel'])){ - return $this->data['FulfillmentChannel']; - } else { - return false; - } - } - - /** - * Returns the Sales Channel of the Order. - * - * This method will return FALSE if the sales channel has not been set yet. - * @return string|boolean single value, or FALSE if channel not set yet - */ - public function getSalesChannel(){ - if (isset($this->data['SalesChannel'])){ - return $this->data['SalesChannel']; - } else { - return false; - } - } - - /** - * Returns the Order Channel of the first item in the Order. - * - * This method will return FALSE if the order channel has not been set yet. - * @return string|boolean single value, or FALSE if channel not set yet - */ - public function getOrderChannel(){ - if (isset($this->data['OrderChannel'])){ - return $this->data['OrderChannel']; - } else { - return false; - } - } - - /** - * Returns the shipment service level of the Order. - * - * This method will return FALSE if the shipment service level has not been set yet. - * @return string|boolean single value, or FALSE if level not set yet - */ - public function getShipServiceLevel(){ - if (isset($this->data['ShipServiceLevel'])){ - return $this->data['ShipServiceLevel']; - } else { - return false; - } - } - - /** - * Returns an array containing all of the address information. - * - * This method will return FALSE if the address has not been set yet. - * The returned array will have the following fields: - * - * @return array|boolean associative array, or FALSE if address not set yet - */ - public function getShippingAddress(){ - if (isset($this->data['ShippingAddress'])){ - return $this->data['ShippingAddress']; - } else { - return false; - } - } - - /** - * Returns an array containing the total cost of the Order along with the currency used. - * - * This method will return FALSE if the order total has not been set yet. - * The returned array has the following fields: - * - * @return array|boolean associative array, or FALSE if total not set yet - */ - public function getOrderTotal(){ - if (isset($this->data['OrderTotal'])){ - return $this->data['OrderTotal']; - } else { - return false; - } - } - - /** - * Returns just the total cost of the Order. - * - * This method will return FALSE if the order total has not been set yet. - * @return string|boolean number, or FALSE if total not set yet - */ - public function getOrderTotalAmount(){ - if (isset($this->data['OrderTotal']) && isset($this->data['OrderTotal']['Amount'])){ - return $this->data['OrderTotal']['Amount']; - } else { - return false; - } - } - - /** - * Returns the number of items in the Order that have been shipped. - * - * This method will return FALSE if the number has not been set yet. - * @return integer|boolean non-negative number, or FALSE if number not set yet - */ - public function getNumberofItemsShipped(){ - if (isset($this->data['NumberOfItemsShipped'])){ - return $this->data['NumberOfItemsShipped']; - } else { - return false; - } - } - - /** - * Returns the number of items in the Order that have yet to be shipped. - * - * This method will return FALSE if the number has not been set yet. - * @return integer|boolean non-negative number, or FALSE if number not set yet - */ - public function getNumberOfItemsUnshipped(){ - if (isset($this->data['NumberOfItemsUnshipped'])){ - return $this->data['NumberOfItemsUnshipped']; - } else { - return false; - } - } - - /** - * Returns an array of the complete payment details. - * - * This method will return FALSE if the payment details has not been set yet. - * The array returned contains one or more arrays with the following fields: - * - * @return array|boolean multi-dimensional array, or FALSE if details not set yet - */ - public function getPaymentExecutionDetail(){ - if (isset($this->data['PaymentExecutionDetail'])){ - return $this->data['PaymentExecutionDetail']; - } else { - return false; - } - } - - /** - * Returns the payment method of the Order. - * - * This method will return FALSE if the payment method has not been set yet. - * @return string|boolean "COD", "CVS", "Other", or FALSE if method not set yet - */ - public function getPaymentMethod(){ - if (isset($this->data['PaymentMethod'])){ - return $this->data['PaymentMethod']; - } else { - return false; - } - } - - /** - * Returns the ID of the Marketplace in which the Order was placed. - * - * This method will return FALSE if the marketplace ID has not been set yet. - * @return string|boolean single value, or FALSE if ID not set yet - */ - public function getMarketplaceId(){ - if (isset($this->data['MarketplaceId'])){ - return $this->data['MarketplaceId']; - } else { - return false; - } - } - - /** - * Returns the name of the buyer. - * - * This method will return FALSE if the buyer name has not been set yet. - * @return string|boolean single value, or FALSE if name not set yet - */ - public function getBuyerName(){ - if (isset($this->data['BuyerName'])){ - return $this->data['BuyerName']; - } else { - return false; - } - } - - /** - * Returns the Amazon-generated email address of the buyer. - * - * This method will return FALSE if the buyer email has not been set yet. - * @return string|boolean single value, or FALSE if email not set yet - */ - public function getBuyerEmail(){ - if (isset($this->data['BuyerEmail'])){ - return $this->data['BuyerEmail']; - } else { - return false; - } - } - - /** - * Returns the shipment service level category of the Order. - * - * This method will return FALSE if the service level category has not been set yet. - * Valid values for the service level category are... - * - * @return string|boolean single value, or FALSE if category not set yet - */ - public function getShipServiceLevelCategory(){ - if (isset($this->data['ShipServiceLevelCategory'])){ - return $this->data['ShipServiceLevelCategory']; - } else { - return false; - } - } - - /** - * Returns the timestamp of the earliest shipping date. - * - * This method will return FALSE if the timestamp has not been set yet. - * @return string|boolean timestamp, or FALSE if timestamp not set yet - */ - public function getEarliestShipDate(){ - if (isset($this->data['EarliestShipDate'])){ - return $this->data['EarliestShipDate']; - } else { - return false; - } - } - - /** - * Returns the timestamp of the latest shipping date. - * - * Note that this could be set to midnight of the day after the last date, - * so the timestamp "2013-09-025T00:00:00Z" indicates the last day is the 24th and not the 25th. - * This method will return FALSE if the timestamp has not been set yet. - * @return string|boolean timestamp, or FALSE if timestamp not set yet - */ - public function getLatestShipDate(){ - if (isset($this->data['LatestShipDate'])){ - return $this->data['LatestShipDate']; - } else { - return false; - } - } - - /** - * Returns the timestamp of the estimated earliest delivery date. - * - * This method will return FALSE if the timestamp has not been set yet. - * @return string|boolean timestamp, or FALSE if timestamp not set yet - */ - public function getEarliestDeliveryDate(){ - if (isset($this->data['EarliestDeliveryDate'])){ - return $this->data['EarliestDeliveryDate']; - } else { - return false; - } - } - - /** - * Returns the timestamp of the estimated latest delivery date. - * - * Note that this could be set to midnight of the day after the last date, - * so the timestamp "2013-09-025T00:00:00Z" indicates the last day is the 24th and not the 25th. - * This method will return FALSE if the timestamp has not been set yet. - * @return string|boolean timestamp, or FALSE if timestamp not set yet - */ - public function getLatestDeliveryDate(){ - if (isset($this->data['LatestDeliveryDate'])){ - return $this->data['LatestDeliveryDate']; - } else { - return false; - } - } - - /** - * Returns the ratio of shipped items to unshipped items. - * - * This method will return FALSE if the shipment numbers have not been set yet. - * @return float|boolean Decimal number from 0 to 1, or FALSE if numbers not set yet - */ - public function getPercentShipped(){ - if (isset($this->data['NumberOfItemsShipped']) && isset($this->data['NumberOfItemsUnshipped'])){ - $total = $this->data['NumberOfItemsShipped'] + $this->data['NumberOfItemsUnshipped']; - - if ($total == 0){ - return 0; - } - - $ratio = $this->data['NumberOfItemsShipped'] / $total; - return $ratio; - } else { - return false; - } - } -} - -?> diff --git a/includes/classes/AmazonOrderList.php b/includes/classes/AmazonOrderList.php deleted file mode 100644 index b4eba584..00000000 --- a/includes/classes/AmazonOrderList.php +++ /dev/null @@ -1,497 +0,0 @@ -AmazonOrder objects. - * - * The parameters are passed to the parent constructor, which are - * in turn passed to the AmazonCore constructor. See it for more information - * on these parameters and common methods. - * @param string $s

    Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); - include($this->env); - if (file_exists($this->config)){ - include($this->config); - } else { - throw new Exception('Config file does not exist!'); - } - - if(isset($store[$s]) && array_key_exists('marketplaceId', $store[$s])){ - $this->options['MarketplaceId.Id.1'] = $store[$s]['marketplaceId']; - } else { - $this->log("Marketplace ID is missing",'Urgent'); - } - - if(isset($THROTTLE_LIMIT_ORDERLIST)) { - $this->throttleLimit = $THROTTLE_LIMIT_ORDERLIST; - } - if(isset($THROTTLE_TIME_ORDERLIST)) { - $this->throttleTime = $THROTTLE_TIME_ORDERLIST; - } - $this->throttleGroup = 'ListOrders'; - } - - /** - * Returns whether or not a token is available. - * @return boolean - */ - public function hasToken(){ - return $this->tokenFlag; - } - - /** - * Sets whether or not the object should automatically use tokens if it receives one. - * - * If this option is set to TRUE, the object will automatically perform - * the necessary operations to retrieve the rest of the list using tokens. If - * this option is off, the object will only ever retrieve the first section of - * the list. - * @param boolean $b [optional]

    Defaults to TRUE

    - * @return boolean FALSE if improper input - */ - public function setUseToken($b = true){ - if (is_bool($b)){ - $this->tokenUseFlag = $b; - } else { - return false; - } - } - - /** - * Sets the time frame for the orders fetched. (Optional) - * - * Sets the time frame for the orders fetched. If no times are specified, times default to the current time. - * @param string $mode

    "Created" or "Modified"

    - * @param string $lower [optional]

    A time string for the earliest time.

    - * @param string $upper [optional]

    A time string for the latest time.

    - * @return boolean FALSE if improper input - */ - public function setLimits($mode,$lower = null,$upper = null){ - try{ - if ($upper){ - $before = $this->genTime($upper); - } else { - $before = $this->genTime('- 2 min'); - } - if ($lower){ - $after = $this->genTime($lower); - } else { - $after = $this->genTime('- 2 min'); - } - if ($after > $before){ - $after = $this->genTime($upper.' - 150 sec'); - } - if ($mode == 'Created'){ - $this->options['CreatedAfter'] = $after; - if ($before) { - $this->options['CreatedBefore'] = $before; - } - unset($this->options['LastUpdatedAfter']); - unset($this->options['LastUpdatedBefore']); - } else if ($mode == 'Modified'){ - $this->options['LastUpdatedAfter'] = $after; - if ($before){ - $this->options['LastUpdatedBefore'] = $before; - } - unset($this->options['CreatedAfter']); - unset($this->options['CreatedBefore']); - } else { - $this->log('First parameter should be either "Created" or "Modified".','Warning'); - return false; - } - - } catch (Exception $e){ - $this->log('Error: '.$e->getMessage(),'Warning'); - return false; - } - - } - - /** - * Sets the order status(es). (Optional) - * - * This method sets the list of Order Statuses to be sent in the next request. - * Setting this parameter tells Amazon to only return Orders with statuses that match - * those in the list. If this parameter is not set, Amazon will return - * Orders of any status. - * @param array|string $s

    A list of Order Statuses, or a single status string.

    - * @return boolean FALSE if improper input - */ - public function setOrderStatusFilter($list){ - if (is_string($list)){ - //if single string, set as filter - $this->resetOrderStatusFilter(); - $this->options['OrderStatus.Status.1'] = $list; - } else if (is_array($list)){ - //if array of strings, set all filters - $this->resetOrderStatusFilter(); - $i = 1; - foreach($list as $x){ - $this->options['OrderStatus.Status.'.$i] = $x; - $i++; - } - } else { - return false; - } - } - - /** - * Removes order status options. - * - * Use this in case you change your mind and want to remove the Order Status - * parameters you previously set. - */ - public function resetOrderStatusFilter(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#OrderStatus#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets (or resets) the Fulfillment Channel Filter - * @param string $filter

    'AFN' or 'MFN' or NULL

    - * @return boolean FALSE on failure - */ - public function setFulfillmentChannelFilter($filter){ - if ($filter == 'AFN' || $filter == 'MFN'){ - $this->options['FulfillmentChannel.Channel.1'] = $filter; - } else if (is_null($filter)){ - unset($this->options['FulfillmentChannel.Channel.1']); - } else { - return false; - } - } - - /** - * Sets the payment method(s). (Optional) - * - * This method sets the list of Payment Methods to be sent in the next request. - * Setting this parameter tells Amazon to only return Orders with payment methods - * that match those in the list. If this parameter is not set, Amazon will return - * Orders with any payment method. - * @param array|string $s

    A list of Payment Methods, or a single method string.

    - * @return boolean FALSE if improper input - */ - public function setPaymentMethodFilter($list){ - if (is_string($list)){ - //if single string, set as filter - $this->resetPaymentMethodFilter(); - $this->options['PaymentMethod.1'] = $list; - } else if (is_array($list)){ - //if array of strings, set all filters - $this->resetPaymentMethodFilter(); - $i = 1; - foreach($list as $x){ - $this->options['PaymentMethod.'.$i++] = $x; - } - } else { - return false; - } - } - - /** - * Removes payment method options. - * - * Use this in case you change your mind and want to remove the Payment Method - * parameters you previously set. - */ - public function resetPaymentMethodFilter(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#PaymentMethod#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets (or resets) the email address. (Optional) - * - * This method sets the email address to be sent in the next request. - * Setting this parameter tells Amazon to only return Orders with addresses - * that match the address given. If this parameter is set, the following options - * will be removed: SellerOrderId, OrderStatus, PaymentMethod, FulfillmentChannel, LastUpdatedAfter, LastUpdatedBefore. - * @param string $s

    A single address string. Set to NULL to remove the option.

    - * @return boolean FALSE if improper input - */ - public function setEmailFilter($filter){ - if (is_string($filter)){ - $this->options['BuyerEmail'] = $filter; - //these fields must be disabled - unset($this->options['SellerOrderId']); - $this->resetOrderStatusFilter(); - $this->resetPaymentMethodFilter(); - $this->setFulfillmentChannelFilter(null); - unset($this->options['LastUpdatedAfter']); - unset($this->options['LastUpdatedBefore']); - } else if (is_null($filter)){ - unset($this->options['BuyerEmail']); - } else { - return false; - } - } - - /** - * Sets (or resets) the seller order ID(s). (Optional) - * - * This method sets the list of seller order IDs to be sent in the next request. - * Setting this parameter tells Amazon to only return Orders with addresses - * that match those in the list. If this parameter is set, the following options - * will be removed: BuyerEmail, OrderStatus, PaymentMethod, FulfillmentChannel, LastUpdatedAfter, LastUpdatedBefore. - * @param array|string $s

    A list of Payment Methods, or a single type string. Set to NULL to remove the option.

    - * @return boolean FALSE if improper input - */ - public function setSellerOrderIdFilter($filter){ - if (is_string($filter)){ - $this->options['SellerOrderId'] = $filter; - //these fields must be disabled - unset($this->options['BuyerEmail']); - $this->resetOrderStatusFilter(); - $this->resetPaymentMethodFilter(); - $this->setFulfillmentChannelFilter(null); - unset($this->options['LastUpdatedAfter']); - unset($this->options['LastUpdatedBefore']); - } else if (is_null($filter)){ - unset($this->options['SellerOrderId']); - } else { - return false; - } - } - - /** - * Sets the maximum response per page count. (Optional) - * - * This method sets the maximum number of Feed Submissions for Amazon to return per page. - * If this parameter is not set, Amazon will send 100 at a time. - * @param array|string $s

    Positive integer from 1 to 100.

    - * @return boolean FALSE if improper input - */ - public function setMaxResultsPerPage($num){ - if (is_int($num) && $num <= 100 && $num >= 1){ - $this->options['MaxResultsPerPage'] = $num; - } else { - return false; - } - } - - /** - * Fetches orders from Amazon and puts them in an array of AmazonOrder objects. - * - * Submits a ListOrders request to Amazon. Amazon will send - * the list back as a response, which can be retrieved using getList. - * This operation can potentially involve tokens. - * @param boolean

    When set to FALSE, the function will not recurse, defaults to TRUE

    - * @return boolean FALSE if something goes wrong - */ - public function fetchOrders($r = true){ - if (!array_key_exists('CreatedAfter', $this->options) && !array_key_exists('LastUpdatedAfter', $this->options)){ - $this->setLimits('Created'); - } - - $this->prepareToken(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->parseXML($xml); - - $this->checkToken($xml); - - if ($this->tokenFlag && $this->tokenUseFlag && $r === true){ - while ($this->tokenFlag){ - $this->log("Recursively fetching more orders"); - $this->fetchOrders(false); - } - - } - } - - /** - * Sets up options for using tokens. - * - * This changes key options for switching between simply fetching a list and - * fetching the rest of a list using a token. Please note: because the - * operation for using tokens does not use any other parameters, all other - * parameters will be removed. - */ - protected function prepareToken(){ - if ($this->tokenFlag && $this->tokenUseFlag){ - $this->options['Action'] = 'ListOrdersByNextToken'; - - //When using tokens, only the NextToken option should be used - unset($this->options['SellerOrderId']); - $this->resetOrderStatusFilter(); - $this->resetPaymentMethodFilter(); - $this->setFulfillmentChannelFilter(null); - $this->setSellerOrderIdFilter(null); - $this->setEmailFilter(null); - unset($this->options['LastUpdatedAfter']); - unset($this->options['LastUpdatedBefore']); - unset($this->options['CreatedAfter']); - unset($this->options['CreatedBefore']); - unset($this->options['MaxResultsPerPage']); - - } else { - $this->options['Action'] = 'ListOrders'; - unset($this->options['NextToken']); - $this->index = 0; - $this->orderList = array(); - } - } - - /** - * Parses XML response into array. - * - * This is what reads the response XML and converts it into an array. - * @param SimpleXMLObject $xml

    The XML response from Amazon.

    - * @return boolean FALSE if no XML data is found - */ - protected function parseXML($xml){ - if (!$xml){ - return false; - } - - foreach($xml->Orders->children() as $key => $data){ - if ($key != 'Order'){ - break; - } - $this->orderList[$this->index] = new AmazonOrder($this->storeName,null,$data,$this->mockMode,$this->mockFiles,$this->config); - $this->orderList[$this->index]->setLogPath($this->logpath); - $this->orderList[$this->index]->mockIndex = $this->mockIndex; - $this->index++; - } - - } - - /** - * Returns array of item lists or a single item list. - * - * If $i is not specified, the method will fetch the items for every - * order in the list. Please note that for lists with a high number of orders, - * this operation could take a while due to throttling. (Two seconds per order when throttled.) - * @param boolean $token [optional]

    whether or not to automatically use tokens when fetching items.

    - * @param int $i [optional]

    List index to retrieve the value from. Defaults to null.

    - * @return array|AmazonOrderItemList AmazonOrderItemList object or array of objects, or FALSE if non-numeric index - */ - public function fetchItems($token = false, $i = null){ - if (!isset($this->orderList)){ - return false; - } - if (!is_bool($token)){ - $token = false; - } - if (is_int($i)) { - return $this->orderList[$i]->fetchItems($token); - } else { - $a = array(); - foreach($this->orderList as $x){ - $a[] = $x->fetchItems($token); - } - return $a; - } - } - - /** - * Returns the list of orders. - * @return array|boolean array of AmazonOrder objects, or FALSE if list not filled yet - */ - public function getList(){ - if (isset($this->orderList)){ - return $this->orderList; - } else { - return false; - } - - } - - /** - * Iterator function - * @return type - */ - public function current(){ - return $this->orderList[$this->i]; - } - - /** - * Iterator function - */ - public function rewind(){ - $this->i = 0; - } - - /** - * Iterator function - * @return type - */ - public function key() { - return $this->i; - } - - /** - * Iterator function - */ - public function next() { - $this->i++; - } - - /** - * Iterator function - * @return type - */ - public function valid() { - return isset($this->orderList[$this->i]); - } -} - -?> diff --git a/includes/classes/AmazonPackageTracker.php b/includes/classes/AmazonPackageTracker.php deleted file mode 100644 index 075c4913..00000000 --- a/includes/classes/AmazonPackageTracker.php +++ /dev/null @@ -1,181 +0,0 @@ -Name for the store you want to use.

    - * @param string $id [optional]

    The package ID to set for the object.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $id = null, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - - if($id){ - $this->setPackageNumber($id); - } - - $this->options['Action'] = 'GetPackageTrackingDetails'; - } - - /** - * Sets the package ID. (Required) - * - * This method sets the package ID to be sent in the next request. - * This parameter is required for fetching the tracking information from Amazon. - * @param string|integer $n

    Must be numeric

    - * @return boolean FALSE if improper input - */ - public function setPackageNumber($n){ - if (is_numeric($n)){ - $this->options['PackageNumber'] = $n; - } else { - return false; - } - } - - /** - * Sends a request to Amazon for package tracking details. - * - * Submits a GetPackageTrackingDetails request to Amazon. In order to do this, - * a package ID is required. Amazon will send - * the data back as a response, which can be retrieved using getDetails. - * @return boolean FALSE if something goes wrong - */ - public function fetchTrackingDetails(){ - if (!array_key_exists('PackageNumber',$this->options)){ - $this->log("Package Number must be set in order to fetch it!",'Warning'); - return false; - } - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->parseXML($xml); - } - - /** - * Parses XML response into array. - * - * This is what reads the response XML and converts it into an array. - * @param SimpleXMLObject $d

    The XML response from Amazon.

    - * @return boolean FALSE if no XML data is found - */ - protected function parseXML($d) { - if (!$d){ - return false; - } - $this->details['PackageNumber'] = (string)$d->PackageNumber; - $this->details['TrackingNumber'] = (string)$d->TrackingNumber; - $this->details['CarrierCode'] = (string)$d->CarrierCode; - $this->details['CarrierPhoneNumber'] = (string)$d->CarrierPhoneNumber; - $this->details['CarrierURL'] = (string)$d->CarrierURL; - $this->details['ShipDate'] = (string)$d->ShipDate; - //Address - $this->details['ShipToAddress']['City'] = (string)$d->ShipToAddress->City; - $this->details['ShipToAddress']['State'] = (string)$d->ShipToAddress->State; - $this->details['ShipToAddress']['Country'] = (string)$d->ShipToAddress->Country; - //End of Address - $this->details['CurrentStatus'] = (string)$d->CurrentStatus; - $this->details['SignedForBy'] = (string)$d->SignedForBy; - $this->details['EstimatedArrivalDate'] = (string)$d->EstimatedArrivalDate; - - $i = 0; - foreach($d->TrackingEvents->children() as $y){ - $this->details['TrackingEvents'][$i]['EventDate'] = (string)$y->EventDate; - //Address - $this->details['TrackingEvents'][$i]['EventAddress']['City'] = (string)$y->EventAddress->City; - $this->details['TrackingEvents'][$i]['EventAddress']['State'] = (string)$y->EventAddress->State; - $this->details['TrackingEvents'][$i]['EventAddress']['Country'] = (string)$y->EventAddress->Country; - //End of Address - $this->details['TrackingEvents'][$i]['EventCode'] = (string)$y->EventCode; - $i++; - } - - $this->details['AdditionalLocationInfo'] = (string)$d->AdditionalLocationInfo; - - } - - /** - * Returns the full package tracking information. - * - * This method will return FALSE if the data has not yet been filled. - * The array returned will have the following fields: - * - * @return array|boolean data array, or FALSE if data not filled yet - */ - public function getDetails(){ - if (isset($this->details)){ - return $this->details; - } else { - return false; - } - - } - -} -?> diff --git a/includes/classes/AmazonProductInfo.php b/includes/classes/AmazonProductInfo.php deleted file mode 100644 index 63e2d219..00000000 --- a/includes/classes/AmazonProductInfo.php +++ /dev/null @@ -1,403 +0,0 @@ -Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); - } - - /** - * Sets the feed seller SKU(s). (Required*) - * - * This method sets the list of seller SKUs to be sent in the next request. - * Setting this parameter tells Amazon to only return inventory supplies that match - * the IDs in the list. If this parameter is set, ASINs cannot be set. - * @param array|string $s

    A list of Seller SKUs, or a single SKU string. (max: 20)

    - * @return boolean FALSE if improper input - */ - public function setSKUs($s){ - if (is_string($s)){ - $this->resetASINs(); - $this->resetSKUs(); - $this->options['SellerSKUList.SellerSKU.1'] = $s; - } else if (is_array($s)){ - $this->resetASINs(); - $this->resetSKUs(); - $i = 1; - foreach ($s as $x){ - $this->options['SellerSKUList.SellerSKU.'.$i] = $x; - $i++; - } - } else { - return false; - } - } - - /** - * Resets the seller SKU options. - * - * Since seller SKU is a required parameter, these options should not be removed - * without replacing them, so this method is not public. - */ - private function resetSKUs(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#SellerSKUList#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets the ASIN(s). (Required*) - * - * This method sets the list of ASINs to be sent in the next request. - * Setting this parameter tells Amazon to only return inventory supplies that match - * the IDs in the list. If this parameter is set, Seller SKUs cannot be set. - * @param array|string $s

    A list of ASINs, or a single ASIN string. (max: 20)

    - * @return boolean FALSE if improper input - */ - public function setASINs($s){ - if (is_string($s)){ - $this->resetSKUs(); - $this->resetASINs(); - $this->options['ASINList.ASIN.1'] = $s; - } else if (is_array($s)){ - $this->resetSKUs(); - $this->resetASINs(); - $i = 1; - foreach ($s as $x){ - $this->options['ASINList.ASIN.'.$i] = $x; - $i++; - } - } else { - return false; - } - } - - /** - * Resets the ASIN options. - * - * Since ASIN is a required parameter, these options should not be removed - * without replacing them, so this method is not public. - */ - private function resetASINs(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#ASINList#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets the item condition filter. (Optional) - * - * This method sets the item condition filter to be sent in the next request. - * Setting this parameter tells Amazon to only return products with conditions that match - * the one given. If this parameter is not set, Amazon will return products with any condition. - * @param string $s

    Single condition string.

    - * @return boolean FALSE if improper input - */ - public function setConditionFilter($s){ - if (is_string($s)){ - $this->options['ItemCondition'] = $s; - } else { - return false; - } - } - - /** - * Sets the "ExcludeSelf" flag. (Optional) - * - * Sets whether or not the next Lowest Offer Listings request should exclude your own listings. - * @param string|boolean $s

    "true" or "false", or boolean

    - * @return boolean FALSE if improper input - */ - public function setExcludeSelf($s = 'true'){ - if ($s == 'true' || (is_bool($s) && $s == true)){ - $this->options['ExcludeMe'] = 'true'; - } else if ($s == 'false' || (is_bool($s) && $s == false)){ - $this->options['ExcludeMe'] = 'false'; - } else { - return false; - } - } - - /** - * Fetches a list of competitive pricing on products from Amazon. - * - * Submits a GetCompetitivePricingForSKU - * or GetCompetitivePricingForASIN request to Amazon. Amazon will send - * the list back as a response, which can be retrieved using getProduct. - * @return boolean FALSE if something goes wrong - */ - public function fetchCompetitivePricing(){ - if (!array_key_exists('SellerSKUList.SellerSKU.1',$this->options) && !array_key_exists('ASINList.ASIN.1',$this->options)){ - $this->log("Product IDs must be set in order to look them up!",'Warning'); - return false; - } - - $this->prepareCompetitive(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $xml = $this->fetchMockFile(); - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body']); - } - - $this->parseXML($xml); - - } - - /** - * Sets up options for using fetchCompetitivePricing. - * - * This changes key options for using fetchCompetitivePricing. - * Please note: because the operation does not use all of the parameters, - * some of the parameters will be removed. The following parameters are removed: - * ItemCondition and ExcludeMe. - */ - protected function prepareCompetitive(){ - include($this->env); - if(isset($THROTTLE_TIME_PRODUCTPRICE)) { - $this->throttleTime = $THROTTLE_TIME_PRODUCTPRICE; - } - $this->throttleGroup = 'GetCompetitivePricing'; - unset($this->options['ExcludeMe']); - unset($this->options['ItemCondition']); - if (array_key_exists('SellerSKUList.SellerSKU.1',$this->options)){ - $this->options['Action'] = 'GetCompetitivePricingForSKU'; - $this->resetASINs(); - } else if (array_key_exists('ASINList.ASIN.1',$this->options)){ - $this->options['Action'] = 'GetCompetitivePricingForASIN'; - $this->resetSKUs(); - } - } - - /** - * Fetches a list of lowest offers on products from Amazon. - * - * Submits a GetLowestOfferListingsForSKU - * or GetLowestOfferListingsForASIN request to Amazon. Amazon will send - * the list back as a response, which can be retrieved using getProduct. - * @return boolean FALSE if something goes wrong - */ - public function fetchLowestOffer(){ - if (!array_key_exists('SellerSKUList.SellerSKU.1',$this->options) && !array_key_exists('ASINList.ASIN.1',$this->options)){ - $this->log("Product IDs must be set in order to look them up!",'Warning'); - return false; - } - - $this->prepareLowest(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $xml = $this->fetchMockFile(); - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body']); - } - - - $this->parseXML($xml); - - } - - /** - * Sets up options for using fetchLowestOffer. - * - * This changes key options for using fetchLowestOffer. - */ - protected function prepareLowest(){ - include($this->env); - if(isset($THROTTLE_TIME_PRODUCTPRICE)) { - $this->throttleTime = $THROTTLE_TIME_PRODUCTPRICE; - } - $this->throttleGroup = 'GetLowestOfferListings'; - if (array_key_exists('SellerSKUList.SellerSKU.1',$this->options)){ - $this->options['Action'] = 'GetLowestOfferListingsForSKU'; - $this->resetASINs(); - } else if (array_key_exists('ASINList.ASIN.1',$this->options)){ - $this->options['Action'] = 'GetLowestOfferListingsForASIN'; - $this->resetSKUs(); - } - } - - /** - * Fetches a list of your prices on products from Amazon. - * - * Submits a GetMyPriceForSKU - * or GetMyPriceForASIN request to Amazon. Amazon will send - * the list back as a response, which can be retrieved using getProduct. - * @return boolean FALSE if something goes wrong - */ - public function fetchMyPrice(){ - if (!array_key_exists('SellerSKUList.SellerSKU.1',$this->options) && !array_key_exists('ASINList.ASIN.1',$this->options)){ - $this->log("Product IDs must be set in order to look them up!",'Warning'); - return false; - } - - $this->prepareMyPrice(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $xml = $this->fetchMockFile(); - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body']); - } - - - $this->parseXML($xml); - - } - - /** - * Sets up options for using fetchMyPrice. - * - * This changes key options for using fetchMyPrice. - * Please note: because the operation does not use all of the parameters, - * the ExcludeMe parameter will be removed. - */ - protected function prepareMyPrice(){ - include($this->env); - if(isset($THROTTLE_TIME_PRODUCTPRICE)) { - $this->throttleTime = $THROTTLE_TIME_PRODUCTPRICE; - } - $this->throttleGroup = 'GetMyPrice'; - unset($this->options['ExcludeMe']); - if (array_key_exists('SellerSKUList.SellerSKU.1',$this->options)){ - $this->options['Action'] = 'GetMyPriceForSKU'; - $this->resetASINs(); - } else if (array_key_exists('ASINList.ASIN.1',$this->options)){ - $this->options['Action'] = 'GetMyPriceForASIN'; - $this->resetSKUs(); - } - } - - /** - * Fetches a list of categories for products from Amazon. - * - * Submits a GetProductCategoriesForSKU - * or GetProductCategoriesForASIN request to Amazon. Amazon will send - * the list back as a response, which can be retrieved using getProduct. - * @return boolean FALSE if something goes wrong - */ - public function fetchCategories(){ - if (!array_key_exists('SellerSKUList.SellerSKU.1',$this->options) && !array_key_exists('ASINList.ASIN.1',$this->options)){ - $this->log("Product IDs must be set in order to look them up!",'Warning'); - return false; - } - - $this->prepareCategories(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $xml = $this->fetchMockFile(); - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body']); - } - - $this->parseXML($xml); - - } - - /** - * Sets up options for using fetchCategories. - * - * This changes key options for using fetchCategories. - * Please note: because the operation does not use all of the parameters, - * some of the parameters will be removed. The following parameters are removed: - * ItemCondition and ExcludeMe. - */ - protected function prepareCategories(){ - include($this->env); - if(isset($THROTTLE_TIME_PRODUCTLIST)) { - $this->throttleTime = $THROTTLE_TIME_PRODUCTLIST; - } - $this->throttleGroup = 'GetProductCategories'; - unset($this->options['ExcludeMe']); - unset($this->options['ItemCondition']); - if (array_key_exists('SellerSKUList.SellerSKU.1',$this->options)){ - $this->options['Action'] = 'GetProductCategoriesForSKU'; - $this->resetASINs(); - } else if (array_key_exists('ASINList.ASIN.1',$this->options)){ - $this->options['Action'] = 'GetProductCategoriesForASIN'; - $this->resetSKUs(); - } - } - -} -?> \ No newline at end of file diff --git a/includes/classes/AmazonReportRequest.php b/includes/classes/AmazonReportRequest.php deleted file mode 100644 index c230e9b4..00000000 --- a/includes/classes/AmazonReportRequest.php +++ /dev/null @@ -1,413 +0,0 @@ -Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - include($this->env); - - $this->options['Action'] = 'RequestReport'; - - if(isset($THROTTLE_LIMIT_REPORTREQUEST)) { - $this->throttleLimit = $THROTTLE_LIMIT_REPORTREQUEST; - } - if(isset($THROTTLE_TIME_REPORTREQUEST)) { - $this->throttleTime = $THROTTLE_TIME_REPORTREQUEST; - } - $this->throttleGroup = 'RequestReport'; - } - - /** - * Sets the report type. (Required) - * - * This method sets the report type to be sent in the next request. - * This parameter is required for fetching the report from Amazon. - * @param string|integer $n

    See comment inside for a list of valid values.

    - * @return boolean FALSE if improper input - */ - public function setReportType($s){ - if (is_string($s) && $s){ - $this->options['ReportType'] = $s; - } else { - return false; - } - /* - * List of valid Report Types: - * Listings Reports: - * Open Listings Report ~ _GET_FLAT_FILE_OPEN_LISTINGS_DATA_ - * Open Listings Report ~ _GET_MERCHANT_LISTINGS_DATA_BACK_COMPAT_ - * Merchant Listings Report ~ _GET_MERCHANT_LISTINGS_DATA_ - * Merchant Listings Lite Report ~ _GET_MERCHANT_LISTINGS_DATA_LITE_ - * Merchant Listings Liter Report ~ _GET_MERCHANT_LISTINGS_DATA_LITER_ - * Canceled Listings Report ~ _GET_MERCHANT_CANCELLED_LISTINGS_DATA_ - * Quality Listing Report ~ _GET_MERCHANT_LISTINGS_DEFECT_DATA_ - * Order Reports: - * Unshipped Orders Report ~ _GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_ - * Flat File Order Report ~ _GET_FLAT_FILE_ORDER_REPORT_DATA_ - * Requested Flat File Order Report ~ _GET_FLAT_FILE_ORDERS_DATA_ - * Flat File Order Report ~ _GET_CONVERGED_FLAT_FILE_ORDER_REPORT_DATA_ - * Order Tracking Reports: - * Flat File Orders By Last Update Report ~ _GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_ - * Flat File Orders By Order Date Report ~ _GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_ - * XML Orders By Last Update Report ~ _GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_ - * XML Orders By Order Date Report ~ _GET_XML_ALL_ORDERS_DATA_BY_ORDER_DATE_ - * Pending Order Reports: - * Flat File Pending Orders Report ~ _GET_FLAT_FILE_PENDING_ORDERS_DATA_ - * XML Pending Orders Report ~ _GET_PENDING_ORDERS_DATA_ - * Converged Flat File Pending Orders Report ~ GET_CONVERGED_FLAT_FILE_PENDING_ORDERS_DATA_ - * Performance Reports: - * Flat File Feedback Report ~ _GET_SELLER_FEEDBACK_DATA_ - * FBA Reports: - * Flat File All Orders Report by Last Update ~ _GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_ - * Flat File All Orders Report by Order Date ~ _GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_ - * XML All Orders Report by Last Update ~ _GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_ - * XML All Orders Report by Order Date ~ _GET_XML_ALL_ORDERS_DATA_BY_ORDER_DATE_ - * FBA Inventory Report ~ _GET_AFN_INVENTORY_DATA_ - * FBA Fulfilled Shipments Report ~ _GET_AMAZON_FULFILLED_SHIPMENTS_DATA_ - * FBA Returns Report ~ _GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_ - * FBA Customer Shipment Sales Report ~ _GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_SALES_DATA_ - * Customer Taxes ~ _GET_FBA_FULFILLMENT_CUSTOMER_TAXES_DATA_ - * FBA Promotions Report ~ _GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_PROMOTION_DATA_ - * FBA Inbound Compliance Report ~ _GET_FBA_FULFILLMENT_INBOUND_NONCOMPLIANCE_DATA_ - * FBA Daily Inventory History Report ~ _GET_FBA_FULFILLMENT_CURRENT_INVENTORY_DATA_ - * FBA Monthly Inventory History Repoty ~ _GET_FBA_FULFILLMENT_MONTHLY_INVENTORY_DATA_ - * FBA Received Inventory Report ~ _GET_FBA_FULFILLMENT_INVENTORY_RECEIPTS_DATA_ - * FBA Inventory Event Detail Report ~ _GET_FBA_FULFILLMENT_INVENTORY_SUMMARY_DATA_ - * FBA Inventory Adjustments Report ~ _GET_FBA_FULFILLMENT_INVENTORY_ADJUSTMENTS_DATA_ - * FBA Inventory Health Report ~ _GET_FBA_FULFILLMENT_INVENTORY_HEALTH_DATA_ - * FBA Manage Inventory ~ _GET_FBA_MYI_UNSUPPRESSED_INVENTORY_DATA_ - * FBA Manage Inventory - Archived ~ _GET_FBA_MYI_ALL_INVENTORY_DATA_ - * FBA Replacements Report ~ _GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_REPLACEMENT_DATA_ - * FBA Cross-Border Inventory Movement Report ~ _GET_FBA_FULFILLMENT_CROSS_BORDER_INVENTORY_MOVEMENT_DATA_ - * FBA Recommended Removal Report ~ _GET_FBA_RECOMMENDED_REMOVAL_DATA_ - * Amazon Product Ads Report: - * Product Ads Listings Report ~ _GET_NEMO_MERCHANT_LISTINGS_DATA_ - * Product Ads Daily Performance by SKU Report, flat file ~ _GET_PADS_PRODUCT_PERFORMANCE_OVER_TIME_DAILY_DATA_TSV_ - * Product Ads Daily Performance by SKU Report, XML ~ _GET_PADS_PRODUCT_PERFORMANCE_OVER_TIME_DAILY_DATA_XML_ - * Product Ads Weekly Performance by SKU Report, flat file ~ _GET_PADS_PRODUCT_PERFORMANCE_OVER_TIME_WEEKLY_DATA_TSV_ - * Product Ads Weekly Performance by SKU Report, XML ~ _GET_PADS_PRODUCT_PERFORMANCE_OVER_TIME_WEEKLY_DATA_XML_ - * Product Ads Monthly Performance by SKU Report, flat file ~ _GET_PADS_PRODUCT_PERFORMANCE_OVER_TIME_MONTHLY_DATA_TSV_ - * Product Ads Monthly Performance by SKU Report, XML ~ _GET_PADS_PRODUCT_PERFORMANCE_OVER_TIME_MONTHLY_DATA_XML_ - */ - } - - /** - * Sets the time frame options. (Optional) - * - * This method sets the start and end times for the report request. If this - * parameter is set, the report will only contain data that was updated - * between the two times given. If these parameters are not set, the report - * will only contain the most recent data. - * The parameters are passed through strtotime, so values such as "-1 hour" are fine. - * @param string $s [optional]

    A time string for the earliest time.

    - * @param string $e [optional]

    A time string for the latest time.

    - */ - public function setTimeLimits($s = null,$e = null){ - if ($s && is_string($s)){ - $times = $this->genTime($s); - $this->options['StartDate'] = $times; - } - if ($e && is_string($e)){ - $timee = $this->genTime($e); - $this->options['EndDate'] = $timee; - } - if (isset($this->options['StartDate']) && - isset($this->options['EndDate']) && - $this->options['StartDate'] > $this->options['EndDate']){ - $this->setTimeLimits($this->options['EndDate'].' - 1 second'); - } - } - - /** - * Removes time limit options. - * - * Use this in case you change your mind and want to remove the time limit - * parameters you previously set. - */ - public function resetTimeLimits(){ - unset($this->options['StartDate']); - unset($this->options['EndDate']); - } - - /** - * Sets whether or not the report should return the Sales Channel column. (Optional) - * - * Setting this parameter to TRUE adds the Sales Channel column to the report. - * @param string|boolean $s

    "true" or "false", or boolean

    - * @return boolean FALSE if improper input - */ - public function setShowSalesChannel($s){ - if ($s == 'true' || (is_bool($s) && $s == true)){ - $this->options['ReportOptions=ShowSalesChannel'] = 'true'; - } else if ($s == 'false' || (is_bool($s) && $s == false)){ - $this->options['ReportOptions=ShowSalesChannel'] = 'false'; - } else { - return false; - } - } - - /** - * Sets the marketplace ID(s). (Optional) - * - * This method sets the list of marketplace IDs to be sent in the next request. - * If this parameter is set, the report will only contain data relevant to the - * marketplaces listed. - * @param array|string $s

    A list of marketplace IDs, or a single ID string.

    - * @return boolean FALSE if improper input - */ - public function setMarketplaces($s){ - if (is_string($s)){ - $this->resetMarketplaces(); - $this->options['MarketplaceIdList.Id.1'] = $s; - } else if (is_array($s)){ - $this->resetMarketplaces(); - $i = 1; - foreach ($s as $x){ - $this->options['MarketplaceIdList.Id.'.$i] = $x; - $i++; - } - } else { - return false; - } - } - - /** - * Removes marketplace ID options. - * - * Use this in case you change your mind and want to remove the Marketplace ID - * parameters you previously set. - */ - public function resetMarketplaces(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#MarketplaceIdList#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sends a report request to Amazon. - * - * Submits a RequestReport request to Amazon. In order to do this, - * a Report Type is required. Amazon will send info back as a response, - * which can be retrieved using getResponse. - * Other methods are available for fetching specific values from the list. - * @return boolean FALSE if something goes wrong - */ - public function requestReport(){ - if (!array_key_exists('ReportType',$this->options)){ - $this->log("Report Type must be set in order to request a report!",'Warning'); - return false; - } - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->parseXML($xml->ReportRequestInfo); - - } - - /** - * Parses XML response into array. - * - * This is what reads the response XML and converts it into an array. - * @param SimpleXMLObject $xml

    The XML response from Amazon.

    - * @return boolean FALSE if no XML data is found - */ - protected function parseXML($xml){ - if (!$xml){ - return false; - } - - $this->response = array(); - $this->response['ReportRequestId'] = (string)$xml->ReportRequestId; - $this->response['ReportType'] = (string)$xml->ReportType; - $this->response['StartDate'] = (string)$xml->StartDate; - $this->response['EndDate'] = (string)$xml->EndDate; - $this->response['Scheduled'] = (string)$xml->Scheduled; - $this->response['SubmittedDate'] = (string)$xml->SubmittedDate; - $this->response['ReportProcessingStatus'] = (string)$xml->ReportProcessingStatus; - - } - - /** - * Returns the full response. - * - * This method will return FALSE if the response data has not yet been filled. - * The returned array will have the following fields: - * - * @return array|boolean data array, or FALSE if list not filled yet - */ - public function getResponse(){ - if (isset($this->response)){ - return $this->response; - } else { - return false; - } - } - - /** - * Returns the report request ID from the response. - * - * This method will return FALSE if the response data has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getReportRequestId(){ - if (isset($this->response)){ - return $this->response['ReportRequestId']; - } else { - return false; - } - } - - /** - * Returns the report type from the response. - * - * This method will return FALSE if the response data has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getReportType(){ - if (isset($this->response)){ - return $this->response['ReportType']; - } else { - return false; - } - } - - /** - * Returns the start date for the report from the response. - * - * This method will return FALSE if the response data has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getStartDate(){ - if (isset($this->response)){ - return $this->response['StartDate']; - } else { - return false; - } - } - - /** - * Returns the end date for the report from the response. - * - * This method will return FALSE if the response data has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getEndDate(){ - if (isset($this->response)){ - return $this->response['EndDate']; - } else { - return false; - } - } - - /** - * Returns whether or not the report is scheduled from the response. - * - * This method will return FALSE if the response data has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean "true" or "false", or FALSE if Non-numeric index - */ - public function getIsScheduled(){ - if (isset($this->response)){ - return $this->response['Scheduled']; - } else { - return false; - } - } - - /** - * Returns the date the report was submitted from the response. - * - * This method will return FALSE if the response data has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getSubmittedDate(){ - if (isset($this->response)){ - return $this->response['SubmittedDate']; - } else { - return false; - } - } - - /** - * Returns the report processing status from the response. - * - * This method will return FALSE if the response data has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getStatus(){ - if (isset($this->response)){ - return $this->response['ReportProcessingStatus']; - } else { - return false; - } - } - -} -?> \ No newline at end of file diff --git a/includes/classes/AmazonReportRequestList.php b/includes/classes/AmazonReportRequestList.php deleted file mode 100644 index 18f0f584..00000000 --- a/includes/classes/AmazonReportRequestList.php +++ /dev/null @@ -1,746 +0,0 @@ -Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - include($this->env); - - if(isset($THROTTLE_LIMIT_REPORTREQUESTLIST)) { - $this->throttleLimit = $THROTTLE_LIMIT_REPORTREQUESTLIST; - } - if(isset($THROTTLE_TIME_REPORTREQUESTLIST)) { - $this->throttleTime = $THROTTLE_TIME_REPORTREQUESTLIST; - } - } - - /** - * Returns whether or not a token is available. - * @return boolean - */ - public function hasToken(){ - return $this->tokenFlag; - } - - /** - * Sets whether or not the object should automatically use tokens if it receives one. - * - * If this option is set to TRUE, the object will automatically perform - * the necessary operations to retrieve the rest of the list using tokens. If - * this option is off, the object will only ever retrieve the first section of - * the list. - * @param boolean $b [optional]

    Defaults to TRUE

    - * @return boolean FALSE if improper input - */ - public function setUseToken($b = true){ - if (is_bool($b)){ - $this->tokenUseFlag = $b; - } else { - return false; - } - } - - /** - * Sets the report request ID(s). (Optional) - * - * This method sets the list of report request IDs to be sent in the next request. - * @param array|string $s

    A list of report request IDs, or a single type string.

    - * @return boolean FALSE if improper input - */ - public function setRequestIds($s){ - if (is_string($s)){ - $this->resetRequestIds(); - $this->options['ReportRequestIdList.Id.1'] = $s; - } else if (is_array($s)){ - $this->resetRequestIds(); - $i = 1; - foreach ($s as $x){ - $this->options['ReportRequestIdList.Id.'.$i] = $x; - $i++; - } - } else { - return false; - } - } - - /** - * Removes report request ID options. - * - * Use this in case you change your mind and want to remove the Report Request ID - * parameters you previously set. - */ - public function resetRequestIds(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#ReportRequestIdList#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets the report type(s). (Optional) - * - * This method sets the list of report types to be sent in the next request. - * @param array|string $s

    A list of report types, or a single type string.

    - * @return boolean FALSE if improper input - */ - public function setReportTypes($s){ - if (is_string($s)){ - $this->resetReportTypes(); - $this->options['ReportTypeList.Type.1'] = $s; - } else if (is_array($s)){ - $this->resetReportTypes(); - $i = 1; - foreach ($s as $x){ - $this->options['ReportTypeList.Type.'.$i] = $x; - $i++; - } - } else { - return false; - } - } - - /** - * Removes report type options. - * - * Use this in case you change your mind and want to remove the Report Type - * parameters you previously set. - */ - public function resetReportTypes(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#ReportTypeList#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets the report status(es). (Optional) - * - * This method sets the list of report types to be sent in the next request. - * @param array|string $s

    A list of report types, or a single type string.

    - * @return boolean FALSE if improper input - */ - public function setReportStatuses($s){ - if (is_string($s)){ - $this->resetReportStatuses(); - $this->options['ReportProcessingStatusList.Status.1'] = $s; - } else if (is_array($s)){ - $this->resetReportStatuses(); - $i = 1; - foreach ($s as $x){ - $this->options['ReportProcessingStatusList.Status.'.$i] = $x; - $i++; - } - } else { - return false; - } - } - - /** - * Removes report status options. - * - * Use this in case you change your mind and want to remove the Report Status - * parameters you previously set. - */ - public function resetReportStatuses(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#ReportProcessingStatusList#",$op)){ - unset($this->options[$op]); - } - } - } - - /** - * Sets the maximum response count. (Optional) - * - * This method sets the maximum number of Report Requests for Amazon to return. - * If this parameter is not set, Amazon will only send 10 at a time. - * @param array|string $s

    Positive integer from 1 to 100.

    - * @return boolean FALSE if improper input - */ - public function setMaxCount($s){ - if (is_int($s) && $s >= 1 && $s <= 100){ - $this->options['MaxCount'] = $s; - } else { - return false; - } - } - - /** - * Sets the time frame options. (Optional) - * - * This method sets the start and end times for the next request. If this - * parameter is set, Amazon will only return Report Requests that were submitted - * between the two times given. If these parameters are not set, Amazon will - * only return Report Requests that were submitted within the past 90 days. - * The parameters are passed through strtotime, so values such as "-1 hour" are fine. - * @param string $s [optional]

    A time string for the earliest time.

    - * @param string $e [optional]

    A time string for the latest time.

    - */ - public function setTimeLimits($s = null,$e = null){ - if ($s && is_string($s)){ - $times = $this->genTime($s); - $this->options['RequestedFromDate'] = $times; - } - if ($e && is_string($e)){ - $timee = $this->genTime($e); - $this->options['RequestedToDate'] = $timee; - } - if (isset($this->options['RequestedFromDate']) && - isset($this->options['RequestedToDate']) && - $this->options['RequestedFromDate'] > $this->options['RequestedToDate']){ - $this->setTimeLimits($this->options['RequestedToDate'].' - 1 second'); - } - } - - /** - * Removes time limit options. - * - * Use this in case you change your mind and want to remove the time limit - * parameters you previously set. - */ - public function resetTimeLimits(){ - unset($this->options['RequestedFromDate']); - unset($this->options['RequestedToDate']); - } - - /** - * Fetches a list of Report Requests from Amazon. - * - * Submits a GetReportRequestList request to Amazon. Amazon will send - * the list back as a response, which can be retrieved using getList. - * Other methods are available for fetching specific values from the list. - * This operation can potentially involve tokens. - * @param boolean

    When set to FALSE, the function will not recurse, defaults to TRUE

    - * @return boolean FALSE if something goes wrong - */ - public function fetchRequestList($r = true){ - $this->prepareToken(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->parseXML($xml); - - $this->checkToken($xml); - - if ($this->tokenFlag && $this->tokenUseFlag && $r === true){ - while ($this->tokenFlag){ - $this->log("Recursively fetching more Report Requests"); - $this->fetchRequestList(false); - } - - } - - } - - /** - * Sets up options for using tokens. - * - * This changes key options for switching between simply fetching a list and - * fetching the rest of a list using a token. Please note: because the - * operation for using tokens does not use any other parameters, all other - * parameters will be removed. - */ - protected function prepareToken(){ - include($this->env); - if ($this->tokenFlag && $this->tokenUseFlag){ - $this->options['Action'] = 'GetReportRequestListByNextToken'; - if(isset($THROTTLE_LIMIT_REPORTTOKEN)) { - $this->throttleLimit = $THROTTLE_LIMIT_REPORTTOKEN; - } - if(isset($THROTTLE_TIME_REPORTTOKEN)) { - $this->throttleTime = $THROTTLE_TIME_REPORTTOKEN; - } - $this->throttleGroup = 'GetReportRequestListByNextToken'; - $this->resetRequestIds(); - $this->resetReportTypes(); - $this->resetReportStatuses(); - unset($this->options['MaxCount']); - unset($this->options['RequestedFromDate']); - unset($this->options['RequestedToDate']); - } else { - $this->options['Action'] = 'GetReportRequestList'; - if(isset($THROTTLE_LIMIT_REPORTREQUESTLIST)) { - $this->throttleLimit = $THROTTLE_LIMIT_REPORTREQUESTLIST; - } - if(isset($THROTTLE_TIME_REPORTREQUESTLIST)) { - $this->throttleTime = $THROTTLE_TIME_REPORTREQUESTLIST; - } - $this->throttleGroup = 'GetReportRequestList'; - unset($this->options['NextToken']); - $this->reportList = array(); - $this->index = 0; - } - } - - /** - * Sets up options for using CancelReportRequests. - * - * This changes key options for using CancelReportRequests. Please note: because the - * operation for cancelling feeds does not use all of the parameters, some of the - * parameters will be removed. The following parameters are removed: - * max count and token. - */ - protected function prepareCancel(){ - include($this->env); - $this->options['Action'] = 'CancelReportRequests'; - if(isset($THROTTLE_LIMIT_REPORTREQUESTLIST)) { - $this->throttleLimit = $THROTTLE_LIMIT_REPORTREQUESTLIST; - } - if(isset($THROTTLE_TIME_REPORTREQUESTLIST)) { - $this->throttleTime = $THROTTLE_TIME_REPORTREQUESTLIST; - } - $this->throttleGroup = 'CancelReportRequests'; - unset($this->options['MaxCount']); - unset($this->options['NextToken']); - } - - /** - * Parses XML response into array. - * - * This is what reads the response XML and converts it into an array. - * @param SimpleXMLObject $xml

    The XML response from Amazon.

    - * @return boolean FALSE if no XML data is found - */ - protected function parseXML($xml){ - if (!$xml){ - return false; - } - - foreach($xml->children() as $key=>$x){ - $i = $this->index; - if ($key == 'Count'){ - $this->count = (string)$x; - $this->log("Successfully canceled $this->count report requests."); - } - if ($key != 'ReportRequestInfo'){ - continue; - } - - $this->reportList[$i]['ReportRequestId'] = (string)$x->ReportRequestId; - $this->reportList[$i]['ReportType'] = (string)$x->ReportType; - $this->reportList[$i]['StartDate'] = (string)$x->StartDate; - $this->reportList[$i]['EndDate'] = (string)$x->EndDate; - $this->reportList[$i]['Scheduled'] = (string)$x->Scheduled; - $this->reportList[$i]['SubmittedDate'] = (string)$x->SubmittedDate; - $this->reportList[$i]['ReportProcessingStatus'] = (string)$x->ReportProcessingStatus; - $this->reportList[$i]['GeneratedReportId'] = (string)$x->GeneratedReportId; - $this->reportList[$i]['StartedProcessingDate'] = (string)$x->StartedProcessingDate; - $this->reportList[$i]['CompletedProcessingDate'] = (string)$x->CompletedProcessingDate; - - $this->index++; - } - } - - /** - * Cancels the report requests that match the given parameters. Careful! - * - * Submits a CancelReportRequests request to Amazon. Amazon will send - * as a response the list of feeds that were cancelled, along with the count - * of the number of affected feeds. This data can be retrieved using the same - * methods as with fetchRequestList and fetchCount. - * @return boolean FALSE if something goes wrong - */ - public function cancelRequests(){ - $this->prepareCancel(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->parseXML($xml); - - } - - /** - * Fetches a count of Report Requests from Amazon. - * - * Submits a GetReportRequestCount request to Amazon. Amazon will send - * the number back as a response, which can be retrieved using getCount. - * @return boolean FALSE if something goes wrong - */ - public function fetchCount(){ - $this->prepareCount(); - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; - } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ - return false; - } - - $xml = simplexml_load_string($response['body'])->$path; - } - - $this->count = (string)$xml->Count; - - } - - /** - * Sets up options for using countFeeds. - * - * This changes key options for using countFeeds. Please note: because the - * operation for counting feeds does not use all of the parameters, some of the - * parameters will be removed. The following parameters are removed: - * request IDs, max count, and token. - */ - protected function prepareCount(){ - include($this->env); - $this->options['Action'] = 'GetReportRequestCount'; - if(isset($THROTTLE_LIMIT_REPORTREQUESTLIST)) { - $this->throttleLimit = $THROTTLE_LIMIT_REPORTREQUESTLIST; - } - if(isset($THROTTLE_TIME_REPORTREQUESTLIST)) { - $this->throttleTime = $THROTTLE_TIME_REPORTREQUESTLIST; - } - $this->throttleGroup = 'GetReportRequestCount'; - unset($this->options['NextToken']); - unset($this->options['MaxCount']); - $this->resetRequestIds(); - } - - /** - * Returns the report request ID for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getRequestId($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['ReportRequestId']; - } else { - return false; - } - } - - /** - * Returns the report type for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getReportType($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['ReportType']; - } else { - return false; - } - } - - /** - * Returns the start date for the specified report request. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getStartDate($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['StartDate']; - } else { - return false; - } - } - - /** - * Returns the end date for the specified report request. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getEndDate($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['EndDate']; - } else { - return false; - } - } - - /** - * Returns whether or not the specified report request is scheduled. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getIsScheduled($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['Scheduled']; - } else { - return false; - } - } - - /** - * Returns the date the specified report request was submitted. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getSubmittedDate($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['SubmittedDate']; - } else { - return false; - } - } - - /** - * Returns the processing status for the specified report request. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getStatus($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['ReportProcessingStatus']; - } else { - return false; - } - } - - /** - * Returns the report ID for the specified entry. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getReportId($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['GeneratedReportId']; - } else { - return false; - } - } - - /** - * Returns the date processing for the specified report request started. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getDateProcessingStarted($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['StartedProcessingDate']; - } else { - return false; - } - } - - /** - * Returns the date processing for the specified report request was finished. - * - * This method will return FALSE if the list has not yet been filled. - * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    - * @return string|boolean single value, or FALSE if Non-numeric index - */ - public function getDateProcessingCompleted($i = 0){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]['CompletedProcessingDate']; - } else { - return false; - } - } - - /** - * Returns the full list. - * - * This method will return FALSE if the list has not yet been filled. - * The array for a single report will have the following fields: - * - * @param int $i [optional]

    List index to retrieve the value from. Defaults to NULL.

    - * @return array|boolean multi-dimensional array, or FALSE if list not filled yet - */ - public function getList($i = null){ - if (!isset($this->reportList)){ - return false; - } - if (is_int($i)){ - return $this->reportList[$i]; - } else { - return $this->reportList; - } - - } - - /** - * Returns the report request count. - * - * This method will return FALSE if the count has not been set yet. - * @return number|boolean number, or FALSE if count not set yet - */ - public function getCount(){ - if (isset($this->count)){ - return $this->count; - } else { - return false; - } - } - - /** - * Iterator function - * @return type - */ - public function current(){ - return $this->reportList[$this->i]; - } - - /** - * Iterator function - */ - public function rewind(){ - $this->i = 0; - } - - /** - * Iterator function - * @return type - */ - public function key() { - return $this->i; - } - - /** - * Iterator function - */ - public function next() { - $this->i++; - } - - /** - * Iterator function - * @return type - */ - public function valid() { - return isset($this->reportList[$this->i]); - } - -} -?> diff --git a/includes/classes/AmazonSellersCore.php b/includes/classes/AmazonSellersCore.php deleted file mode 100644 index 720f9a7f..00000000 --- a/includes/classes/AmazonSellersCore.php +++ /dev/null @@ -1,49 +0,0 @@ -Name for the store you want to use.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    - */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); - include($this->env); - - if(isset($AMAZON_VERSION_SELLERS)){ - $this->urlbranch = 'Sellers/'.$AMAZON_VERSION_SELLERS; - $this->options['Version'] = $AMAZON_VERSION_SELLERS; - } - } -} -?> diff --git a/includes/includes.php b/includes/includes.php deleted file mode 100644 index 3818d858..00000000 --- a/includes/includes.php +++ /dev/null @@ -1,20 +0,0 @@ - diff --git a/nbproject/project.properties b/nbproject/project.properties deleted file mode 100644 index 74c6d3aa..00000000 --- a/nbproject/project.properties +++ /dev/null @@ -1,22 +0,0 @@ -auxiliary.org-netbeans-modules-php-phpunit.bootstrap_2e_create_2e_tests=false -auxiliary.org-netbeans-modules-php-phpunit.bootstrap_2e_enabled=true -auxiliary.org-netbeans-modules-php-phpunit.bootstrap_2e_path=test-cases/bootstrap.php -auxiliary.org-netbeans-modules-php-phpunit.configuration_2e_path= -auxiliary.org-netbeans-modules-php-phpunit.customSuite_2e_path= -auxiliary.org-netbeans-modules-php-phpunit.phpUnit_2e_path= -auxiliary.org-netbeans-modules-php-phpunit.test_2e_groups_2e_ask=false -auxiliary.org-netbeans-modules-php-phpunit.test_2e_run_2e_all=false -file.reference.athena-includes=../../includes -file.reference.athena-includes-1=../../../includes -ignore.path= -include.path=\ - ${php.global.include.path}:\ - ${file.reference.athena-includes-1} -php.version=PHP_54 -source.encoding=UTF-8 -src.dir=. -tags.asp=false -tags.short=true -test.src.dir=test-cases -testing.providers=PhpUnit -web.root=. diff --git a/nbproject/project.xml b/nbproject/project.xml deleted file mode 100644 index a17b193d..00000000 --- a/nbproject/project.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - org.netbeans.modules.php.project - - - newAmazon - - - diff --git a/phpunit.xml b/phpunit.xml index 3347b75b..c861ca6c 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,18 +1,19 @@ - + - - ./tests/ + + tests/classes/ - + \ No newline at end of file diff --git a/src/Creacoon/AmazonMws/AmazonCore.php b/src/AmazonCore.php similarity index 53% rename from src/Creacoon/AmazonMws/AmazonCore.php rename to src/AmazonCore.php index 1423d35a..c198ab6f 100755 --- a/src/Creacoon/AmazonMws/AmazonCore.php +++ b/src/AmazonCore.php @@ -1,6 +1,8 @@ - *
  • Create an object (or objects) of the desired type.
  • @@ -92,7 +94,8 @@ * only non-"get" functions that will return the information. * */ -abstract class AmazonCore{ +abstract class AmazonCore +{ protected $urlbase; protected $urlbranch; protected $throttleLimit; @@ -100,6 +103,7 @@ abstract class AmazonCore{ protected $throttleSafe; protected $throttleGroup; protected $throttleStop = false; + protected $throttleCount = 0; protected $storeName; protected $options; protected $config; @@ -107,38 +111,42 @@ abstract class AmazonCore{ protected $mockFiles; protected $mockIndex = 0; protected $env; - protected $rawResponses = array(); - + protected $marketplaceId; + protected $rawResponses = []; + protected $proxyInfo = []; + /** * AmazonCore constructor sets up key information used in all Amazon requests. - * + * * This constructor is called when initializing all objects in this library. * The parameters are passed by the child objects' constructors. - * @param string $s

    Name for the store you want to use as seen in the config file. - * If this is not set to a valid name, none of these objects will work.

    - * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. - * When this is set to TRUE, the object will fetch responses from - * files you specify instead of sending the requests to Amazon. - * The log will indicate whether mock mode is on or off each time - * an object is initialized. This defaults to FALSE.

    - * @param array|string $m [optional]

    The files (or file) to use in Mock Mode. - * When Mock Mode is enabled, the object will retrieve one of these files - * from the list to use as a response. See setMock for more information.

    - * @param string $config [optional]

    An alternate config file to set. Used for testing.

    + * + * @param string $s

    Name for the store you want to use as seen in the config file. + * If this is not set to a valid name, none of these objects will work.

    + * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. + * When this is set to TRUE, the object will fetch responses from + * files you specify instead of sending the requests to Amazon. + * The log will indicate whether mock mode is on or off each time + * an object is initialized. This defaults to FALSE.

    + * @param array|string $m [optional]

    The files (or file) to use in Mock Mode. + * When Mock Mode is enabled, the object will retrieve one of these files + * from the list to use as a response. See setMock for more information.

    + * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - protected function __construct($s, $mock=false, $m = null, $config = null){ + protected function __construct($s, $mock = false, $m = null) + { $this->setConfig(); $this->setStore($s); - $this->setMock($mock,$m); + $this->setMock($mock, $m); - $this->env=__DIR__.'/environment.php'; - $this->options['SignatureVersion'] = 2; - $this->options['SignatureMethod'] = 'HmacSHA256'; + $this->env = __DIR__ . '/environment.php'; + $this->options[ 'SignatureVersion' ] = 2; + $this->options[ 'SignatureMethod' ] = 'HmacSHA256'; } - + /** * Enables or disables Mock Mode for the object. - * + * * Use this method when you want to test your object without sending * actual requests to Amazon. When Mock Mode is enabled, responses are * pulled from files you specify instead of sending the request. @@ -149,109 +157,122 @@ protected function __construct($s, $mock=false, $m = null, $config = null){ * This method is also used to set response codes used by certain functions. * Mock Mode is particularly useful when you need * to test functions such as canceling orders or adding new products. - * @param boolean $b [optional]

    When set to TRUE, Mock Mode is - * enabled for the object. Defaults to TRUE.

    + * + * @param boolean $b [optional]

    When set to TRUE, Mock Mode is + * enabled for the object. Defaults to TRUE.

    * @param array|string|integer $files [optional]

    The list of files (or single file) - * to be used with Mock Mode. If a single string is given, this method will - * put it into an array. Integers can also be given, for use in fetchMockResponse. - * These numbers should only be response codes, such as 200 or 404.

    + * to be used with Mock Mode. If a single string is given, this method will + * put it into an array. Integers can also be given, for use in fetchMockResponse. + * These numbers should only be response codes, such as 200 or 404.

    */ - public function setMock($b = true,$files = null){ - if (is_bool($b)){ + public function setMock($b = true, $files = null) + { + if (is_bool($b)) { $this->resetMock(true); $this->mockMode = $b; - if ($b){ + if ($b) { $this->log("Mock Mode set to ON"); } - - if (is_string($files)){ - $this->mockFiles = array(); - $this->mockFiles[0] = $files; + + if (is_string($files)) { + $this->mockFiles = []; + $this->mockFiles[ 0 ] = $files; $this->log("Single Mock File set: $files"); - } else if (is_array($files)){ - $this->mockFiles = $files; - $this->log("Mock files array set."); - } else if (is_numeric($files)){ - $this->mockFiles = array(); - $this->mockFiles[0] = $files; - $this->log("Single Mock Response set: $files"); + } else { + if (is_array($files)) { + $this->mockFiles = $files; + $this->log("Mock files array set."); + } else { + if (is_numeric($files)) { + $this->mockFiles = []; + $this->mockFiles[ 0 ] = $files; + $this->log("Single Mock Response set: $files"); + } + } } } } - + /** * Fetches the given mock file, or attempts to. - * + * * This method is only called when Mock Mode is enabled. This is where * files from the mock file list are retrieved and passed back to the caller. * The success or failure of the operation will be recorded in the log, * including the name and path of the file involved. For retrieving response * codes, see fetchMockResponse. + * * @param boolean $load [optional]

    Set this to FALSE to prevent the - * method from loading the file's contents into a SimpleXMLObject. This is - * for when the contents of the file are not in XML format, or if you simply - * want to retrieve the raw string of the file.

    + * method from loading the file's contents into a SimpleXMLObject. This is + * for when the contents of the file are not in XML format, or if you simply + * want to retrieve the raw string of the file.

    + * * @return SimpleXMLObject|string|boolean

    A SimpleXMLObject holding the * contents of the file, or a string of said contents if $load is set to * FALSE. The return will be FALSE if the file cannot be * fetched for any reason.

    */ - protected function fetchMockFile($load = true){ - if(!is_array($this->mockFiles) || !array_key_exists(0, $this->mockFiles)){ - $this->log("Attempted to retrieve mock files, but no mock files present",'Warning'); + protected function fetchMockFile($load = true) + { + if (!is_array($this->mockFiles) || !array_key_exists(0, $this->mockFiles)) { + $this->log("Attempted to retrieve mock files, but no mock files present", 'Warning'); return false; } - if(!array_key_exists($this->mockIndex, $this->mockFiles)){ + if (!array_key_exists($this->mockIndex, $this->mockFiles)) { $this->log("End of Mock List, resetting to 0"); $this->resetMock(); } //check for absolute/relative file paths - if (strpos($this->mockFiles[$this->mockIndex], '/') === 0 || strpos($this->mockFiles[$this->mockIndex], '..') === 0){ - $url = $this->mockFiles[$this->mockIndex]; + if (strpos($this->mockFiles[ $this->mockIndex ], '/') === 0 || strpos($this->mockFiles[ $this->mockIndex ], + '..') === 0 + ) { + $url = $this->mockFiles[ $this->mockIndex ]; } else { - $url = 'mock/'.$this->mockFiles[$this->mockIndex]; + $url = 'mock/' . $this->mockFiles[ $this->mockIndex ]; } $this->mockIndex++; - - - if(file_exists($url)){ - - try{ + + + if (file_exists($url)) { + + try { $this->log("Fetched Mock File: $url"); - if ($load){ + if ($load) { $return = simplexml_load_file($url); } else { $return = file_get_contents($url); } return $return; - } catch (\Exception $e){ - $this->log("Error when opening Mock File: $url - ".$e->getMessage(),'Warning'); + } catch (Exception $e) { + $this->log("Error when opening Mock File: $url - " . $e->getMessage(), 'Warning'); return false; } - + } else { - $this->log("Mock File not found: $url",'Warning'); + $this->log("Mock File not found: $url", 'Warning'); return false; } - + } - + /** * Sets mock index back to 0. - * + * * This method is used for returning to the beginning of the mock file list. + * * @param boolean $mute [optional]

    Set to TRUE to prevent logging.

    */ - protected function resetMock($mute = false){ + protected function resetMock($mute = false) + { $this->mockIndex = 0; - if (!$mute){ + if (!$mute) { $this->log("Mock List index reset to 0"); } } - + /** * Generates a fake HTTP response using the mock file list. - * + * * This method uses the response codes in the mock file list to generate an * HTTP response. The success or failure of this operation will be recorded * in the log, including the response code returned. This is only used by @@ -268,301 +289,379 @@ protected function resetMock($mute = false){ * the value FALSE if the response could not be found or does not * match the list of valid responses. */ - protected function fetchMockResponse(){ - if(!is_array($this->mockFiles) || !array_key_exists(0, $this->mockFiles)){ - $this->log("Attempted to retrieve mock responses, but no mock responses present",'Warning'); + protected function fetchMockResponse() + { + if (!is_array($this->mockFiles) || !array_key_exists(0, $this->mockFiles)) { + $this->log("Attempted to retrieve mock responses, but no mock responses present", 'Warning'); return false; } - if(!array_key_exists($this->mockIndex, $this->mockFiles)){ + if (!array_key_exists($this->mockIndex, $this->mockFiles)) { $this->log("End of Mock List, resetting to 0"); $this->resetMock(); } - if (!is_numeric($this->mockFiles[$this->mockIndex])){ - $this->log("fetchMockResponse only works with response code numbers",'Warning'); + if (!is_numeric($this->mockFiles[ $this->mockIndex ])) { + $this->log("fetchMockResponse only works with response code numbers", 'Warning'); return false; } - - $r = array(); - $r['head'] = 'HTTP/1.1 200 OK'; - $r['body'] = ''; - $r['code'] = $this->mockFiles[$this->mockIndex]; + + $r = []; + $r[ 'head' ] = 'HTTP/1.1 200 OK'; + $r[ 'body' ] = ''; + $r[ 'code' ] = $this->mockFiles[ $this->mockIndex ]; $this->mockIndex++; - if ($r['code'] == 200){ - $r['answer'] = 'OK'; - $r['ok'] = 1; - } else if ($r['code'] == 404){ - $r['answer'] = 'Not Found'; - $r['error'] = 'Not Found'; - $r['ok'] = 0; - } else if ($r['code'] == 503){ - $r['answer'] = 'Service Unavailable'; - $r['error'] = 'Service Unavailable'; - $r['ok'] = 0; - } else if ($r['code'] == 400){ - $r['answer'] = 'Bad Request'; - $r['error'] = 'Bad Request'; - $r['ok'] = 0; - } - - if ($r['code'] != 200){ - $r['body'] = ' + if ($r[ 'code' ] == 200) { + $r[ 'answer' ] = 'OK'; + $r[ 'ok' ] = 1; + } else { + if ($r[ 'code' ] == 404) { + $r[ 'answer' ] = 'Not Found'; + $r[ 'error' ] = 'Not Found'; + $r[ 'ok' ] = 0; + } else { + if ($r[ 'code' ] == 503) { + $r[ 'answer' ] = 'Service Unavailable'; + $r[ 'error' ] = 'Service Unavailable'; + $r[ 'ok' ] = 0; + } else { + if ($r[ 'code' ] == 400) { + $r[ 'answer' ] = 'Bad Request'; + $r[ 'error' ] = 'Bad Request'; + $r[ 'ok' ] = 0; + } + } + } + } + + if ($r[ 'code' ] != 200) { + $r[ 'body' ] = ' Sender - '.$r['error'].' - '.$r['answer'].' + ' . $r[ 'error' ] . ' + ' . $r[ 'answer' ] . ' 123 '; } - - - $r['headarray'] = array(); - $this->log("Returning Mock Response: ".$r['code']); + + + $r[ 'headarray' ] = []; + $this->log("Returning Mock Response: " . $r[ 'code' ]); return $r; } - + /** * Checks whether or not the response is OK. - * + * * Verifies whether or not the HTTP response has the 200 OK code. If the code * is not 200, the incident and error message returned are logged. + * * @param array $r

    The HTTP response array. Expects the array to have - * the fields code, body, and error.

    + * the fields code, body, and error.

    + * * @return boolean TRUE if the status is 200 OK, FALSE otherwise. */ - protected function checkResponse($r){ - if (!is_array($r) || !array_key_exists('code', $r)){ - $this->log("No Response found",'Warning'); + protected function checkResponse($r) + { + if (!is_array($r) || !array_key_exists('code', $r)) { + $this->log("No Response found", 'Warning'); return false; } - if ($r['code'] == 200){ + if ($r[ 'code' ] == 200) { return true; } else { - $xml = simplexml_load_string($r['body'])->Error; - $this->log("Bad Response! ".$r['code']." ".$r['error'].": ".$xml->Code." - ".$xml->Message,'Urgent'); + $xml = simplexml_load_string($r[ 'body' ])->Error; + $this->log("Bad Response! " . $r[ 'code' ] . " " . $r[ 'error' ] . ": " . $xml->Code . " - " . $xml->Message, + 'Urgent'); return false; } } - + // * // * Set the config file. - // * + // * // * This method can be used to change the config file after the object has // * been initiated. The file will not be set if it cannot be found or read. // * This is useful for testing, in cases where you want to use a different file. // * @param string $path

    The path to the config file.

    // * @throws Exception If the file cannot be found or read. - - public function setConfig(){ - $AMAZON_SERVICE_URL = Config::get('amazon-mws::AMAZON_SERVICE_URL'); - if (isset($AMAZON_SERVICE_URL)){ + public function setConfig() + { + $AMAZON_SERVICE_URL = Config::get('amazon-mws.AMAZON_SERVICE_URL'); + + if (isset($AMAZON_SERVICE_URL)) { $this->urlbase = $AMAZON_SERVICE_URL; } else { - throw new Exception("Config file does not exist or cannot be read! ($path)"); + throw new Exception("Config file does not exist or cannot be read!"); } } - + /** * Sets the store values. - * + * * This method sets a number of key values from the config file. These values * include your Merchant ID, Access Key ID, and Secret Key, and are critical * for making requests with Amazon. If the store cannot be found in the * config file, or if any of the key values are missing, * the incident will be logged. + * * @param string $s

    The store name to look for.

    + * * @throws Exception If the file can't be found. */ - public function setStore($s){ + public function setStore($s) + { // if (file_exists($this->config)){ // include($this->config); // } else { // throw new \Exception("Config file does not exist!"); // } - - $store = Config::get('amazon-mws::store'); - if(array_key_exists($s, $store)){ + $store = Config::get('amazon-mws.store'); + + if (array_key_exists($s, $store)) { $this->storeName = $s; - if(array_key_exists('merchantId', $store[$s])){ - $this->options['SellerId'] = $store[$s]['merchantId']; + if (array_key_exists('merchantId', $store[ $s ])) { + $this->options[ 'SellerId' ] = $store[ $s ][ 'merchantId' ]; } else { - $this->log("Merchant ID is missing!",'Warning'); + $this->log("Merchant ID is missing!", 'Warning'); } - if(array_key_exists('keyId', $store[$s])){ - $this->options['AWSAccessKeyId'] = $store[$s]['keyId']; + if (array_key_exists('keyId', $store[ $s ])) { + $this->options[ 'AWSAccessKeyId' ] = $store[ $s ][ 'keyId' ]; } else { - $this->log("Access Key ID is missing!",'Warning'); + $this->log("Access Key ID is missing!", 'Warning'); } - if(!array_key_exists('secretKey', $store[$s])){ - $this->log("Secret Key is missing!",'Warning'); + if (!array_key_exists('secretKey', $store[ $s ])) { + $this->log("Secret Key is missing!", 'Warning'); + } + // Overwrite Amazon service url if specified + if (array_key_exists('amazonServiceUrl', $store[ $s ])) { + $AMAZON_SERVICE_URL = $store[ $s ][ 'amazonServiceUrl' ]; + $this->urlbase = $AMAZON_SERVICE_URL; + } + if (array_key_exists('proxyInfo', $store[ $s ])) { + $this->proxyInfo = $store[ $s ][ 'proxyInfo' ]; + } + + if (array_key_exists('authToken', $store[ $s ]) && !empty($store[ $s ][ 'authToken' ])) { + $this->options[ 'MWSAuthToken' ] = $store[ $s ][ 'authToken' ]; } - + + if (array_key_exists('marketplaceId', $store[ $s ]) && !empty($store[ $s ][ 'marketplaceId' ])) { + $this->marketplaceId = $store[ $s ][ 'marketplaceId' ]; + } + } else { - throw new \Exception("Store $s does not exist!"); - $this->log("Store $s does not exist!",'Warning'); + $this->log("Store $s does not exist!", 'Warning'); + throw new Exception("Store $s does not exist!"); } } - + /** * Enables or disables the throttle stop. - * + * * When the throttle stop is enabled, throttled requests will not be repeated. * This setting is off by default. + * * @param boolean $b

    Defaults to TRUE.

    */ - public function setThrottleStop($b=true) { - $this->throttleStop=!empty($b); + public function setThrottleStop($b = true) + { + $this->throttleStop = !empty($b); } - + /** * Writes a message to the log. - * + * * This method adds a message line to the log file defined by the config. * This includes the priority level, user IP, and a backtrace of the call. - * @param string $msg

    The message to write to the log.

    + * + * @param string $msg

    The message to write to the log.

    * @param string $level [optional]

    The priority level of the message. - * This is merely for the benefit of the user and does not affect how - * the code runs. The values used in this library are "Info", "Warning", - * "Urgent", and "Throttle".

    + * This is merely for the benefit of the user and does not affect how + * the code runs. The values used in this library are "Info", "Warning", + * "Urgent", and "Throttle".

    + * * @return boolean FALSE if the message is empty, NULL if logging is muted * @throws Exception If the file can't be written to. */ - protected function log($msg, $level = 'Info'){ + protected function log($msg, $level = 'Info') + { if ($msg != false) { $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - $muteLog = Config::get('amazon-mws::muteLog'); - - switch ($level){ - case('Info'): $loglevel = 'info'; break; - case('Throttle'): $loglevel = 'info'; break; - case('Warning'): $loglevel = 'notice'; break; - case('Urgent'): $loglevel = 'error'; break; - default: $loglevel = 'info'; + $muteLog = Config::get('amazon-mws.muteLog'); + if (isset($muteLog) && $muteLog == true) { + return false; } - call_user_func(array('Log', $loglevel),$msg); - - if (isset($muteLog) && $muteLog == true){ - return; + + switch ($level) { + case('Info'): + $loglevel = 'info'; + break; + case('Throttle'): + $loglevel = 'info'; + break; + case('Warning'): + $loglevel = 'notice'; + break; + case('Urgent'): + $loglevel = 'error'; + break; + default: + $loglevel = 'info'; } - - if(isset($userName) && $userName != ''){ - $name = $userName; - }else{ - $name = 'guest'; + + call_user_func(['Log', $loglevel], $msg); + + if (isset($userName) && $userName != '') { + $name = $userName; + } else { + $name = 'guest'; } - - if(isset($backtrace) && isset($backtrace[1]) && isset($backtrace[1]['file']) && isset($backtrace[1]['line']) && isset($backtrace[1]['function'])){ - $fileName = basename($backtrace[1]['file']); - $file = $backtrace[1]['file']; - $line = $backtrace[1]['line']; - $function = $backtrace[1]['function']; - }else{ - $fileName = basename($backtrace[0]['file']); - $file = $backtrace[0]['file']; - $line = $backtrace[0]['line']; - $function = $backtrace[0]['function']; + + if (isset($backtrace) && isset($backtrace[ 1 ]) && isset($backtrace[ 1 ][ 'file' ]) && isset($backtrace[ 1 ][ 'line' ]) && isset($backtrace[ 1 ][ 'function' ])) { + $fileName = basename($backtrace[ 1 ][ 'file' ]); + $file = $backtrace[ 1 ][ 'file' ]; + $line = $backtrace[ 1 ][ 'line' ]; + $function = $backtrace[ 1 ][ 'function' ]; + } else { + $fileName = basename($backtrace[ 0 ][ 'file' ]); + $file = $backtrace[ 0 ][ 'file' ]; + $line = $backtrace[ 0 ][ 'line' ]; + $function = $backtrace[ 0 ][ 'function' ]; } - if(isset($_SERVER['REMOTE_ADDR'])){ - $ip = $_SERVER['REMOTE_ADDR']; - if($ip == '127.0.0.1')$ip = 'local';//save some char - }else{ - $ip = 'cli'; + if (isset($_SERVER[ 'REMOTE_ADDR' ])) { + $ip = $_SERVER[ 'REMOTE_ADDR' ]; + if ($ip == '127.0.0.1') { + $ip = 'local'; + }//save some char + } else { + $ip = 'cli'; } } else { return false; } } - + /** * Returns options array. - * + * * Gets the options for the object, for debugging or recording purposes. * Note that this also includes key information such as your Amazon Access Key ID. * @return array All of the options for the object. */ - public function getOptions(){ + public function getOptions() + { return $this->options; } - + /** * Generates timestamp in ISO8601 format. - * + * * This method creates a timestamp from the provided string in ISO8601 format. * The string given is passed through strtotime before being used. The - * value returned is actually two minutes early, to prevent it from tripping up + * value returned is actually 30 seconds early, to prevent it from tripping up * Amazon. If no time is given, the current time is used. + * * @param string $time [optional]

    The time to use. Since this value is - * passed through strtotime first, values such as "-1 hour" are fine. - * Defaults to the current time.

    - * @return string Unix timestamp of the time, minus 2 minutes. + * passed through strtotime first, values such as "-1 hour" are fine. + * Defaults to the current time.

    + * + * @return string Unix timestamp of the time, minus 30 seconds. */ - protected function genTime($time=false){ - if (!$time){ + protected function genTime($time = false) + { + if (!$time) { $time = time(); } else { - $time = strtotime($time); - + if (is_numeric($time)) { + $time = (int)$time; + } else { + if (is_string($time)) { + $time = strtotime($time); + } else { + throw new Exception('Invalid time input given'); + } + } } - return date('Y-m-d\TH:i:sO',$time-120); - + return date('c', $time - 120); + } - + /** * Handles generation of the signed query string. - * + * * This method uses the secret key from the config file to generate the * signed query string. * It also handles the creation of the timestamp option prior. * @return string query string to send to cURL * @throws Exception if config file or secret key is missing */ - protected function genQuery(){ + protected function genQuery() + { // if (file_exists($this->config)){ // include($this->config); // } else { // throw new Exception("Config file does not exist!"); // } - - $store = Config::get('amazon-mws::store'); - if (array_key_exists($this->storeName, $store) && array_key_exists('secretKey', $store[$this->storeName])){ - $secretKey = $store[$this->storeName]['secretKey']; + $store = Config::get('amazon-mws.store'); + + if (array_key_exists($this->storeName, $store) && array_key_exists('secretKey', $store[ $this->storeName ])) { + $secretKey = $store[ $this->storeName ][ 'secretKey' ]; } else { - throw new \Exception("Secret Key is missing!"); + throw new Exception("Secret Key is missing!"); } - - unset($this->options['Signature']); - $this->options['Timestamp'] = $this->genTime(); - $this->options['Signature'] = $this->_signParameters($this->options, $secretKey); + + unset($this->options[ 'Signature' ]); + $this->options[ 'Timestamp' ] = $this->genTime(); + $this->options[ 'Signature' ] = $this->_signParameters($this->options, $secretKey); return $this->_getParametersAsString($this->options); } - + /** * Sends a request to Amazon via cURL - * + * * This method will keep trying if the request was throttled. - * @param string $url

    URL to feed to cURL

    - * @param array $param

    parameter array to feed to cURL

    + * + * @param string $url

    URL to feed to cURL

    + * @param array $param

    parameter array to feed to cURL

    + * * @return array cURL response array */ - protected function sendRequest($url,$param){ - $this->log("Making request to Amazon: ".$this->options['Action']); - $response = $this->fetchURL($url,$param); - - while ($response['code'] == '503' && $this->throttleStop==false){ + protected function sendRequest($url, $param = []) + { + $this->log("Making request to Amazon: " . $this->options['Action']); + $this->throttleCount = 0; + if (!empty($param)) { + $response = $this->fetchURL($url, $param); + } else { + $query = $this->genQuery(); + $response = $this->fetchURL($url, ['Post' => $query]); + } + + if (!isset($response[ 'code' ])) { + $this->log("Unrecognized response: " . print_r($response, true)); + return null; + } + while ($response['code'] == '503' && $this->throttleStop == false) { + ++$this->throttleCount; $this->sleep(); - $response = $this->fetchURL($url,$param); + if (!empty($param)) { + $response = $this->fetchURL($url, $param); + } else { + $query = $this->genQuery(); + $response = $this->fetchURL($url, ['Post' => $query]); + } } - - $this->rawResponses[]=$response; + + $this->rawResponses[] = $response; return $response; } - + /** * Gives the latest response data received from Amazon. * Response arrays contain the following keys: @@ -574,181 +673,223 @@ protected function sendRequest($url,$param){ *
  • ok - Contains a 1 if the response was normal, or 0 if there was a problem
  • *
  • headarray - An associative array of the head data, for convenience
  • * + * * @param int $i [optional]

    If set, retrieves the specific response instead of the last one. * If the index for the response is not used, FALSE will be returned.

    - * @return array associative array of HTTP response or FALSE if not set yet + * @return array|boolean associative array of HTTP response or FALSE if not set yet */ - public function getLastResponse($i=NULL) { + public function getLastResponse($i = null) + { if (!isset($i)) { - $i=count($this->rawResponses)-1; + $i = count($this->rawResponses) - 1; } if ($i >= 0 && isset($this->rawResponses[$i])) { return $this->rawResponses[$i]; - } else { - return false; } + return false; } - + /** * Gives all response code received from Amazon. - * @return array list of associative arrays of HTTP response or FALSE if not set yet + * @return array|boolean list of associative arrays of HTTP response or FALSE if not set yet * @see getLastResponse */ - public function getRawResponses() { + public function getRawResponses() + { if (!empty($this->rawResponses)) { return $this->rawResponses; - } else { - return false; } + return false; } - + + /** + * Gives the number of times the last call to sendRequest was throttled + * @return int + * @see sendRequest + */ + public function getThrottleCountForLastRequest() + { + return $this->throttleCount; + } + /** * Sleeps for the throttle time and records to the log. */ - protected function sleep(){ + protected function sleep() + { flush(); $s = ($this->throttleTime == 1) ? '' : 's'; - $this->log("Request was throttled, Sleeping for ".$this->throttleTime." second$s",'Throttle'); + $this->log("Request was throttled, Sleeping for " . $this->throttleTime . " second$s", 'Throttle'); sleep($this->throttleTime); } - + /** * Checks for a token and changes the proper options + * * @param SimpleXMLObject $xml

    response data

    + * * @return boolean FALSE if no XML data */ - protected function checkToken($xml){ - if (!$xml){ + protected function checkToken($xml) + { + if (!$xml) { return false; } - if ($xml->NextToken){ + if ($xml->NextToken) { $this->tokenFlag = true; - $this->options['NextToken'] = (string)$xml->NextToken; + $this->options[ 'NextToken' ] = (string)$xml->NextToken; } else { - unset($this->options['NextToken']); + unset($this->options[ 'NextToken' ]); $this->tokenFlag = false; } } - + //Functions from Athena: - /** - * Get url or send POST data - * @param string $url - * @param array $param['Header'] - * $param['Post'] - * @return array $return['ok'] 1 - success, (0,-1) - fail - * $return['body'] - response - * $return['error'] - error, if "ok" is not 1 - * $return['head'] - http header - */ - function fetchURL ($url, $param) { - $return = array(); - + + /** + * Get url or send POST data + * + * @param string $url + * @param array $param ['Header'] + * $param['Post'] + * + * @return array $return['ok'] 1 - success, (0,-1) - fail + * $return['body'] - response + * $return['error'] - error, if "ok" is not 1 + * $return['head'] - http header + */ + function fetchURL($url, $param) + { + $return = []; + $ch = curl_init(); - - curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch,CURLOPT_TIMEOUT, 0); - curl_setopt($ch,CURLOPT_FORBID_REUSE, 1); - curl_setopt($ch,CURLOPT_FRESH_CONNECT, 1); - curl_setopt($ch,CURLOPT_HEADER, 1); - curl_setopt($ch,CURLOPT_URL,$url); - if (!empty($param)){ - if (!empty($param['Header'])){ - curl_setopt($ch,CURLOPT_HTTPHEADER, $param['Header']); + + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_TIMEOUT, 0); + curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); + curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); + curl_setopt($ch, CURLOPT_HEADER, 1); + curl_setopt($ch, CURLOPT_URL, $url); + if (!empty($param)) { + if (!empty($param[ 'Header' ])) { + curl_setopt($ch, CURLOPT_HTTPHEADER, $param[ 'Header' ]); } - if (!empty($param['Post'])){ - curl_setopt($ch,CURLOPT_POSTFIELDS, $param['Post']); + if (!empty($param[ 'Post' ])) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $param[ 'Post' ]); } } - + + if (!empty($this->proxyInfo) + && !empty($this->proxyInfo[ 'ip' ]) + && !empty($this->proxyInfo[ 'port' ]) + ) { + curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); + curl_setopt($ch, CURLOPT_PROXY, $this->proxyInfo[ 'ip' ]); + curl_setopt($ch, CURLOPT_PROXYPORT, $this->proxyInfo[ 'port' ]); + if (!empty($this->proxyInfo[ 'user_pwd' ])) { + curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->proxyInfo[ 'user_pwd' ]); + } + curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); + } + $data = curl_exec($ch); - if ( curl_errno($ch) ) { - $return['ok'] = -1; - $return['error'] = curl_error($ch); - return $return; + if (curl_errno($ch)) { + $return[ 'ok' ] = -1; + $return[ 'error' ] = curl_error($ch); + return $return; } - + if (is_numeric(strpos($data, 'HTTP/1.1 100 Continue'))) { - $data=str_replace('HTTP/1.1 100 Continue', '', $data); + $data = str_replace('HTTP/1.1 100 Continue', '', $data); } - $data = preg_split("/\r\n\r\n/",$data, 2, PREG_SPLIT_NO_EMPTY); + $data = preg_split("/\r\n\r\n/", $data, 2, PREG_SPLIT_NO_EMPTY); if (!empty($data)) { - $return['head'] = ( isset($data[0]) ? $data[0] : null ); - $return['body'] = ( isset($data[1]) ? $data[1] : null ); + $return[ 'head' ] = (isset($data[ 0 ]) ? $data[ 0 ] : null); + $return[ 'body' ] = (isset($data[ 1 ]) ? $data[ 1 ] : null); } else { - $return['head'] = null; - $return['body'] = null; + $return[ 'head' ] = null; + $return[ 'body' ] = null; } - + $matches = array(); - $data = preg_match("/HTTP\/[0-9.]+ ([0-9]+) (.+)\r\n/",$return['head'], $matches); + preg_match("/HTTP\/[0-9.]+ ([0-9]+) (.+)\r\n/", $return['head'], $matches); + $return['code'] = ''; + $return['answer'] = ''; if (!empty($matches)) { - $return['code'] = $matches[1]; - $return['answer'] = $matches[2]; + $return[ 'code' ] = $matches[ 1 ]; + $return[ 'answer' ] = $matches[ 2 ]; } - - $data = preg_match("/meta http-equiv=.refresh. +content=.[0-9]*;url=([^'\"]*)/i",$return['body'], $matches); + + preg_match("/meta http-equiv=.refresh. +content=.[0-9]*;url=([^'\"]*)/i", $return['body'], $matches); if (!empty($matches)) { - $return['location'] = $matches[1]; - $return['code'] = '301'; + $return[ 'location' ] = $matches[ 1 ]; + $return[ 'code' ] = '301'; } - - if ( $return['code'] == '200' || $return['code'] == '302' ) { - $return['ok'] = 1; + + if ($return[ 'code' ] == '200' || $return[ 'code' ] == '302') { + $return[ 'ok' ] = 1; } else { - $return['error'] = (($return['answer'] and $return['answer'] != 'OK') ? $return['answer'] : 'Something wrong!'); - $return['ok'] = 0; - } - - foreach (preg_split('/\n/', $return['head'], -1, PREG_SPLIT_NO_EMPTY) as $value) { - $data = preg_split('/:/', $value, 2, PREG_SPLIT_NO_EMPTY); - if (is_array($data) and isset($data['1'])) { - $return['headarray'][$data['0']] = trim($data['1']); - } + $return[ 'error' ] = (($return[ 'answer' ] and $return[ 'answer' ] != 'OK') ? $return[ 'answer' ] : 'Something wrong!'); + $return[ 'ok' ] = 0; } - + + foreach (preg_split('/\n/', $return[ 'head' ], -1, PREG_SPLIT_NO_EMPTY) as $value) { + $data = preg_split('/:/', $value, 2, PREG_SPLIT_NO_EMPTY); + if (is_array($data) and isset($data[ '1' ])) { + $return[ 'headarray' ][ $data[ '0' ] ] = trim($data[ '1' ]); + } + } + curl_close($ch); return $return; - } + } // End Functions from Athena - + // Functions from Amazon: /** * Reformats the provided string using rawurlencode while also replacing ~, copied from Amazon - * + * * Almost the same as using rawurlencode + * * @param string $value + * * @return string */ - protected function _urlencode($value) { + protected function _urlencode($value) + { return rawurlencode($value); - return str_replace('%7E', '~', rawurlencode($value)); } - + /** * Fuses all of the parameters together into a string, copied from Amazon + * * @param array $parameters + * * @return string */ - protected function _getParametersAsString(array $parameters) { - $queryParameters = array(); + protected function _getParametersAsString(array $parameters) + { + $queryParameters = []; foreach ($parameters as $key => $value) { $queryParameters[] = $key . '=' . $this->_urlencode($value); } return implode('&', $queryParameters); } - + /** * validates signature and sets up signing of them, copied from Amazon - * @param array $parameters + * + * @param array $parameters * @param string $key + * * @return string signed string * @throws Exception */ - protected function _signParameters(array $parameters, $key) { - $algorithm = $this->options['SignatureMethod']; + protected function _signParameters(array $parameters, $key) + { + $algorithm = $this->options[ 'SignatureMethod' ]; $stringToSign = null; - if (2 === $this->options['SignatureVersion']) { + if (2 === $this->options[ 'SignatureVersion' ]) { $stringToSign = $this->_calculateStringToSignV2($parameters); // var_dump($stringToSign); } else { @@ -756,54 +897,61 @@ protected function _signParameters(array $parameters, $key) { } return $this->_sign($stringToSign, $key, $algorithm); } - + /** * generates the string to sign, copied from Amazon + * * @param array $parameters - * @return type + * @return string */ - protected function _calculateStringToSignV2(array $parameters) { + protected function _calculateStringToSignV2(array $parameters) + { $data = 'POST'; $data .= "\n"; - $endpoint = parse_url ($this->urlbase.$this->urlbranch); - $data .= $endpoint['host']; + $endpoint = parse_url($this->urlbase . $this->urlbranch); + $data .= $endpoint[ 'host' ]; $data .= "\n"; - $uri = array_key_exists('path', $endpoint) ? $endpoint['path'] : null; + $uri = array_key_exists('path', $endpoint) ? $endpoint[ 'path' ] : null; if (!isset ($uri)) { - $uri = "/"; + $uri = "/"; } - $uriencoded = implode("/", array_map(array($this, "_urlencode"), explode("/", $uri))); + $uriencoded = implode("/", array_map([$this, "_urlencode"], explode("/", $uri))); $data .= $uriencoded; $data .= "\n"; uksort($parameters, 'strcmp'); $data .= $this->_getParametersAsString($parameters); return $data; } + /** * Runs the hash, copied from Amazon + * * @param string $data * @param string $key * @param string $algorithm 'HmacSHA1' or 'HmacSHA256' + * * @return string * @throws Exception */ - protected function _sign($data, $key, $algorithm) + protected function _sign($data, $key, $algorithm) { if ($algorithm === 'HmacSHA1') { $hash = 'sha1'; - } else if ($algorithm === 'HmacSHA256') { - $hash = 'sha256'; } else { - throw new Exception ("Non-supported signing method specified"); + if ($algorithm === 'HmacSHA256') { + $hash = 'sha256'; + } else { + throw new Exception ("Non-supported signing method specified"); + } } - + return base64_encode( hash_hmac($hash, $data, $key, true) ); } - + // -- End Functions from Amazon -- - + } ?> diff --git a/includes/classes/AmazonFeed.php b/src/AmazonFeed.php old mode 100644 new mode 100755 similarity index 76% rename from includes/classes/AmazonFeed.php rename to src/AmazonFeed.php index 67f6302f..735b5ae6 --- a/includes/classes/AmazonFeed.php +++ b/src/AmazonFeed.php @@ -1,4 +1,7 @@ -getResponse. */ -class AmazonFeed extends AmazonFeedsCore{ +class AmazonFeed extends AmazonFeedsCore +{ private $response; private $feedContent; private $feedMD5; - + /** * AmazonFeed submits a Feed to Amazon. - * + * * The parameters are passed to the parent constructor, which are * in turn passed to the AmazonCore constructor. See it for more information * on these parameters and common methods. @@ -41,62 +45,65 @@ class AmazonFeed extends AmazonFeedsCore{ * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); + public function __construct($s, $mock = false, $m = null) + { + parent::__construct($s, $mock, $m); include($this->env); - + $this->options['Action'] = 'SubmitFeed'; - - if(isset($THROTTLE_LIMIT_FEEDSUBMIT)) { + + if (isset($THROTTLE_LIMIT_FEEDSUBMIT)) { $this->throttleLimit = $THROTTLE_LIMIT_FEEDSUBMIT; } - if(isset($THROTTLE_TIME_FEEDSUBMIT)) { + if (isset($THROTTLE_TIME_FEEDSUBMIT)) { $this->throttleTime = $THROTTLE_TIME_FEEDSUBMIT; } $this->throttleGroup = 'SubmitFeed'; } - + /** * Sets the Feed Content. (Required) - * + * * Thie method sets the feed's contents from direct input. * This parameter is required in order to submit a feed to Amazon. * @param string $s

    The contents to put in the file.

    * It can be relative or absolute.

    * @return boolean FALSE if improper input */ - public function setFeedContent($s){ - if (is_string($s) && $s){ - $this->feedContent=$s; - $this->feedMD5 = base64_encode(md5($this->feedContent,true)); + public function setFeedContent($s) + { + if (is_string($s) && $s) { + $this->feedContent = $s; + $this->feedMD5 = base64_encode(md5($this->feedContent, true)); } else { return false; } } - + /** * Sets the Feed Content. (Required) - * + * * This method loads the contents of a file to send as the feed. This * parameter is required in order to submit a feed to Amazon. * @param string $url

    The path to a file you want to use. * It can be relative or absolute.

    */ - public function loadFeedFile($path){ - if (file_exists($path)){ - if (strpos($path, '/') == 0){ + public function loadFeedFile($path) + { + if (file_exists($path)) { + if (strpos($path, '/') == 0) { $this->feedContent = file_get_contents($path); } else { - $url = __DIR__.'/../../'.$path; //todo: change to current install dir + $url = __DIR__ . '/../../' . $path; //todo: change to current install dir $this->feedContent = file_get_contents($url); } - $this->feedMD5 = base64_encode(md5($this->feedContent,true)); + $this->feedMD5 = base64_encode(md5($this->feedContent, true)); } } - + /** * Sets the Feed Type. (Required) - * + * * This method sets the Feed Type to be sent in the next request. This tells * Amazon how the Feed should be processsed. * This parameter is required in order to submit a feed to Amazon. @@ -104,8 +111,9 @@ public function loadFeedFile($path){ * See the comment inside the function for the complete list.

    * @return boolean FALSE if improper input */ - public function setFeedType($s){ - if (is_string($s) && $s){ + public function setFeedType($s) + { + if (is_string($s) && $s) { $this->options['FeedType'] = $s; } else { return false; @@ -148,10 +156,10 @@ public function setFeedType($s){ * UIEE Inventory File ~ _POST_UIEE_BOOKLOADER_DATA_ */ } - + /** * Sets the request ID(s). (Optional) - * + * * This method sets the list of Marketplace IDs to be sent in the next request. * Setting this parameter tells Amazon to apply the Feed to more than one * Marketplace. These should be IDs for Marketplaces that you are registered @@ -160,42 +168,46 @@ public function setFeedType($s){ * @param array|string $s

    A list of Marketplace IDs, or a single ID string.

    * @return boolean FALSE if improper input */ - public function setMarketplaceIds($s){ - if ($s && is_string($s)){ + public function setMarketplaceIds($s) + { + if ($s && is_string($s)) { $this->resetMarketplaceIds(); $this->options['MarketplaceIdList.Id.1'] = $s; - } else if ($s && is_array($s)){ - $this->resetMarketplaceIds(); - $i = 1; - foreach ($s as $x){ - $this->options['MarketplaceIdList.Id.'.$i] = $x; - $i++; - } } else { - return false; + if ($s && is_array($s)) { + $this->resetMarketplaceIds(); + $i = 1; + foreach ($s as $x) { + $this->options['MarketplaceIdList.Id.' . $i] = $x; + $i++; + } + } else { + return false; + } } } - + /** * Removes ID options. - * + * * Use this in case you change your mind and want to remove the Marketplace ID * parameters you previously set. */ - public function resetMarketplaceIds(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#MarketplaceIdList#",$op)){ + public function resetMarketplaceIds() + { + foreach ($this->options as $op => $junk) { + if (preg_match("#MarketplaceIdList#", $op)) { unset($this->options[$op]); } } } - + /** * Turns on or off Purge mode. (Optional) - * - * + * + * * Warning! This parameter can only be used once every 24 hours! - * + * * This method sets whether or not the tab delimited feed you provide should * completely replace old data. Use this parameter only in exceptional cases. * If this is not set, Amazon assumes it to be false. @@ -203,107 +215,114 @@ public function resetMarketplaceIds(){ * a boolean or a string. It defaults to "true".

    * @return boolean FALSE if improper input */ - public function setPurge($s = 'true'){ - if ($s == 'true' || ($s && is_bool($s))){ - $this->log("Caution! Purge mode set!",'Warning'); + public function setPurge($s = 'true') + { + if ($s == 'true' || ($s && is_bool($s))) { + $this->log("Caution! Purge mode set!", 'Warning'); $this->options['PurgeAndReplace'] = 'true'; $this->throttleTime = 86400; - } else if ($s == 'false' || (!$s && is_bool($s))){ - $this->log("Purge mode deactivated."); - $this->options['PurgeAndReplace'] = 'false'; - include($this->env); - if(isset($THROTTLE_TIME_FEEDSUBMIT)) { - $this->throttleTime = $THROTTLE_TIME_FEEDSUBMIT; - } } else { - return false; + if ($s == 'false' || (!$s && is_bool($s))) { + $this->log("Purge mode deactivated."); + $this->options['PurgeAndReplace'] = 'false'; + include($this->env); + if (isset($THROTTLE_TIME_FEEDSUBMIT)) { + $this->throttleTime = $THROTTLE_TIME_FEEDSUBMIT; + } + } else { + return false; + } } } - + /** * Submits a feed to Amazon. - * + * * Submits a SubmitFeed request to Amazon. In order to do this, both * the feed's contents and feed type are required. The request will not be * sent if either of these are not set. Amazon will send a response back, * which can be retrieved using getResponse. * @return boolean FALSE if something goes wrong */ - public function submitFeed(){ - if (!$this->feedContent){ - $this->log("Feed's contents must be set in order to submit it!",'Warning'); + public function submitFeed() + { + if (!$this->feedContent) { + $this->log("Feed's contents must be set in order to submit it!", 'Warning'); return false; } - if (!array_key_exists('FeedType',$this->options)){ - $this->log("Feed Type must be set in order to submit a feed!",'Warning'); + if (!array_key_exists('FeedType', $this->options)) { + $this->log("Feed Type must be set in order to submit a feed!", 'Warning'); return false; } - - $url = $this->urlbase.$this->urlbranch; - + + $url = $this->urlbase . $this->urlbranch; + $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; + + $path = $this->options['Action'] . 'Result'; + if ($this->mockMode) { + $xml = $this->fetchMockFile()->$path; } else { $headers = $this->genHeader(); - $response = $this->sendRequest("$url?$query",array('Header'=>$headers,'Post'=>$this->feedContent)); - - if (!$this->checkResponse($response)){ + $response = $this->sendRequest("$url?$query", array('Header' => $headers, 'Post' => $this->feedContent)); + + if (!$this->checkResponse($response)) { return false; } - - if (isset($response['code']) && $response['code'] == '200'){ - $body = strstr($response['body'],'<'); + + if (isset($response['code']) && $response['code'] == '200') { + $body = strstr($response['body'], '<'); $xml = simplexml_load_string($body)->$path; } else { - $this->log("Unexpected response: ".print_r($response,true),'Warning'); + $this->log("Unexpected response: " . print_r($response, true), 'Warning'); $xml = simplexml_load_string($response['body'])->$path; } - - + + } - + $this->parseXML($xml->FeedSubmissionInfo); - + } - + /** * Parses XML response into array. - * + * * This is what reads the response XML and converts it into an array. * @param SimpleXMLObject $xml

    The XML response from Amazon.

    * @return boolean FALSE if no XML data is found */ - protected function parseXML($xml){ - if (!$xml){ + protected function parseXML($xml) + { + if (!$xml) { return false; } - + $this->response = array(); $this->response['FeedSubmissionId'] = (string)$xml->FeedSubmissionId; $this->response['FeedType'] = (string)$xml->FeedType; $this->response['SubmittedDate'] = (string)$xml->SubmittedDate; $this->response['FeedProcessingStatus'] = (string)$xml->FeedProcessingStatus; - - $this->log("Successfully submitted feed #".$this->response['FeedSubmissionId'].' ('.$this->response['FeedType'].')'); + + $this->log("Successfully submitted feed #" . $this->response['FeedSubmissionId'] . ' (' . $this->response['FeedType'] . ')'); } - + /** * Generates array for Header. - * + * * This method creates the Header array to use with cURL. It contains the Content MD5. * @return array */ - protected function genHeader(){ - $return[0] = "Content-MD5:".$this->feedMD5; + protected function genHeader() + { + $return[0] = "Content-Type: text/xml"; + $return[1] = "Content-MD5:" . $this->feedMD5; return $return; } - + /** * Checks whether or not the response is OK. - * + * * Verifies whether or not the HTTP response has the 200 OK code. If the code * is not 200, the incident and error message returned are logged. This method * is different than the ones used by other objects due to Amazon sending @@ -312,24 +331,25 @@ protected function genHeader(){ * the fields code, body, and error.

    * @return boolean TRUE if the status is 200 OK, FALSE otherwise. */ - protected function checkResponse($r){ - if (!is_array($r)){ - $this->log("No Response found",'Warning'); + protected function checkResponse($r) + { + if (!is_array($r)) { + $this->log("No Response found", 'Warning'); return false; } //for dealing with 100 response - if (array_key_exists('error', $r) && $r['ok'] == 0){ - $this->log("Response Not OK! Error: ".$r['error'],'Urgent'); + if (array_key_exists('error', $r) && $r['ok'] == 0) { + $this->log("Response Not OK! Error: " . $r['error'], 'Urgent'); return false; } else { $this->log("Response OK!"); return true; } } - + /** * Returns the response data in array. - * + * * It will contain the following fields: * * @return array */ - public function getResponse(){ - if (isset($this->response)){ + public function getResponse() + { + if (isset($this->response)) { return $this->response; } else { return false; } } - - - + + } -?> \ No newline at end of file + +?> diff --git a/includes/classes/AmazonFeedList.php b/src/AmazonFeedList.php old mode 100644 new mode 100755 similarity index 97% rename from includes/classes/AmazonFeedList.php rename to src/AmazonFeedList.php index 6b2ccca7..95506b9c --- a/includes/classes/AmazonFeedList.php +++ b/src/AmazonFeedList.php @@ -1,4 +1,8 @@ -The files (or file) to use in Mock Mode.

    * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); + public function __construct($s, $mock = false, $m = null){ + parent::__construct($s, $mock, $m); include($this->env); if(isset($THROTTLE_LIMIT_FEEDLIST)) { @@ -268,13 +273,11 @@ public function fetchFeedSubmissions($r = true){ $url = $this->urlbase.$this->urlbranch; - $query = $this->genQuery(); - $path = $this->options['Action'].'Result'; if ($this->mockMode){ $xml = $this->fetchMockFile()->$path; } else { - $response = $this->sendRequest($url, array('Post'=>$query)); + $response = $this->sendRequest($url); if (!$this->checkResponse($response)){ return false; @@ -378,13 +381,11 @@ public function countFeeds(){ $url = $this->urlbase.$this->urlbranch; - $query = $this->genQuery(); - $path = $this->options['Action'].'Result'; if ($this->mockMode){ $xml = $this->fetchMockFile()->$path; } else { - $response = $this->sendRequest($url, array('Post'=>$query)); + $response = $this->sendRequest($url); if (!$this->checkResponse($response)){ return false; @@ -433,13 +434,11 @@ public function cancelFeeds(){ $url = $this->urlbase.$this->urlbranch; - $query = $this->genQuery(); - $path = $this->options['Action'].'Result'; if ($this->mockMode){ $xml = $this->fetchMockFile()->$path; } else { - $response = $this->sendRequest($url, array('Post'=>$query)); + $response = $this->sendRequest($url); if (!$this->checkResponse($response)){ return false; @@ -626,4 +625,4 @@ public function valid() { } } -?> \ No newline at end of file +?> diff --git a/src/Creacoon/AmazonMws/AmazonFeedResult.php b/src/AmazonFeedResult.php similarity index 74% rename from src/Creacoon/AmazonMws/AmazonFeedResult.php rename to src/AmazonFeedResult.php index cd008455..15f7a048 100755 --- a/src/Creacoon/AmazonMws/AmazonFeedResult.php +++ b/src/AmazonFeedResult.php @@ -1,4 +1,6 @@ -The files (or file) to use in Mock Mode.

    * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - public function __construct($s, $id = null, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); + public function __construct($s, $id = null, $mock = false, $m = null) + { + parent::__construct($s, $mock, $m); include($this->env); - - if($id){ + + if ($id) { $this->options['FeedSubmissionId'] = $id; } - + $this->options['Action'] = 'GetFeedSubmissionResult'; - - if(isset($THROTTLE_LIMIT_FEEDRESULT)) { + + if (isset($THROTTLE_LIMIT_FEEDRESULT)) { $this->throttleLimit = $THROTTLE_LIMIT_FEEDRESULT; } - if(isset($THROTTLE_TIME_FEEDRESULT)) { + if (isset($THROTTLE_TIME_FEEDRESULT)) { $this->throttleTime = $THROTTLE_TIME_FEEDRESULT; } $this->throttleGroup = 'GetFeedSubmissionResult'; } - + /** * Sets the feed submission ID for the next request. (Required) - * + * * This method sets the feed submission ID to be sent in the next request. This * parameter is required in order to retrieve a feed from Amazon. * @param string|integer $n

    Must be numeric

    * @return boolean FALSE if improper input */ - public function setFeedId($n){ - if (is_numeric($n)){ + public function setFeedId($n) + { + if (is_numeric($n)) { $this->options['FeedSubmissionId'] = $n; } else { return false; } } - + /** * Sends a request to Amazon for a feed. - * + * * Submits a GetFeedSubmissionResult request to Amazon. In order to * do this, a feed submission ID is required. Amazon will send back the raw results * of the feed as a response, which can be saved to a file using saveFeed. * @return boolean FALSE if something goes wrong */ - public function fetchFeedResult(){ - if (!array_key_exists('FeedSubmissionId',$this->options)){ - $this->log("Feed Submission ID must be set in order to fetch it!",'Warning'); + public function fetchFeedResult() + { + if (!array_key_exists('FeedSubmissionId', $this->options)) { + $this->log("Feed Submission ID must be set in order to fetch it!", 'Warning'); return false; } - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ - $this->rawFeed = $this->fetchMockFile(false); + + $url = $this->urlbase . $this->urlbranch; + + if ($this->mockMode) { + $this->rawFeed = $this->fetchMockFile(false); } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ + $response = $this->sendRequest($url); + + if (!$this->checkResponse($response)) { return false; } - + $this->rawFeed = $response['body']; } - + } - + /** * Saves the raw report data to a path you specify. - * + * * This method will record in the log whether or not the save was successful. * @param string $path

    path for the file to save the feed data in

    * @return boolean FALSE if something goes wrong */ - public function saveFeed($path){ - if (!isset($this->rawFeed)){ + public function saveFeed($path) + { + if (!isset($this->rawFeed)) { return false; } - try{ - file_put_contents($path,$this->rawFeed); - $this->log("Successfully saved feed #".$this->options['FeedSubmissionId']." at $path"); - } catch (Exception $e){ - $this->log("Unable to save feed #".$this->options['FeedSubmissionId']." at $path: ".$e->getMessage(),'Urgent'); + try { + file_put_contents($path, $this->rawFeed); + $this->log("Successfully saved feed #" . $this->options['FeedSubmissionId'] . " at $path"); + } catch (Exception $e) { + $this->log("Unable to save feed #" . $this->options['FeedSubmissionId'] . " at $path: " . $e->getMessage(), + 'Urgent'); return false; } } - + /** * Returns the entire raw report data. - * + * * This is useful for handling the report with an external file management system. * @return string|boolean The raw report data as a string, or FALSE if there is no data */ - public function getRawFeed() { - if (!isset($this->rawFeed)){ + public function getRawFeed() + { + if (!isset($this->rawFeed)) { return false; } return $this->rawFeed; } - + } + ?> \ No newline at end of file diff --git a/src/Creacoon/AmazonMws/AmazonFeedsCore.php b/src/AmazonFeedsCore.php similarity index 85% rename from src/Creacoon/AmazonMws/AmazonFeedsCore.php rename to src/AmazonFeedsCore.php index 249d4456..768a72d4 100755 --- a/src/Creacoon/AmazonMws/AmazonFeedsCore.php +++ b/src/AmazonFeedsCore.php @@ -1,4 +1,7 @@ -The files (or file) to use in Mock Mode.

    * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); + public function __construct($s, $mock = false, $m = null) + { + parent::__construct($s, $mock, $m); include($this->env); - + $this->urlbranch = ''; - if(isset($AMAZON_VERSION_FEEDS)) { + if (isset($AMAZON_VERSION_FEEDS)) { $this->options['Version'] = $AMAZON_VERSION_FEEDS; } } } + ?> diff --git a/includes/classes/AmazonInboundCore.php b/src/AmazonFinanceCore.php similarity index 55% rename from includes/classes/AmazonInboundCore.php rename to src/AmazonFinanceCore.php index 62b755fc..3c149044 100644 --- a/includes/classes/AmazonInboundCore.php +++ b/src/AmazonFinanceCore.php @@ -1,4 +1,6 @@ -Name for the store you want to use.

    + * @param string $s [optional]

    Name for the store you want to use. + * This parameter is optional if only one store is defined in the config file.

    * @param boolean $mock [optional]

    This is a flag for enabling Mock Mode. * This defaults to FALSE.

    * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - public function __construct($s, $mock = false, $m = null, $config = null){ - parent::__construct($s, $mock, $m, $config); + public function __construct($s = null, $mock = false, $m = null){ + parent::__construct($s, $mock, $m); include($this->env); - - if(isset($AMAZON_VERSION_INBOUND)){ - $this->urlbranch = 'FulfillmentInboundShipment/'.$AMAZON_VERSION_INBOUND; - $this->options['Version'] = $AMAZON_VERSION_INBOUND; + + if(isset($AMAZON_VERSION_FINANCE)){ + $this->urlbranch = 'Finances/'.$AMAZON_VERSION_FINANCE; + $this->options['Version'] = $AMAZON_VERSION_FINANCE; } - - - if(isset($THROTTLE_LIMIT_INVENTORY)) { - $this->throttleLimit = $THROTTLE_LIMIT_INVENTORY; + + if(isset($THROTTLE_LIMIT_FINANCE)) { + $this->throttleLimit = $THROTTLE_LIMIT_FINANCE; } - if(isset($THROTTLE_TIME_INVENTORY)) { - $this->throttleTime = $THROTTLE_TIME_INVENTORY; + if(isset($THROTTLE_TIME_FINANCE)) { + $this->throttleTime = $THROTTLE_TIME_FINANCE; } - $this->throttleGroup = 'Inventory'; + $this->throttleGroup = 'Finance'; } } -?> diff --git a/src/AmazonFinancialEventList.php b/src/AmazonFinancialEventList.php new file mode 100644 index 00000000..175b153b --- /dev/null +++ b/src/AmazonFinancialEventList.php @@ -0,0 +1,994 @@ +tokenFlag; + } + + /** + * Sets whether or not the object should automatically use tokens if it receives one. + * + * If this option is set to TRUE, the object will automatically perform + * the necessary operations to retrieve the rest of the list using tokens. If + * this option is off, the object will only ever retrieve the first section of + * the list. + * @param boolean $b [optional]

    Defaults to TRUE

    + * @return boolean FALSE if improper input + */ + public function setUseToken($b = true) { + if (is_bool($b)) { + $this->tokenUseFlag = $b; + } else { + return false; + } + } + + /** + * Sets the maximum number of responses per page. (Optional) + * + * This method sets the maximum number of Financial Events for Amazon to return per page. + * If this parameter is not set, Amazon will send 100 at a time. + * @param int $num

    Positive integer from 1 to 100.

    + * @return boolean FALSE if improper input + */ + public function setMaxResultsPerPage($num){ + if (is_numeric($num) && $num <= 100 && $num >= 1){ + $this->options['MaxResultsPerPage'] = $num; + } else { + return false; + } + } + + /** + * Sets the order ID filter. (Required*) + * + * If this parameter is set, Amazon will only return Financial Events that + * relate to the given order. This parameter is required if none of the + * other filter options are set. + * If this parameter is set, the group ID and time range options will be removed. + * @param string $s

    Amazon Order ID in 3-7-7 format

    + * @return boolean FALSE if improper input + */ + public function setOrderFilter($s){ + if ($s && is_string($s)) { + $this->resetFilters(); + $this->options['AmazonOrderId'] = $s; + } else { + return false; + } + } + + /** + * Sets the financial event group ID filter. (Required*) + * + * If this parameter is set, Amazon will only return Financial Events that + * belong to the given financial event group. This parameter is required if + * none of the other filter options are set. + * If this parameter is set, the order ID and time range options will be removed. + * @param string $s

    Financial Event Group ID

    + * @return boolean FALSE if improper input + */ + public function setGroupFilter($s){ + if ($s && is_string($s)) { + $this->resetFilters(); + $this->options['FinancialEventGroupId'] = $s; + } else { + return false; + } + } + + /** + * Sets the time frame options. (Required*) + * + * This method sets the start and end times for the next request. If this + * parameter is set, Amazon will only return Financial Events posted + * between the two times given. This parameter is required if none of the + * other filter options are set. + * The parameters are passed through strtotime, so values such as "-1 hour" are fine. + * If this parameter is set, the order ID and group ID options will be removed. + * @param string $s

    A time string for the earliest time.

    + * @param string $e [optional]

    A time string for the latest time.

    + * @return boolean FALSE if improper input + */ + public function setTimeLimits($s, $e = null) { + if (empty($s)) { + return FALSE; + } + $this->resetFilters(); + + $times = $this->genTime($s); + $this->options['PostedAfter'] = $times; + if (!empty($e)) { + $timee = $this->genTime($e); + $this->options['PostedBefore'] = $timee; + } + } + + /** + * Removes time limit options. + * + * Use this in case you change your mind and want to remove the time limit + * parameters you previously set. + */ + public function resetTimeLimits(){ + unset($this->options['PostedAfter']); + unset($this->options['PostedBefore']); + } + + /** + * Removes all filter options. + * + * Use this in case you change your mind and want to remove all filter + * parameters you previously set. + */ + public function resetFilters(){ + unset($this->options['AmazonOrderId']); + unset($this->options['FinancialEventGroupId']); + $this->resetTimeLimits(); + } + + /** + * Fetches the inventory supply list from Amazon. + * + * Submits a ListFinancialEvents request to Amazon. Amazon will send + * the list back as a response, which can be retrieved using getEvents. + * Other methods are available for fetching specific values from the list. + * This operation can potentially involve tokens. + * @param boolean $r [optional]

    When set to FALSE, the function will not recurse, defaults to TRUE

    + * @return boolean FALSE if something goes wrong + */ + public function fetchEventList($r = true) { + $this->prepareToken(); + + $url = $this->urlbase.$this->urlbranch; + + $path = $this->options['Action'].'Result'; + + if ($this->mockMode) { + $xml = $this->fetchMockFile()->$path; + } else { + $response = $this->sendRequest($url); + + if (!$this->checkResponse($response)) { + return false; + } + + $xml = simplexml_load_string($response['body'])->$path; + } + + $this->parseXml($xml->FinancialEvents); + + $this->checkToken($xml); + + if ($this->tokenFlag && $this->tokenUseFlag && $r === true) { + while ($this->tokenFlag) { + $this->log("Recursively fetching more Financial Events"); + $this->fetchEventList(false); + } + } + } + + /** + * Sets up options for using tokens. + * + * This changes key options for switching between simply fetching a list and + * fetching the rest of a list using a token. Please note: because the + * operation for using tokens does not use any other parameters, all other + * parameters will be removed. + */ + protected function prepareToken() { + if ($this->tokenFlag && $this->tokenUseFlag) { + $this->options['Action'] = 'ListFinancialEventsByNextToken'; + unset($this->options['MaxResultsPerPage']); + $this->resetFilters(); + } else { + $this->options['Action'] = 'ListFinancialEvents'; + unset($this->options['NextToken']); + $this->list = array(); + } + } + + /** + * Parses XML response into array. + * + * This is what reads the response XML and converts it into an array. + * @param SimpleXMLElement $xml

    The XML response from Amazon.

    + * @return boolean FALSE if no XML data is found + */ + protected function parseXml($xml) { + if (!$xml) { + return false; + } + if (isset($xml->ShipmentEventList)) { + foreach($xml->ShipmentEventList->children() as $x) { + $this->list['Shipment'][] = $this->parseShipmentEvent($x); + } + } + if (isset($xml->RefundEventList)) { + foreach($xml->RefundEventList->children() as $x) { + $this->list['Refund'][] = $this->parseShipmentEvent($x); + } + } + if (isset($xml->GuaranteeClaimEventList)) { + foreach($xml->GuaranteeClaimEventList->children() as $x) { + $this->list['GuaranteeClaim'][] = $this->parseShipmentEvent($x); + } + } + if (isset($xml->ChargebackEventList)) { + foreach($xml->ChargebackEventList->children() as $x) { + $this->list['Chargeback'][] = $this->parseShipmentEvent($x); + } + } + if (isset($xml->PayWithAmazonEventList)) { + foreach($xml->PayWithAmazonEventList->children() as $x) { + $temp = array(); + $temp['SellerOrderId'] = (string)$x->SellerOrderId; + $temp['TransactionPostedDate'] = (string)$x->TransactionPostedDate; + $temp['BusinessObjectType'] = (string)$x->BusinessObjectType; + $temp['SalesChannel'] = (string)$x->SalesChannel; + $temp['Charge'] = $this->parseCharge($x->Charge); + if (isset($x->FeeList)) { + foreach($x->FeeList->children() as $z) { + $temp['FeeList'][] = $this->parseFee($z); + } + } + $temp['PaymentAmountType'] = (string)$x->PaymentAmountType; + $temp['AmountDescription'] = (string)$x->AmountDescription; + $temp['FulfillmentChannel'] = (string)$x->FulfillmentChannel; + $temp['StoreName'] = (string)$x->StoreName; + $this->list['PayWithAmazon'][] = $temp; + } + } + if (isset($xml->ServiceProviderCreditEventList)) { + foreach($xml->ServiceProviderCreditEventList->children() as $x) { + $temp = array(); + $temp['ProviderTransactionType'] = (string)$x->ProviderTransactionType; + $temp['SellerOrderId'] = (string)$x->SellerOrderId; + $temp['MarketplaceId'] = (string)$x->MarketplaceId; + $temp['MarketplaceCountryCode'] = (string)$x->MarketplaceCountryCode; + $temp['SellerId'] = (string)$x->SellerId; + $temp['SellerStoreName'] = (string)$x->SellerStoreName; + $temp['ProviderId'] = (string)$x->ProviderId; + $temp['ProviderStoreName'] = (string)$x->ProviderStoreName; + $this->list['ServiceProviderCredit'][] = $temp; + } + } + if (isset($xml->RetrochargeEventList)) { + foreach($xml->RetrochargeEventList->children() as $x) { + $temp = array(); + $temp['RetrochargeEventType'] = (string)$x->RetrochargeEventType; + $temp['AmazonOrderId'] = (string)$x->AmazonOrderId; + $temp['PostedDate'] = (string)$x->PostedDate; + $temp['BaseTax']['Amount'] = (string)$x->BaseTax->CurrencyAmount; + $temp['BaseTax']['CurrencyCode'] = (string)$x->BaseTax->CurrencyCode; + $temp['ShippingTax']['Amount'] = (string)$x->ShippingTax->CurrencyAmount; + $temp['ShippingTax']['CurrencyCode'] = (string)$x->ShippingTax->CurrencyCode; + $temp['MarketplaceName'] = (string)$x->MarketplaceName; + $this->list['Retrocharge'][] = $temp; + } + } + if (isset($xml->RentalTransactionEventList)) { + foreach($xml->RentalTransactionEventList->children() as $x) { + $temp = array(); + $temp['AmazonOrderId'] = (string)$x->AmazonOrderId; + $temp['RentalEventType'] = (string)$x->RentalEventType; + $temp['ExtensionLength'] = (string)$x->ExtensionLength; + $temp['PostedDate'] = (string)$x->PostedDate; + if (isset($x->RentalChargeList)) { + foreach($x->RentalChargeList->children() as $z) { + $temp['RentalChargeList'][] = $this->parseCharge($z); + } + } + if (isset($x->RentalFeeList)) { + foreach($x->RentalFeeList->children() as $z) { + $temp['RentalFeeList'][] = $this->parseFee($z); + } + } + $temp['MarketplaceName'] = (string)$x->MarketplaceName; + if (isset($x->RentalInitialValue)) { + $temp['RentalInitialValue']['Amount'] = (string)$x->RentalInitialValue->CurrencyAmount; + $temp['RentalInitialValue']['CurrencyCode'] = (string)$x->RentalInitialValue->CurrencyCode; + } + if (isset($x->RentalReimbursement)) { + $temp['RentalReimbursement']['Amount'] = (string)$x->RentalReimbursement->CurrencyAmount; + $temp['RentalReimbursement']['CurrencyCode'] = (string)$x->RentalReimbursement->CurrencyCode; + } + $this->list['RentalTransaction'][] = $temp; + } + } + if (isset($xml->PerformanceBondRefundEventList)) { + foreach($xml->PerformanceBondRefundEventList->children() as $x) { + $temp = array(); + $temp['MarketplaceCountryCode'] = (string)$x->MarketplaceCountryCode; + $temp['Amount'] = (string)$x->Amount->CurrencyAmount; + $temp['CurrencyCode'] = (string)$x->Amount->CurrencyCode; + if (isset($x->ProductGroupList)) { + foreach($x->ProductGroupList->children() as $z) { + $temp['ProductGroupList'][] = (string)$z; + } + } + $this->list['PerformanceBondRefund'][] = $temp; + } + } + if (isset($xml->ServiceFeeEventList)) { + foreach($xml->ServiceFeeEventList->children() as $x) { + $temp = array(); + $temp['AmazonOrderId'] = (string)$x->AmazonOrderId; + $temp['FeeReason'] = (string)$x->FeeReason; + if (isset($x->FeeList)) { + foreach($x->FeeList->children() as $z) { + $temp['FeeList'][] = $this->parseFee($z); + } + } + $temp['SellerSKU'] = (string)$x->SellerSKU; + $temp['FnSKU'] = (string)$x->FnSKU; + $temp['FeeDescription'] = (string)$x->FeeDescription; + $temp['ASIN'] = (string)$x->ASIN; + $this->list['ServiceFee'][] = $temp; + } + } + if (isset($xml->DebtRecoveryEventList)) { + foreach($xml->DebtRecoveryEventList->children() as $x) { + $temp = array(); + $temp['DebtRecoveryType'] = (string)$x->DebtRecoveryType; + $temp['RecoveryAmount']['Amount'] = (string)$x->RecoveryAmount->CurrencyAmount; + $temp['RecoveryAmount']['CurrencyCode'] = (string)$x->RecoveryAmount->CurrencyCode; + $temp['OverPaymentCredit']['Amount'] = (string)$x->OverPaymentCredit->CurrencyAmount; + $temp['OverPaymentCredit']['CurrencyCode'] = (string)$x->OverPaymentCredit->CurrencyCode; + if (isset($x->DebtRecoveryItemList)) { + foreach($x->DebtRecoveryItemList->children() as $z) { + $ztemp = array(); + $ztemp['RecoveryAmount']['Amount'] = (string)$z->RecoveryAmount->CurrencyAmount; + $ztemp['RecoveryAmount']['CurrencyCode'] = (string)$z->RecoveryAmount->CurrencyCode; + $ztemp['OriginalAmount']['Amount'] = (string)$z->OriginalAmount->CurrencyAmount; + $ztemp['OriginalAmount']['CurrencyCode'] = (string)$z->OriginalAmount->CurrencyCode; + $ztemp['GroupBeginDate'] = (string)$z->GroupBeginDate; + $ztemp['GroupEndDate'] = (string)$z->GroupEndDate; + $temp['DebtRecoveryItemList'][] = $ztemp; + } + } + if (isset($x->ChargeInstrumentList)) { + foreach($x->ChargeInstrumentList->children() as $z) { + $ztemp = array(); + $ztemp['Description'] = (string)$z->Description; + $ztemp['Tail'] = (string)$z->Tail; + $ztemp['Amount'] = (string)$z->Amount->CurrencyAmount; + $ztemp['CurrencyCode'] = (string)$z->Amount->CurrencyCode; + $temp['ChargeInstrumentList'][] = $ztemp; + } + } + $this->list['DebtRecovery'][] = $temp; + } + } + if (isset($xml->LoanServicingEventList)) { + foreach($xml->LoanServicingEventList->children() as $x) { + $temp = array(); + $temp['Amount'] = (string)$x->LoanAmount->CurrencyAmount; + $temp['CurrencyCode'] = (string)$x->LoanAmount->CurrencyCode; + $temp['SourceBusinessEventType'] = (string)$x->SourceBusinessEventType; + $this->list['LoanServicing'][] = $temp; + } + } + if (isset($xml->AdjustmentEventList)) { + foreach($xml->AdjustmentEventList->children() as $x) { + $temp = array(); + $temp['AdjustmentType'] = (string)$x->AdjustmentType; + $temp['Amount'] = (string)$x->AdjustmentAmount->CurrencyAmount; + $temp['CurrencyCode'] = (string)$x->AdjustmentAmount->CurrencyCode; + if (isset($x->AdjustmentItemList)) { + foreach($x->AdjustmentItemList->children() as $z) { + $ztemp = array(); + $ztemp['Quantity'] = (string)$z->Quantity; + $ztemp['PerUnitAmount']['Amount'] = (string)$z->PerUnitAmount->CurrencyAmount; + $ztemp['PerUnitAmount']['CurrencyCode'] = (string)$z->PerUnitAmount->CurrencyCode; + $ztemp['TotalAmount']['Amount'] = (string)$z->TotalAmount->CurrencyAmount; + $ztemp['TotalAmount']['CurrencyCode'] = (string)$z->TotalAmount->CurrencyCode; + $ztemp['SellerSKU'] = (string)$z->SellerSKU; + $ztemp['FnSKU'] = (string)$z->FnSKU; + $ztemp['ProductDescription'] = (string)$z->ProductDescription; + $ztemp['ASIN'] = (string)$z->ASIN; + $temp['AdjustmentItemList'][] = $ztemp; + } + } + $this->list['Adjustment'][] = $temp; + } + } + } + + /** + * Parses XML for a single shipment event into an array. + * @param SimpleXMLElement $xml

    The XML response from Amazon.

    + * @return array parsed structure from XML + */ + protected function parseShipmentEvent($xml) { + $r = array(); + $r['AmazonOrderId'] = (string)$xml->AmazonOrderId; + $r['SellerOrderId'] = (string)$xml->SellerOrderId; + $r['MarketplaceName'] = (string)$xml->MarketplaceName; + $chargeLists = array( + 'OrderChargeList', + 'OrderChargeAdjustmentList', + ); + foreach ($chargeLists as $key) { + if (isset($xml->$key)) { + foreach($xml->$key->children() as $x) { + $r[$key][] = $this->parseCharge($x); + } + } + } + $feelists = array( + 'ShipmentFeeList', + 'ShipmentFeeAdjustmentList', + 'OrderFeeList', + 'OrderFeeAdjustmentList', + ); + foreach ($feelists as $key) { + if (isset($xml->$key)) { + foreach($xml->$key->children() as $x) { + $r[$key][] = $this->parseFee($x); + } + } + } + if (isset($xml->DirectPaymentList)) { + foreach($xml->DirectPaymentList->children() as $x){ + $temp = array(); + $temp['DirectPaymentType'] = (string)$x->DirectPaymentType; + $temp['Amount'] = (string)$x->DirectPaymentAmount->CurrencyAmount; + $temp['CurrencyCode'] = (string)$x->DirectPaymentAmount->CurrencyCode; + $r['DirectPaymentList'][] = $temp; + } + } + $r['PostedDate'] = (string)$xml->PostedDate; + $itemLists = array( + 'ShipmentItemList', + 'ShipmentItemAdjustmentList', + ); + $itemChargeLists = array( + 'ItemChargeList', + 'ItemChargeAdjustmentList', + ); + $itemFeeLists = array( + 'ItemFeeList', + 'ItemFeeAdjustmentList', + ); + $itemPromoLists = array( + 'PromotionList', + 'PromotionAdjustmentList', + ); + foreach ($itemLists as $key) { + if (isset($xml->$key)) { + foreach($xml->$key->children() as $x) { + $temp = array(); + $temp['SellerSKU'] = (string)$x->SellerSKU; + $temp['OrderItemId'] = (string)$x->OrderItemId; + if (isset($x->OrderAdjustmentItemId)) { + $temp['OrderAdjustmentItemId'] = (string)$x->OrderAdjustmentItemId; + } + $temp['QuantityShipped'] = (string)$x->QuantityShipped; + foreach ($itemChargeLists as $zkey) { + if (isset($x->$zkey)) { + foreach($x->$zkey->children() as $z) { + $temp[$zkey][] = $this->parseCharge($z); + } + } + } + foreach ($itemFeeLists as $zkey) { + if (isset($x->$zkey)) { + foreach($x->$zkey->children() as $z) { + $temp[$zkey][] = $this->parseFee($z); + } + } + } + foreach ($itemPromoLists as $zkey) { + if (isset($x->$zkey)) { + foreach($x->$zkey->children() as $z) { + $ztemp = array(); + $ztemp['PromotionType'] = (string)$z->PromotionType; + $ztemp['PromotionId'] = (string)$z->PromotionId; + $ztemp['Amount'] = (string)$z->PromotionAmount->CurrencyAmount; + $ztemp['CurrencyCode'] = (string)$z->PromotionAmount->CurrencyCode; + $temp[$zkey][] = $ztemp; + } + } + } + if (isset($x->CostOfPointsGranted)) { + $temp['CostOfPointsGranted']['Amount'] = (string)$x->CostOfPointsGranted->CurrencyAmount; + $temp['CostOfPointsGranted']['CurrencyCode'] = (string)$x->CostOfPointsGranted->CurrencyCode; + } + if (isset($x->CostOfPointsReturned)) { + $temp['CostOfPointsReturned']['Amount'] = (string)$x->CostOfPointsReturned->CurrencyAmount; + $temp['CostOfPointsReturned']['CurrencyCode'] = (string)$x->CostOfPointsReturned->CurrencyCode; + } + $r[$key][] = $temp; + } + } + } + return $r; + } + + /** + * Parses XML for a single charge into an array. + * This structure is used many times throughout shipment events. + * @param SimpleXMLElement $xml

    The XML response from Amazon.

    + * @return array parsed structure from XML + */ + protected function parseCharge($xml) { + $r = array(); + $r['ChargeType'] = (string)$xml->ChargeType; + $r['Amount'] = (string)$xml->ChargeAmount->CurrencyAmount; + $r['CurrencyCode'] = (string)$xml->ChargeAmount->CurrencyCode; + return $r; + } + + /** + * Parses XML for a single charge into an array. + * This structure is used many times throughout shipment events. + * @param SimpleXMLElement $xml

    The XML response from Amazon.

    + * @return array parsed structure from XML + */ + protected function parseFee($xml) { + $r = array(); + $r['FeeType'] = (string)$xml->FeeType; + $r['Amount'] = (string)$xml->FeeAmount->CurrencyAmount; + $r['CurrencyCode'] = (string)$xml->FeeAmount->CurrencyCode; + return $r; + } + + /** + * Returns all financial events. + * + * The array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + * @see getShipmentEvents + * @see getRefundEvents + * @see getGuaranteeClaimEvents + * @see getChargebackEvents + * @see getPayWithAmazonEvents + * @see getServiceProviderCreditEvents + * @see getRetrochargeEvents + * @see getRentalTransactionEvents + * @see getPerformanceBondRefundEvents + * @see getServiceFeeEvents + * @see getDebtRecoveryEvents + * @see getLoanServicingEvents + * @see getAdjustmentEvents + */ + public function getEvents(){ + if (isset($this->list)){ + return $this->list; + } else { + return false; + } + } + + /** + * Returns all shipment events. + * + * Each event array will have the following keys: + * + * + * Each "charge" array has the following keys: + * + * Each "fee" array has the following keys: + * + * Each "item" array has the following keys: + * + * Each "promotion" array has the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getShipmentEvents(){ + if (isset($this->list['Shipment'])){ + return $this->list['Shipment']; + } else { + return false; + } + } + + /** + * Returns all refund events. + * + * The structure for each event array is the same as in getShipmentEvents, + * but with the following additional keys in each "item" array: + * + * Each "item" array will have the following additional keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + * @see getShipmentEvents + */ + public function getRefundEvents(){ + if (isset($this->list['Refund'])){ + return $this->list['Refund']; + } else { + return false; + } + } + + /** + * Returns all guarantee claim events. + * + * The structure for each event array is the same as in getRefundEvents. + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + * @see getRefundEvents + */ + public function getGuaranteeClaimEvents(){ + if (isset($this->list['GuaranteeClaim'])){ + return $this->list['GuaranteeClaim']; + } else { + return false; + } + } + + /** + * Returns all chargeback events. + * + * The structure for each event array is the same as in getRefundEvents. + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + * @see getRefundEvents + */ + public function getChargebackEvents(){ + if (isset($this->list['Chargeback'])){ + return $this->list['Chargeback']; + } else { + return false; + } + } + + /** + * Returns all pay with Amazon events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getPayWithAmazonEvents(){ + if (isset($this->list['PayWithAmazon'])){ + return $this->list['PayWithAmazon']; + } else { + return false; + } + } + + /** + * Returns all service provider credit events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getServiceProviderCreditEvents(){ + if (isset($this->list['ServiceProviderCredit'])){ + return $this->list['ServiceProviderCredit']; + } else { + return false; + } + } + + /** + * Returns all retrocharge events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getRetrochargeEvents(){ + if (isset($this->list['Retrocharge'])){ + return $this->list['Retrocharge']; + } else { + return false; + } + } + + /** + * Returns all rental transaction events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getRentalTransactionEvents(){ + if (isset($this->list['RentalTransaction'])){ + return $this->list['RentalTransaction']; + } else { + return false; + } + } + + /** + * Returns all performance bond refund events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getPerformanceBondRefundEvents(){ + if (isset($this->list['PerformanceBondRefund'])){ + return $this->list['PerformanceBondRefund']; + } else { + return false; + } + } + + /** + * Returns all service fee events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getServiceFeeEvents(){ + if (isset($this->list['ServiceFee'])){ + return $this->list['ServiceFee']; + } else { + return false; + } + } + + /** + * Returns all debt recovery events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getDebtRecoveryEvents(){ + if (isset($this->list['DebtRecovery'])){ + return $this->list['DebtRecovery']; + } else { + return false; + } + } + + /** + * Returns all loan servicing events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getLoanServicingEvents(){ + if (isset($this->list['LoanServicing'])){ + return $this->list['LoanServicing']; + } else { + return false; + } + } + + /** + * Returns all adjustment events. + * + * Each event array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getAdjustmentEvents(){ + if (isset($this->list['Adjustment'])){ + return $this->list['Adjustment']; + } else { + return false; + } + } + +} diff --git a/src/AmazonFinancialGroupList.php b/src/AmazonFinancialGroupList.php new file mode 100644 index 00000000..9bd70ddd --- /dev/null +++ b/src/AmazonFinancialGroupList.php @@ -0,0 +1,467 @@ +tokenFlag; + } + + /** + * Sets whether or not the object should automatically use tokens if it receives one. + * + * If this option is set to TRUE, the object will automatically perform + * the necessary operations to retrieve the rest of the list using tokens. If + * this option is off, the object will only ever retrieve the first section of + * the list. + * @param boolean $b [optional]

    Defaults to TRUE

    + * @return boolean FALSE if improper input + */ + public function setUseToken($b = true) { + if (is_bool($b)) { + $this->tokenUseFlag = $b; + } else { + return false; + } + } + + /** + * Sets the maximum number of responses per page. (Optional) + * + * This method sets the maximum number of Financial Event Groups for Amazon to return per page. + * If this parameter is not set, Amazon will send 100 at a time. + * @param int $num

    Positive integer from 1 to 100.

    + * @return boolean FALSE if improper input + */ + public function setMaxResultsPerPage($num){ + if (is_numeric($num) && $num <= 100 && $num >= 1){ + $this->options['MaxResultsPerPage'] = $num; + } else { + return false; + } + } + + /** + * Sets the time frame options. (Required*) + * + * This method sets the start and end times for the next request. If this + * parameter is set, Amazon will only return Financial Event Groups that occurred + * between the two times given. Only the starting time is required to fetch financial event groups. + * The parameters are passed through strtotime, so values such as "-1 hour" are fine. + * @param string $s

    A time string for the earliest time.

    + * @param string $e [optional]

    A time string for the latest time.

    + * @return boolean FALSE if improper input + */ + public function setTimeLimits($s, $e = null) { + if (empty($s)) { + return FALSE; + } + $times = $this->genTime($s); + $this->options['FinancialEventGroupStartedAfter'] = $times; + if (!empty($e)) { + $timee = $this->genTime($e); + $this->options['FinancialEventGroupStartedBefore'] = $timee; + } else { + unset($this->options['FinancialEventGroupStartedBefore']); + } + } + + /** + * Fetches a list of financial event groups from Amazon. + * + * Submits a ListFinancialEventGroups request to Amazon. In order to do this, + * a start date must be set. Amazon will send the list back as a response, + * which can be retrieved using getGroups. + * Other methods are available for fetching specific values from the list. + * This operation can potentially involve tokens. + * @param boolean $r [optional]

    When set to FALSE, the function will not recurse, defaults to TRUE

    + * @return boolean FALSE if something goes wrong + */ + public function fetchGroupList($r = true) { + if (!array_key_exists('FinancialEventGroupStartedAfter', $this->options)) { + $this->log("Start date must be set in order to fetch financial event groups", 'Warning'); + return false; + } + + $this->prepareToken(); + + $url = $this->urlbase.$this->urlbranch; + + $path = $this->options['Action'].'Result'; + + if ($this->mockMode) { + $xml = $this->fetchMockFile()->$path; + } else { + $response = $this->sendRequest($url); + + if (!$this->checkResponse($response)) { + return false; + } + + $xml = simplexml_load_string($response['body'])->$path; + } + + $this->parseXml($xml); + + $this->checkToken($xml); + + if ($this->tokenFlag && $this->tokenUseFlag && $r === true) { + while ($this->tokenFlag) { + $this->log("Recursively fetching more Financial Event Groups"); + $this->fetchGroupList(false); + } + } + } + + /** + * Sets up options for using tokens. + * + * This changes key options for switching between simply fetching a list and + * fetching the rest of a list using a token. Please note: because the + * operation for using tokens does not use any other parameters, all other + * parameters will be removed. + */ + protected function prepareToken() { + if ($this->tokenFlag && $this->tokenUseFlag) { + $this->options['Action'] = 'ListFinancialEventGroupsByNextToken'; + unset($this->options['MaxResultsPerPage']); + unset($this->options['FinancialEventGroupStartedAfter']); + unset($this->options['FinancialEventGroupStartedBefore']); + } else { + $this->options['Action'] = 'ListFinancialEventGroups'; + unset($this->options['NextToken']); + $this->index = 0; + $this->list = array(); + } + } + + /** + * Parses XML response into array. + * + * This is what reads the response XML and converts it into an array. + * @param SimpleXMLElement $xml

    The XML response from Amazon.

    + * @return boolean FALSE if no XML data is found + */ + protected function parseXml($xml) { + if (!$xml || !$xml->FinancialEventGroupList) { + return false; + } + foreach($xml->FinancialEventGroupList->children() as $x) { + $temp = array(); + $temp['FinancialEventGroupId'] = (string)$x->FinancialEventGroupId; + $temp['ProcessingStatus'] = (string)$x->ProcessingStatus; + if (isset($x->FundTransferStatus)) { + $temp['FundTransferStatus'] = (string)$x->FundTransferStatus; + } + $temp['OriginalTotal']['Amount'] = (string)$x->OriginalTotal->CurrencyAmount; + $temp['OriginalTotal']['CurrencyCode'] = (string)$x->OriginalTotal->CurrencyCode; + if (isset($x->ConvertedTotal)) { + $temp['ConvertedTotal']['Amount'] = (string)$x->ConvertedTotal->CurrencyAmount; + $temp['ConvertedTotal']['CurrencyCode'] = (string)$x->ConvertedTotal->CurrencyCode; + } + if (isset($x->FundTransferDate)) { + $temp['FundTransferDate'] = (string)$x->FundTransferDate; + } + if (isset($x->TraceId)) { + $temp['TraceId'] = (string)$x->TraceId; + } + if (isset($x->AccountTail)) { + $temp['AccountTail'] = (string)$x->AccountTail; + } + $temp['BeginningBalance']['Amount'] = (string)$x->BeginningBalance->CurrencyAmount; + $temp['BeginningBalance']['CurrencyCode'] = (string)$x->BeginningBalance->CurrencyCode; + $temp['FinancialEventGroupStart'] = (string)$x->FinancialEventGroupStart; + if (isset($x->FinancialEventGroupEnd)) { + $temp['FinancialEventGroupEnd'] = (string)$x->FinancialEventGroupEnd; + } + $this->list[$this->index] = $temp; + $this->index++; + } + } + + /** + * Returns all financial event groups. + * + * Each financial event group array will have the following keys: + * + * @return array|boolean multi-dimensional array, or FALSE if list not filled yet + */ + public function getGroups(){ + if (isset($this->list)){ + return $this->list; + } else { + return false; + } + } + + /** + * Returns the ID for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @return string|boolean single value, or FALSE if Non-numeric index + */ + public function getGroupId($i = 0) { + if (isset($this->list[$i]['FinancialEventGroupId'])) { + return $this->list[$i]['FinancialEventGroupId']; + } else { + return false; + } + } + + /** + * Returns the processing status for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @return string|boolean "Open" or "Closed", or FALSE if Non-numeric index + */ + public function getProcessingStatus($i = 0) { + if (isset($this->list[$i]['ProcessingStatus'])) { + return $this->list[$i]['ProcessingStatus']; + } else { + return false; + } + } + + /** + * Returns the transfer status for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @return string|boolean single value, or FALSE if Non-numeric index + */ + public function getTransferStatus($i = 0) { + if (isset($this->list[$i]['FundTransferStatus'])) { + return $this->list[$i]['FundTransferStatus']; + } else { + return false; + } + } + + /** + * Returns the original total for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * If an array is returned, it will have the fields Amount and CurrencyCode. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @param boolean $only [optional]

    set to TRUE to get only the amount

    + * @return array|string|boolean array, single value, or FALSE if Non-numeric index + */ + public function getOriginalTotal($i = 0, $only = false) { + if (isset($this->list[$i]['OriginalTotal'])) { + if ($only) { + return $this->list[$i]['OriginalTotal']['Amount']; + } else { + return $this->list[$i]['OriginalTotal']; + } + } else { + return false; + } + } + + /** + * Returns the converted total for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * If an array is returned, it will have the fields Amount and CurrencyCode. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @param boolean $only [optional]

    set to TRUE to get only the amount

    + * @return array|string|boolean array, single value, or FALSE if Non-numeric index + */ + public function getConvertedTotal($i = 0, $only = false) { + if (isset($this->list[$i]['ConvertedTotal'])) { + if ($only) { + return $this->list[$i]['ConvertedTotal']['Amount']; + } else { + return $this->list[$i]['ConvertedTotal']; + } + } else { + return false; + } + } + + /** + * Returns the transfer date for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @return string|boolean date in ISO 8601 format, or FALSE if Non-numeric index + */ + public function getTransferDate($i = 0) { + if (isset($this->list[$i]['FundTransferDate'])) { + return $this->list[$i]['FundTransferDate']; + } else { + return false; + } + } + + /** + * Returns the trace ID for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @return string|boolean single value, or FALSE if Non-numeric index + */ + public function getTraceId($i = 0) { + if (isset($this->list[$i]['TraceId'])) { + return $this->list[$i]['TraceId']; + } else { + return false; + } + } + + /** + * Returns the account tail for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @return string|boolean single value, or FALSE if Non-numeric index + */ + public function getAccountTail($i = 0) { + if (isset($this->list[$i]['AccountTail'])) { + return $this->list[$i]['AccountTail']; + } else { + return false; + } + } + + /** + * Returns the balance at the beginning of the settlement period for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * If an array is returned, it will have the fields Amount and CurrencyCode. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @param boolean $only [optional]

    set to TRUE to get only the amount

    + * @return array|string|boolean array, single value, or FALSE if Non-numeric index + */ + public function getBeginningBalance($i = 0, $only = false) { + if (isset($this->list[$i]['BeginningBalance'])) { + if ($only) { + return $this->list[$i]['BeginningBalance']['Amount']; + } else { + return $this->list[$i]['BeginningBalance']; + } + } else { + return false; + } + } + + /** + * Returns the start date for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @return string|boolean date in ISO 8601 format, or FALSE if Non-numeric index + */ + public function getStartDate($i = 0) { + if (isset($this->list[$i]['FinancialEventGroupStart'])) { + return $this->list[$i]['FinancialEventGroupStart']; + } else { + return false; + } + } + + /** + * Returns the end date for the specified entry. + * + * This method will return FALSE if the list has not yet been filled. + * @param int $i [optional]

    List index to retrieve the value from. Defaults to 0.

    + * @return string|boolean date in ISO 8601 format, or FALSE if Non-numeric index + */ + public function getEndDate($i = 0) { + if (isset($this->list[$i]['FinancialEventGroupEnd'])) { + return $this->list[$i]['FinancialEventGroupEnd']; + } else { + return false; + } + } + + /** + * Iterator function + * @return type + */ + public function current() { + return $this->list[$this->i]; + } + + /** + * Iterator function + */ + public function rewind() { + $this->i = 0; + } + + /** + * Iterator function + * @return type + */ + public function key() { + return $this->i; + } + + /** + * Iterator function + */ + public function next() { + $this->i++; + } + + /** + * Iterator function + * @return type + */ + public function valid() { + return isset($this->list[$this->i]); + } + +} diff --git a/src/Creacoon/AmazonMws/AmazonFulfillmentOrder.php b/src/AmazonFulfillmentOrder.php similarity index 69% rename from src/Creacoon/AmazonMws/AmazonFulfillmentOrder.php rename to src/AmazonFulfillmentOrder.php index d0b099eb..bf96cb54 100755 --- a/src/Creacoon/AmazonMws/AmazonFulfillmentOrder.php +++ b/src/AmazonFulfillmentOrder.php @@ -1,4 +1,7 @@ -AmazonFulfillmentPreview object. */ -class AmazonFulfillmentOrder extends AmazonOutboundCore{ +class AmazonFulfillmentOrder extends AmazonOutboundCore +{ private $order; - + /** * AmazonFulfillmentOrder fetches a fulfillment order from Amazon. You need a Fulfillment Order ID. - * + * * The parameters are passed to the parent constructor, which are * in turn passed to the AmazonCore constructor. See it for more information * on these parameters and common methods. @@ -42,84 +46,86 @@ class AmazonFulfillmentOrder extends AmazonOutboundCore{ * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - public function __construct($s, $id = null, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - - if($id){ + public function __construct($s, $id = null, $mock = false, $m = null) + { + parent::__construct($s, $mock, $m); + + if ($id) { $this->setOrderId($id); } } - + /** * Sets the fulfillment order ID. (Required) - * + * * This method sets the Fulfillment Order ID to be sent in the next request. * This parameter is required for fetching the fulfillment order from Amazon. * @param string $s

    Maximum 40 characters.

    * @return boolean FALSE if improper input */ - public function setOrderId($s){ - if (is_string($s)){ + public function setOrderId($s) + { + if ($s !== null) { $this->options['SellerFulfillmentOrderId'] = $s; } else { return false; } } - + /** * Fetches data on a fulfillment order from Amazon. - * + * * Submits a GetFulfillmentOrder request to Amazon. In order to do this, * a fulfillment order ID is required. Amazon will send * the data back as a response, which can be retrieved using getOrder. * @return boolean FALSE if something goes wrong */ - public function fetchOrder(){ - if (!array_key_exists('SellerFulfillmentOrderId',$this->options)){ - $this->log("Fulfillment Order ID must be set in order to fetch it!",'Warning'); + public function fetchOrder() + { + if (!array_key_exists('SellerFulfillmentOrderId', $this->options)) { + $this->log("Fulfillment Order ID must be set in order to fetch it!", 'Warning'); return false; } - + $this->options['Action'] = 'GetFulfillmentOrder'; - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; + + $url = $this->urlbase . $this->urlbranch; + + $path = $this->options['Action'] . 'Result'; + if ($this->mockMode) { + $xml = $this->fetchMockFile()->$path; } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ + $response = $this->sendRequest($url); + + if (!$this->checkResponse($response)) { return false; } - + $xml = simplexml_load_string($response['body'])->$path; } - + $this->parseXML($xml); } - + /** * Parses XML response into array. - * + * * This is what reads the response XML and converts it into an array. * @param SimpleXMLObject $xml

    The XML response from Amazon.

    * @return boolean FALSE if no XML data is found */ - protected function parseXML($xml) { - if (!$xml){ + protected function parseXML($xml) + { + if (!$xml) { return false; } - if (!$xml->FulfillmentOrder){ + if (!$xml->FulfillmentOrder) { return false; } - if (!$xml->FulfillmentOrderItem){ + if (!$xml->FulfillmentOrderItem) { return false; } - if (!$xml->FulfillmentShipment){ + if (!$xml->FulfillmentShipment) { return false; } //Section 1: ShipmentOrder @@ -130,156 +136,155 @@ protected function parseXML($xml) { $this->order['Details']['DisplayableOrderComment'] = (string)$d->DisplayableOrderComment; $this->order['Details']['ShippingSpeedCategory'] = (string)$d->ShippingSpeedCategory; //Address - $this->order['Details']['DestinationAddress']['Name'] = (string)$d->DestinationAddress->Name; - $this->order['Details']['DestinationAddress']['Line1'] = (string)$d->DestinationAddress->Line1; - if (isset($d->DestinationAddress->Line2)){ - $this->order['Details']['DestinationAddress']['Line2'] = (string)$d->DestinationAddress->Line2; - } - if (isset($d->DestinationAddress->Line3)){ - $this->order['Details']['DestinationAddress']['Line3'] = (string)$d->DestinationAddress->Line3; - } - if (isset($d->DestinationAddress->DistrictOrCounty)){ - $this->order['Details']['DestinationAddress']['DistrictOrCounty'] = (string)$d->DestinationAddress->DistrictOrCounty; - } - $this->order['Details']['DestinationAddress']['City'] = (string)$d->DestinationAddress->City; - $this->order['Details']['DestinationAddress']['StateOrProvinceCode'] = (string)$d->DestinationAddress->StateOrProvinceCode; - $this->order['Details']['DestinationAddress']['CountryCode'] = (string)$d->DestinationAddress->CountryCode; - if (isset($d->DestinationAddress->PostalCode)){ - $this->order['Details']['DestinationAddress']['PostalCode'] = (string)$d->DestinationAddress->PostalCode; - } - if (isset($d->DestinationAddress->PhoneNumber)){ - $this->order['Details']['DestinationAddress']['PhoneNumber'] = (string)$d->DestinationAddress->PhoneNumber; - } + $this->order['Details']['DestinationAddress']['Name'] = (string)$d->DestinationAddress->Name; + $this->order['Details']['DestinationAddress']['Line1'] = (string)$d->DestinationAddress->Line1; + if (isset($d->DestinationAddress->Line2)) { + $this->order['Details']['DestinationAddress']['Line2'] = (string)$d->DestinationAddress->Line2; + } + if (isset($d->DestinationAddress->Line3)) { + $this->order['Details']['DestinationAddress']['Line3'] = (string)$d->DestinationAddress->Line3; + } + if (isset($d->DestinationAddress->DistrictOrCounty)) { + $this->order['Details']['DestinationAddress']['DistrictOrCounty'] = (string)$d->DestinationAddress->DistrictOrCounty; + } + $this->order['Details']['DestinationAddress']['City'] = (string)$d->DestinationAddress->City; + $this->order['Details']['DestinationAddress']['StateOrProvinceCode'] = (string)$d->DestinationAddress->StateOrProvinceCode; + $this->order['Details']['DestinationAddress']['CountryCode'] = (string)$d->DestinationAddress->CountryCode; + if (isset($d->DestinationAddress->PostalCode)) { + $this->order['Details']['DestinationAddress']['PostalCode'] = (string)$d->DestinationAddress->PostalCode; + } + if (isset($d->DestinationAddress->PhoneNumber)) { + $this->order['Details']['DestinationAddress']['PhoneNumber'] = (string)$d->DestinationAddress->PhoneNumber; + } //End of Address - if (isset($d->FulfillmentPolicy)){ + if (isset($d->FulfillmentPolicy)) { $this->order['Details']['FulfillmentPolicy'] = (string)$d->FulfillmentPolicy; } - if (isset($d->FulfillmentMethod)){ + if (isset($d->FulfillmentMethod)) { $this->order['Details']['FulfillmentMethod'] = (string)$d->FulfillmentMethod; } $this->order['Details']['ReceivedDateTime'] = (string)$d->ReceivedDateTime; $this->order['Details']['FulfillmentOrderStatus'] = (string)$d->FulfillmentOrderStatus; $this->order['Details']['StatusUpdatedDateTime'] = (string)$d->StatusUpdatedDateTime; - if (isset($d->NotificationEmailList)){ + if (isset($d->NotificationEmailList)) { $i = 0; - foreach($d->NotificationEmailList->children() as $x){ + foreach ($d->NotificationEmailList->children() as $x) { $this->order['Details']['NotificationEmailList'][$i++] = (string)$x; } } - + //Section 2: Order Items $i = 0; - foreach($xml->FulfillmentOrderItem->children() as $x){ + foreach ($xml->FulfillmentOrderItem->children() as $x) { $this->order['Items'][$i]['SellerSKU'] = (string)$x->SellerSKU; $this->order['Items'][$i]['SellerFulfillmentOrderItemId'] = (string)$x->SellerFulfillmentOrderItemId; $this->order['Items'][$i]['Quantity'] = (string)$x->Quantity; - if (isset($x->GiftMessage)){ + if (isset($x->GiftMessage)) { $this->order['Items'][$i]['GiftMessage'] = (string)$x->GiftMessage; } - if (isset($x->DisplayableComment)){ + if (isset($x->DisplayableComment)) { $this->order['Items'][$i]['DisplayableComment'] = (string)$x->DisplayableComment; } - if (isset($x->FulfillmentNetworkSKU)){ + if (isset($x->FulfillmentNetworkSKU)) { $this->order['Items'][$i]['FulfillmentNetworkSKU'] = (string)$x->FulfillmentNetworkSKU; } - if (isset($x->OrderItemDisposition)){ + if (isset($x->OrderItemDisposition)) { $this->order['Items'][$i]['OrderItemDisposition'] = (string)$x->OrderItemDisposition; } $this->order['Items'][$i]['CancelledQuantity'] = (string)$x->CancelledQuantity; $this->order['Items'][$i]['UnfulfillableQuantity'] = (string)$x->UnfulfillableQuantity; - if (isset($x->EstimatedShipDateTime)){ + if (isset($x->EstimatedShipDateTime)) { $this->order['Items'][$i]['EstimatedShipDateTime'] = (string)$x->EstimatedShipDateTime; } - if (isset($x->EstimatedArrivalDateTime)){ + if (isset($x->EstimatedArrivalDateTime)) { $this->order['Items'][$i]['EstimatedArrivalDateTime'] = (string)$x->EstimatedArrivalDateTime; } - if (isset($x->PerUnitDeclaredValue)){ + if (isset($x->PerUnitDeclaredValue)) { $this->order['Items'][$i]['PerUnitDeclaredValue']['CurrencyCode'] = (string)$x->PerUnitDeclaredValue->CurrencyCode; $this->order['Items'][$i]['PerUnitDeclaredValue']['Value'] = (string)$x->PerUnitDeclaredValue->Value; } $i++; } - + //Section 3: Order Shipments $i = 0; - foreach($xml->FulfillmentShipment->children() as $x){ + foreach ($xml->FulfillmentShipment->children() as $x) { $this->order['Shipments'][$i]['AmazonShipmentId'] = (string)$x->AmazonShipmentId; $this->order['Shipments'][$i]['FulfillmentCenterId'] = (string)$x->FulfillmentCenterId; $this->order['Shipments'][$i]['FulfillmentShipmentStatus'] = (string)$x->FulfillmentShipmentStatus; - if (isset($x->ShippingDateTime)){ + if (isset($x->ShippingDateTime)) { $this->order['Shipments'][$i]['ShippingDateTime'] = (string)$x->ShippingDateTime; } - if (isset($x->EstimatedArrivalDateTime)){ + if (isset($x->EstimatedArrivalDateTime)) { $this->order['Shipments'][$i]['EstimatedArrivalDateTime'] = (string)$x->EstimatedArrivalDateTime; } //FulfillmentShipmentItem $j = 0; - foreach ($x->FulfillmentShipmentItem->children() as $y){ - if (isset($y->SellerSKU)){ + foreach ($x->FulfillmentShipmentItem->children() as $y) { + if (isset($y->SellerSKU)) { $this->order['Shipments'][$i]['FulfillmentShipmentItem'][$j]['SellerSKU'] = (string)$y->SellerSKU; } $this->order['Shipments'][$i]['FulfillmentShipmentItem'][$j]['SellerFulfillmentOrderItemId'] = (string)$y->SellerFulfillmentOrderItemId; $this->order['Shipments'][$i]['FulfillmentShipmentItem'][$j]['Quantity'] = (string)$y->Quantity; - if (isset($y->PackageNumber)){ + if (isset($y->PackageNumber)) { $this->order['Shipments'][$i]['FulfillmentShipmentItem'][$j]['PackageNumber'] = (string)$y->PackageNumber; } $j++; } - if (isset($x->FulfillmentShipmentPackage)){ + if (isset($x->FulfillmentShipmentPackage)) { $j = 0; - foreach ($x->FulfillmentShipmentPackage->children() as $y){ + foreach ($x->FulfillmentShipmentPackage->children() as $y) { $this->order['Shipments'][$i]['FulfillmentShipmentPackage'][$j]['PackageNumber'] = (string)$y->PackageNumber; $this->order['Shipments'][$i]['FulfillmentShipmentPackage'][$j]['CarrierCode'] = (string)$y->CarrierCode; - if (isset($y->TrackingNumber)){ + if (isset($y->TrackingNumber)) { $this->order['Shipments'][$i]['FulfillmentShipmentPackage'][$j]['TrackingNumber'] = (string)$y->TrackingNumber; } - if (isset($y->EstimatedArrivalDateTime)){ + if (isset($y->EstimatedArrivalDateTime)) { $this->order['Shipments'][$i]['FulfillmentShipmentPackage'][$j]['EstimatedArrivalDateTime'] = (string)$y->EstimatedArrivalDateTime; } $j++; } } - + $i++; } } - + /** * Cancels a fulfillment order on Amazon. - * + * * Submits a CancelFulfillmentOrder request to Amazon. In order to do this, * a fulfillment order ID is required. Amazon will send back an HTTP response, * so there is no data to retrieve afterwards. * @return boolean TRUE if the cancellation was successful, FALSE if something goes wrong */ - public function cancelOrder(){ - if (!array_key_exists('SellerFulfillmentOrderId',$this->options)){ - $this->log("Fulfillment Order ID must be set in order to cancel it!",'Warning'); + public function cancelOrder() + { + if (!array_key_exists('SellerFulfillmentOrderId', $this->options)) { + $this->log("Fulfillment Order ID must be set in order to cancel it!", 'Warning'); return false; } - + $this->options['Action'] = 'CancelFulfillmentOrder'; - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ + + $url = $this->urlbase . $this->urlbranch; + + if ($this->mockMode) { $response = $this->fetchMockResponse(); } else { - $response = $this->sendRequest($url, array('Post'=>$query)); + $response = $this->sendRequest($url); } - if (!$this->checkResponse($response)){ + if (!$this->checkResponse($response)) { return false; } else { - $this->log("Successfully deleted Fulfillment Order ".$this->options['SellerFulfillmentOrderId']); + $this->log("Successfully deleted Fulfillment Order " . $this->options['SellerFulfillmentOrderId']); return true; } } - + /** * Returns the full order information. - * + * * This method will return FALSE if the data has not yet been filled. * The array returned will have the following fields: * * @return array|boolean data array, or FALSE if data not filled yet */ - public function getOrder(){ - if (isset($this->order)){ + public function getOrder() + { + if (isset($this->order)) { return $this->order; } else { return false; } } } + ?> diff --git a/src/Creacoon/AmazonMws/AmazonFulfillmentOrderCreator.php b/src/AmazonFulfillmentOrderCreator.php similarity index 69% rename from src/Creacoon/AmazonMws/AmazonFulfillmentOrderCreator.php rename to src/AmazonFulfillmentOrderCreator.php index f1993d14..0eebf50a 100755 --- a/src/Creacoon/AmazonMws/AmazonFulfillmentOrderCreator.php +++ b/src/AmazonFulfillmentOrderCreator.php @@ -1,4 +1,7 @@ -AmazonFulfillmentPreview object. */ -class AmazonFulfillmentOrderCreator extends AmazonOutboundCore{ - +class AmazonFulfillmentOrderCreator extends AmazonOutboundCore +{ + /** * AmazonFulfillmentOrderCreator creates a fulfillment order. You need a fulfillment order ID. - * + * * The parameters are passed to the parent constructor, which are * in turn passed to the AmazonCore constructor. See it for more information * on these parameters and common methods. @@ -38,104 +42,152 @@ class AmazonFulfillmentOrderCreator extends AmazonOutboundCore{ * @param array|string $m [optional]

    The files (or file) to use in Mock Mode.

    * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - public function __construct($s, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - + public function __construct($s, $mock = false, $m = null) + { + parent::__construct($s, $mock, $m); + $this->options['Action'] = 'CreateFulfillmentOrder'; } - + /** * Sets the fulfillment order ID. (Required) - * + * * This method sets the Fulfillment Order ID to be sent in the next request. * This parameter is required for creating a fulfillment order with Amazon. * A fulfillment order ID can be generated using the AmazonFulfillmentPreview object. * @param string $s

    Maximum 40 characters.

    * @return boolean FALSE if improper input */ - public function setFulfillmentOrderId($s){ - if (is_string($s)){ + public function setFulfillmentOrderId($s) + { + if (is_string($s)) { $this->options['SellerFulfillmentOrderId'] = $s; + return true; } else { return false; } } - + /** * Sets the displayed order ID. (Required) - * + * * This method sets the Displayable Order ID to be sent in the next request. * This parameter is required for creating a fulfillment order with Amazon. * This is your own order ID, and is the ID that is displayed on the packing slip. * @param string $s

    Must be alpha-numeric or ISO-8559-1 compliant. Maximum 40 characters.

    * @return boolean FALSE if improper input */ - public function setDisplayableOrderId($s){ - if (is_string($s)){ + public function setDisplayableOrderId($s) + { + if (is_string($s)) { $this->options['DisplayableOrderId'] = $s; + return true; + } else { + return false; + } + } + + /** + * Sets the marketplace Id + * + * @param null $id + * @return bool + */ + public function setMarketPlaceId($id = null) + { + if (!$id && $this->marketplaceId) { + $id = $this->marketplaceId; + } + if ($id) { + $this->options['MarketplaceId'] = $id; + return true; + } + return false; + } + + /** + * Sets the displayed order comment. (Optional) + * + * Order-specific text that appears in customer-facing materials such as the outbound shipment packing slip. + * Maximum: 1000 characters + * + * @param $s + * @return bool + */ + public function setDisplayableOrderComment($s) + { + if (is_string($s)) { + $this->options['DisplayableOrderComment'] = $s; + return true; } else { return false; } } - + /** * Sets the displayed timestamp. (Required) - * + * * This method sets the displayed timestamp to be sent in the next request. * This parameter is required for creating a fulfillment order with Amazon. * The parameter is passed through strtotime, so values such as "-1 hour" are fine. * @param string $s

    Time string.

    * @return boolean FALSE if improper input */ - public function setDate($s){ - if (is_string($s)){ + public function setDate($s) + { + if (is_string($s)) { $time = $this->genTime($s); $this->options['DisplayableOrderDateTime'] = $time; + return true; } else { return false; } } - + /** * Sets the displayed comment. (Required) - * + * * This method sets the displayed order comment to be sent in the next request. * This parameter is required for creating a fulfillment order with Amazon. * @param string $s

    Maximum 1000 characters.

    * @return boolean FALSE if improper input */ - public function setComment($s){ - if (is_string($s)){ + public function setComment($s) + { + if (is_string($s)) { $this->options['DisplayableOrderComment'] = $s; + return true; } else { return false; } } - + /** * Sets the shipping speed. (Required) - * + * * This method sets the shipping speed to be sent in the next request. * This parameter is required for creating a fulfillment order with Amazon. * @param string $s

    "Standard", "Expedited", or "Priority"

    * @return boolean FALSE if improper input */ - public function setShippingSpeed($s){ - if (is_string($s)){ - if ($s == 'Standard' || $s == 'Expedited' || $s == 'Priority'){ + public function setShippingSpeed($s) + { + if (is_string($s)) { + if ($s == 'Standard' || $s == 'Expedited' || $s == 'Priority') { $this->options['ShippingSpeedCategory'] = $s; + return true; } else { - $this->log("Tried to set shipping status to invalid value",'Warning'); + $this->log("Tried to set shipping status to invalid value", 'Warning'); return false; } } else { return false; } } - + /** * Sets the address. (Required) - * + * * This method sets the destination address to be sent in the next request. * This parameter is required for creating a fulfillment order with Amazon. * The array provided should have the following fields: @@ -154,62 +206,65 @@ public function setShippingSpeed($s){ * @param array $a

    See above.

    * @return boolean FALSE if improper input */ - public function setAddress($a){ - if (is_null($a) || is_string($a) || !$a){ - $this->log("Tried to set address to invalid values",'Warning'); + public function setAddress($a) + { + if (is_null($a) || is_string($a) || !$a) { + $this->log("Tried to set address to invalid values", 'Warning'); return false; } $this->resetAddress(); $this->options['DestinationAddress.Name'] = $a['Name']; $this->options['DestinationAddress.Line1'] = $a['Line1']; - if (array_key_exists('Line2', $a)){ + if (array_key_exists('Line2', $a)) { $this->options['DestinationAddress.Line2'] = $a['Line2']; } else { $this->options['DestinationAddress.Line2'] = null; } - if (array_key_exists('Line3', $a)){ + if (array_key_exists('Line3', $a)) { $this->options['DestinationAddress.Line3'] = $a['Line3']; } else { $this->options['DestinationAddress.Line3'] = null; } - if (array_key_exists('DistrictOrCounty', $a)){ + if (array_key_exists('DistrictOrCounty', $a)) { $this->options['DestinationAddress.DistrictOrCounty'] = $a['DistrictOrCounty']; } else { $this->options['DestinationAddress.DistrictOrCounty'] = null; } $this->options['DestinationAddress.City'] = $a['City']; - $this->options['DestinationAddress.StateOrProvidenceCode'] = $a['StateOrProvidenceCode']; + $this->options['DestinationAddress.StateOrProvinceCode'] = $a['StateOrProvinceCode']; $this->options['DestinationAddress.CountryCode'] = $a['CountryCode']; $this->options['DestinationAddress.PostalCode'] = $a['PostalCode']; - if (array_key_exists('PhoneNumber', $a)){ + if (array_key_exists('PhoneNumber', $a)) { $this->options['DestinationAddress.PhoneNumber'] = $a['PhoneNumber']; } else { $this->options['DestinationAddress.PhoneNumber'] = null; } + return true; } - + /** * Resets the address options. - * + * * Since address is a required parameter, these options should not be removed * without replacing them, so this method is not public. */ - protected function resetAddress(){ + protected function resetAddress() + { unset($this->options['DestinationAddress.Name']); unset($this->options['DestinationAddress.Line1']); unset($this->options['DestinationAddress.Line2']); unset($this->options['DestinationAddress.Line3']); unset($this->options['DestinationAddress.DistrictOrCounty']); unset($this->options['DestinationAddress.City']); - unset($this->options['DestinationAddress.StateOrProvidenceCode']); + unset($this->options['DestinationAddress.StateOrProvinceCode']); unset($this->options['DestinationAddress.CountryCode']); unset($this->options['DestinationAddress.PostalCode']); unset($this->options['DestinationAddress.PhoneNumber']); } - + /** * Sets the fulfillment policy. (Optional) - * + * * This method sets the Fulfillment Policy to be sent in the next request. * If this parameter is not set, Amazon will assume a FillOrKill policy. * Here is a quick description of the policies: @@ -221,22 +276,24 @@ protected function resetAddress(){ * @param string $s

    "FillOrKill", "FillAll", or "FillAllAvailable"

    * @return boolean FALSE if improper input */ - public function setFulfillmentPolicy($s){ - if (is_string($s)){ - if ($s == 'FillOrKill' || $s == 'FillAll' || $s == 'FillAllAvailable'){ + public function setFulfillmentPolicy($s) + { + if (is_string($s)) { + if ($s == 'FillOrKill' || $s == 'FillAll' || $s == 'FillAllAvailable') { $this->options['FulfillmentPolicy'] = $s; + return true; } else { - $this->log("Tried to set fulfillment policy to invalid value",'Warning'); + $this->log("Tried to set fulfillment policy to invalid value", 'Warning'); return false; } } else { return false; } } - + /** * Sets the fulfillment method. (Optional) - * + * * This method sets the Fulfillment Method to be sent in the next request. * If this parameter is not set, Amazon will assume a Consumer method. * Here is a quick description of the methods: @@ -247,61 +304,67 @@ public function setFulfillmentPolicy($s){ * @param string $s

    "Consumer" or "Removal"

    * @return boolean FALSE if improper input */ - public function setFulfillmentMethod($s){ - if (is_string($s)){ - if ($s == 'Consumer' || $s == 'Removal'){ + public function setFulfillmentMethod($s) + { + if (is_string($s)) { + if ($s == 'Consumer' || $s == 'Removal') { $this->options['FulfillmentMethod'] = $s; + return true; } else { - $this->log("Tried to set fulfillment method to invalid value",'Warning'); + $this->log("Tried to set fulfillment method to invalid value", 'Warning'); return false; } } else { return false; } } - + /** * Sets the email(s). (Optional) - * + * * This method sets the list of Email addresses to be sent in the next request. * Setting this parameter tells Amazon who to send emails to regarding the * completion of the shipment. * @param array|string $s

    A list of email addresses, or a single email address. (max: 64 chars each)

    * @return boolean FALSE if improper input */ - public function setEmails($s){ - if (is_string($s)){ + public function setEmails($s) + { + if (is_string($s)) { $this->resetEmails(); $this->options['NotificationEmailList.member.1'] = $s; - } else if (is_array($s) && $s){ - $this->resetEmails(); - $i = 1; - foreach ($s as $x){ - $this->options['NotificationEmailList.member.'.$i] = $x; - $i++; - } } else { - return false; + if (is_array($s) && $s) { + $this->resetEmails(); + $i = 1; + foreach ($s as $x) { + $this->options['NotificationEmailList.member.' . $i] = $x; + $i++; + } + } else { + return false; + } } } - + /** * Removes email options. - * + * * Use this in case you change your mind and want to remove the email * parameters you previously set. */ - public function resetEmails(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#NotificationEmailList#",$op)){ + public function resetEmails() + { + foreach ($this->options as $op => $junk) { + if (preg_match("#NotificationEmailList#", $op)) { unset($this->options[$op]); } } } - + /** * Sets the items. (Required) - * + * * This method sets the Fulfillment Order ID to be sent in the next request. * This parameter is required for creating a fulfillment order with Amazon. * The array provided should contain a list of arrays, each with the following fields: @@ -322,61 +385,66 @@ public function resetEmails(){ * @param array $a

    See above.

    * @return boolean FALSE if improper input */ - public function setItems($a){ - if (is_null($a) || is_string($a) || !$a){ - $this->log("Tried to set Items to invalid values",'Warning'); + public function setItems($a) + { + if (is_null($a) || is_string($a) || !$a) { + $this->log("Tried to set Items to invalid values", 'Warning'); return false; } $this->resetItems(); $i = 1; - foreach ($a as $x){ - if (is_array($x) && array_key_exists('SellerSKU', $x) && array_key_exists('SellerFulfillmentOrderItemId', $x) && array_key_exists('Quantity', $x)){ - $this->options['Items.member.'.$i.'.SellerSKU'] = $x['SellerSKU']; - $this->options['Items.member.'.$i.'.SellerFulfillmentOrderItemId'] = $x['SellerFulfillmentOrderItemId']; - $this->options['Items.member.'.$i.'.Quantity'] = $x['Quantity']; - if (array_key_exists('GiftMessage', $x)){ - $this->options['Items.member.'.$i.'.GiftMessage'] = $x['GiftMessage']; + foreach ($a as $x) { + if (is_array($x) && array_key_exists('SellerSKU', $x) && array_key_exists('SellerFulfillmentOrderItemId', + $x) && array_key_exists('Quantity', $x) + ) { + $this->options['Items.member.' . $i . '.SellerSKU'] = $x['SellerSKU']; + $this->options['Items.member.' . $i . '.SellerFulfillmentOrderItemId'] = $x['SellerFulfillmentOrderItemId']; + $this->options['Items.member.' . $i . '.Quantity'] = $x['Quantity']; + if (array_key_exists('GiftMessage', $x)) { + $this->options['Items.member.' . $i . '.GiftMessage'] = $x['GiftMessage']; } - if (array_key_exists('Comment', $x)){ - $this->options['Items.member.'.$i.'.DisplayableComment'] = $x['Comment']; + if (array_key_exists('Comment', $x)) { + $this->options['Items.member.' . $i . '.DisplayableComment'] = $x['Comment']; } - if (array_key_exists('FulfillmentNetworkSKU', $x)){ - $this->options['Items.member.'.$i.'.FulfillmentNetworkSKU'] = $x['FulfillmentNetworkSKU']; + if (array_key_exists('FulfillmentNetworkSKU', $x)) { + $this->options['Items.member.' . $i . '.FulfillmentNetworkSKU'] = $x['FulfillmentNetworkSKU']; } - if (array_key_exists('OrderItemDisposition', $x)){ - $this->options['Items.member.'.$i.'.OrderItemDisposition'] = $x['OrderItemDisposition']; + if (array_key_exists('OrderItemDisposition', $x)) { + $this->options['Items.member.' . $i . '.OrderItemDisposition'] = $x['OrderItemDisposition']; } - if (array_key_exists('PerUnitDeclaredValue', $x)){ - $this->options['Items.member.'.$i.'.PerUnitDeclaredValue.CurrencyCode'] = $x['PerUnitDeclaredValue']['CurrencyCode']; - $this->options['Items.member.'.$i.'.PerUnitDeclaredValue.Value'] = $x['PerUnitDeclaredValue']['Value']; + if (array_key_exists('PerUnitDeclaredValue', $x)) { + $this->options['Items.member.' . $i . '.PerUnitDeclaredValue.CurrencyCode'] = $x['PerUnitDeclaredValue']['CurrencyCode']; + $this->options['Items.member.' . $i . '.PerUnitDeclaredValue.Value'] = $x['PerUnitDeclaredValue']['Value']; } - + $i++; } else { $this->resetItems(); - $this->log("Tried to set Items with invalid array",'Warning'); + $this->log("Tried to set Items with invalid array", 'Warning'); return false; } } + return true; } - + /** * Resets the item options. - * + * * Since the list of items is a required parameter, these options should not be removed * without replacing them, so this method is not public. */ - protected function resetItems(){ - foreach($this->options as $op=>$junk){ - if(preg_match("#Items#",$op)){ + protected function resetItems() + { + foreach ($this->options as $op => $junk) { + if (preg_match("#Items#", $op)) { unset($this->options[$op]); } } } - + /** * Creates a Fulfillment Order with Amazon. - * + * * Submits a CreateFulfillmentOrder request to Amazon. In order to do this, * a number of parameters are required. Amazon will send back an HTTP response, * so there is no data to retrieve afterwards. The following parameters are required: @@ -384,52 +452,52 @@ protected function resetItems(){ * shipping speed, address, items. * @return boolean TRUE if the order creation was successful, FALSE if something goes wrong */ - public function createOrder(){ - if (!array_key_exists('SellerFulfillmentOrderId',$this->options)){ - $this->log("Seller Fulfillment OrderID must be set in order to create an order",'Warning'); + public function createOrder() + { + if (!array_key_exists('SellerFulfillmentOrderId', $this->options)) { + $this->log("Seller Fulfillment OrderID must be set in order to create an order", 'Warning'); return false; } - if (!array_key_exists('DisplayableOrderId',$this->options)){ - $this->log("Displayable Order ID must be set in order to create an order",'Warning'); + if (!array_key_exists('DisplayableOrderId', $this->options)) { + $this->log("Displayable Order ID must be set in order to create an order", 'Warning'); return false; } - if (!array_key_exists('DisplayableOrderDateTime',$this->options)){ - $this->log("Date must be set in order to create an order",'Warning'); + if (!array_key_exists('DisplayableOrderDateTime', $this->options)) { + $this->log("Date must be set in order to create an order", 'Warning'); return false; } - if (!array_key_exists('DisplayableOrderComment',$this->options)){ - $this->log("Comment must be set in order to create an order",'Warning'); + if (!array_key_exists('DisplayableOrderComment', $this->options)) { + $this->log("Comment must be set in order to create an order", 'Warning'); return false; } - if (!array_key_exists('ShippingSpeedCategory',$this->options)){ - $this->log("Shipping Speed must be set in order to create an order",'Warning'); + if (!array_key_exists('ShippingSpeedCategory', $this->options)) { + $this->log("Shipping Speed must be set in order to create an order", 'Warning'); return false; } - if (!array_key_exists('DestinationAddress.Name',$this->options)){ - $this->log("Address must be set in order to create an order",'Warning'); + if (!array_key_exists('DestinationAddress.Name', $this->options)) { + $this->log("Address must be set in order to create an order", 'Warning'); return false; } - if (!array_key_exists('Items.member.1.SellerSKU',$this->options)){ - $this->log("Items must be set in order to create an order",'Warning'); + if (!array_key_exists('Items.member.1.SellerSKU', $this->options)) { + $this->log("Items must be set in order to create an order", 'Warning'); return false; } - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - if ($this->mockMode){ + + $url = $this->urlbase . $this->urlbranch; + + if ($this->mockMode) { $response = $this->fetchMockResponse(); } else { - $response = $this->sendRequest($url, array('Post'=>$query)); + $response = $this->sendRequest($url); } - if (!$this->checkResponse($response)){ + if (!$this->checkResponse($response)) { return false; } else { - $this->log("Successfully created Fulfillment Order ".$this->options['SellerFulfillmentOrderId']." / ".$this->options['DisplayableOrderId']); + $this->log("Successfully created Fulfillment Order " . $this->options['SellerFulfillmentOrderId'] . " / " . $this->options['DisplayableOrderId']); return true; } } - + } + ?> diff --git a/src/Creacoon/AmazonMws/AmazonFulfillmentOrderList.php b/src/AmazonFulfillmentOrderList.php similarity index 83% rename from src/Creacoon/AmazonMws/AmazonFulfillmentOrderList.php rename to src/AmazonFulfillmentOrderList.php index c89b8d85..cb677f17 100755 --- a/src/Creacoon/AmazonMws/AmazonFulfillmentOrderList.php +++ b/src/AmazonFulfillmentOrderList.php @@ -1,4 +1,7 @@ -The files (or file) to use in Mock Mode.

    * @param string $config [optional]

    An alternate config file to set. Used for testing.

    */ - public function __construct($s, $mock = false, $m = null, $config = null) { - parent::__construct($s, $mock, $m, $config); - + public function __construct($s, $mock = false, $m = null) + { + parent::__construct($s, $mock, $m); + $this->options['Action'] = 'ListAllFulfillmentOrders'; } - + /** * Sets the start time. (Optional) - * + * * This method sets the earliest time frame to be sent in the next request. * If this parameter is set, Amazon will only return fulfillment orders that * were last updated after the time set. If this parameter is not set, Amazon @@ -60,18 +66,19 @@ public function __construct($s, $mock = false, $m = null, $config = null) { * @param string $s

    Time string.

    * @return boolean FALSE if improper input */ - public function setStartTime($s){ - if (is_string($s)){ + public function setStartTime($s) + { + if (is_string($s)) { $time = $this->genTime($s); $this->options['QueryStartDateTime'] = $time; } else { return false; } } - + /** * Sets the fulfillment method filter. (Optional) - * + * * This method sets the Fulfillment Method to be sent in the next request. * If this parameter is set, Amazon will return fulfillment orders using the given method. * If this parameter is not set, Amazon will only return fulfillment orders @@ -84,25 +91,27 @@ public function setStartTime($s){ * @param string $s

    "Consumer" or "Removal"

    * @return boolean FALSE if improper input */ - public function setMethodFilter($s){ - if ($s == 'Consumer' || $s == 'Removal'){ + public function setMethodFilter($s) + { + if ($s == 'Consumer' || $s == 'Removal') { $this->options['FulfillmentMethod'] = $s; } else { return false; } } - + /** * Returns whether or not a token is available. * @return boolean */ - public function hasToken(){ + public function hasToken() + { return $this->tokenFlag; } - + /** * Sets whether or not the object should automatically use tokens if it receives one. - * + * * If this option is set to TRUE, the object will automatically perform * the necessary operations to retrieve the rest of the list using tokens. If * this option is off, the object will only ever retrieve the first section of @@ -110,69 +119,70 @@ public function hasToken(){ * @param boolean $b [optional]

    Defaults to TRUE

    * @return boolean FALSE if improper input */ - public function setUseToken($b = true){ - if (is_bool($b)){ + public function setUseToken($b = true) + { + if (is_bool($b)) { $this->tokenUseFlag = $b; } else { return false; } } - + /** * Fetches the fulfillment order list from Amazon. - * + * * Submits a ListAllFulfillmentOrders request to Amazon. Amazon will send * the list back as a response, which can be retrieved using getOrder. * This operation can potentially involve tokens. * @param boolean

    When set to FALSE, the function will not recurse, defaults to TRUE

    * @return boolean FALSE if something goes wrong */ - public function fetchOrderList($r = true){ + public function fetchOrderList($r = true) + { $this->prepareToken(); - - - $url = $this->urlbase.$this->urlbranch; - - $query = $this->genQuery(); - - $path = $this->options['Action'].'Result'; - - if ($this->mockMode){ - $xml = $this->fetchMockFile()->$path; + + + $url = $this->urlbase . $this->urlbranch; + + $path = $this->options['Action'] . 'Result'; + + if ($this->mockMode) { + $xml = $this->fetchMockFile()->$path; } else { - $response = $this->sendRequest($url, array('Post'=>$query)); - - if (!$this->checkResponse($response)){ + $response = $this->sendRequest($url); + + if (!$this->checkResponse($response)) { return false; } - + $xml = simplexml_load_string($response['body'])->$path; } - + $this->parseXML($xml->FulfillmentOrders); - + $this->checkToken($xml); - - if ($this->tokenFlag && $this->tokenUseFlag && $r === true){ - while ($this->tokenFlag){ + + if ($this->tokenFlag && $this->tokenUseFlag && $r === true) { + while ($this->tokenFlag) { $this->log("Recursively fetching more Orders"); $this->fetchOrderList(false); } - + } - + } - + /** * Sets up options for using tokens. - * + * * This changes key options for switching between simply fetching a list and * fetching the rest of a list using a token. Please note: because the * operation for using tokens does not use any other parameters, all other * parameters will be removed. */ - protected function prepareToken(){ - if ($this->tokenFlag && $this->tokenUseFlag){ + protected function prepareToken() + { + if ($this->tokenFlag && $this->tokenUseFlag) { $this->options['Action'] = 'ListAllFulfillmentOrdersByNextToken'; unset($this->options['QueryStartDateTime']); unset($this->options['FulfillmentMethod']); @@ -183,92 +193,95 @@ protected function prepareToken(){ $this->index = 0; } } - + /** * Parses XML response into array. - * + * * This is what reads the response XML and converts it into an array. * @param SimpleXMLObject $xml

    The XML response from Amazon.

    * @return boolean FALSE if no XML data is found */ - protected function parseXML($xml){ - if (!$xml){ + protected function parseXML($xml) + { + if (!$xml) { return false; } - foreach($xml->children() as $x){ + foreach ($xml->children() as $x) { $i = $this->index; $this->orderList[$i]['SellerFulfillmentOrderId'] = (string)$x->SellerFulfillmentOrderId; $this->orderList[$i]['DisplayableOrderId'] = (string)$x->DisplayableOrderId; $this->orderList[$i]['DisplayableOrderDateTime'] = (string)$x->DisplayableOrderDateTime; $this->orderList[$i]['DisplayableOrderComment'] = (string)$x->DisplayableOrderComment; $this->orderList[$i]['ShippingSpeedCategory'] = (string)$x->ShippingSpeedCategory; - if (isset($x->DestinationAddress)){ + if (isset($x->DestinationAddress)) { $this->orderList[$i]['DestinationAddress']['Name'] = (string)$x->DestinationAddress->Name; $this->orderList[$i]['DestinationAddress']['Line1'] = (string)$x->DestinationAddress->Line1; - if (isset($x->DestinationAddress->Line2)){ + if (isset($x->DestinationAddress->Line2)) { $this->orderList[$i]['DestinationAddress']['Line2'] = (string)$x->DestinationAddress->Line2; } - if (isset($x->DestinationAddress->Line3)){ + if (isset($x->DestinationAddress->Line3)) { $this->orderList[$i]['DestinationAddress']['Line3'] = (string)$x->DestinationAddress->Line3; } - if (isset($x->DestinationAddress->DistrictOrCounty)){ + if (isset($x->DestinationAddress->DistrictOrCounty)) { $this->orderList[$i]['DestinationAddress']['DistrictOrCounty'] = (string)$x->DestinationAddress->DistrictOrCounty; } $this->orderList[$i]['DestinationAddress']['City'] = (string)$x->DestinationAddress->City; $this->orderList[$i]['DestinationAddress']['StateOrProvinceCode'] = (string)$x->DestinationAddress->StateOrProvinceCode; $this->orderList[$i]['DestinationAddress']['CountryCode'] = (string)$x->DestinationAddress->CountryCode; - if (isset($x->DestinationAddress->PostalCode)){ + if (isset($x->DestinationAddress->PostalCode)) { $this->orderList[$i]['DestinationAddress']['PostalCode'] = (string)$x->DestinationAddress->PostalCode; } - if (isset($x->DestinationAddress->PhoneNumber)){ + if (isset($x->DestinationAddress->PhoneNumber)) { $this->orderList[$i]['DestinationAddress']['PhoneNumber'] = (string)$x->DestinationAddress->PhoneNumber; } } - if (isset($x->FulfillmentPolicy)){ + if (isset($x->FulfillmentPolicy)) { $this->orderList[$i]['FulfillmentPolicy'] = (string)$x->FulfillmentPolicy; } - if (isset($x->FulfillmentMethod)){ + if (isset($x->FulfillmentMethod)) { $this->orderList[$i]['FulfillmentPolicy'] = (string)$x->FulfillmentMethod; } $this->orderList[$i]['ReceivedDateTime'] = (string)$x->ReceivedDateTime; $this->orderList[$i]['FulfillmentOrderStatus'] = (string)$x->FulfillmentOrderStatus; $this->orderList[$i]['StatusUpdatedDateTime'] = (string)$x->StatusUpdatedDateTime; - if (isset($x->NotificationEmailList)){ + if (isset($x->NotificationEmailList)) { $j = 0; - foreach($x->NotificationEmailList->children() as $y){ + foreach ($x->NotificationEmailList->children() as $y) { $this->orderList[$i]['NotificationEmailList'][$j++] = (string)$y; } } $this->index++; } } - + /** * Creates a list of full order objects from the list. (Warning: could take a while.) - * + * * This method automatically creates an array of AmazonFulfillmentOrder objects * and fetches all of their full information from Amazon. Because of throttling, this * could take a while if the list has more than a few orders. * @return array|boolean array of AmazonFulfillmentOrder objects, or FALSE if list not filled yet */ - public function getFullList(){ - if (!isset($this->orderList)){ + public function getFullList() + { + if (!isset($this->orderList)) { return false; } $list = array(); $i = 0; - foreach($this->orderList as $x){ - $list[$i] = new AmazonFulfillmentOrder($this->storeName,$x['SellerFulfillmentOrderId'],$this->mockMode,$this->mockFiles,$this->config); + foreach ($this->orderList as $x) { + $list[$i] = new AmazonFulfillmentOrder($this->storeName, $x['SellerFulfillmentOrderId'], $this->mockMode, + $this->mockFiles, $this->config); $list[$i]->mockIndex = $this->mockIndex; $list[$i]->fetchOrder(); $i++; } return $list; } - + /** * Returns the specified fulfillment order, or all of them. - * + * * This method will return FALSE if the list has not yet been filled. * The array for a single fulfillment order will have the following fields: *