@recaptime-dev's working patches + fork for Phorge, a community fork of Phabricator. (Upstream dev and stable branches are at upstream/main and upstream/stable respectively.) hq.recaptime.dev/wiki/Phorge
phorge phabricator
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

Remove WePay support from Phortune, and Restful/Httpful dependencies

Summary: Ref PHI1166. I'm documenting our dependencies, and we have approximately 5,000 lines of external code to support WePay as a Phortune provider. We don't use it, I'm almost certain it doesn't work, and we have no plans to use it in the near future. If we did pursue it, I'd probably just wrap the API in a 100-line `WePayFuture` anyway since 5K lines of dependencies to make a couple method calls is ridiculous.

Test Plan: Grepped for `wepay`, `httpful`, `restful`.

Reviewers: amckinley

Reviewed By: amckinley

Subscribers: aurelijus

Differential Revision: https://secure.phabricator.com/D20521

-5450
-4
externals/httpful/.gitignore
··· 1 - .DS_Store 2 - composer.lock 3 - vendor 4 - downloads
-5
externals/httpful/.travis.yml
··· 1 - language: php 2 - before_script: cd tests 3 - php: 4 - - 5.3 5 - - 5.4
-7
externals/httpful/LICENSE.txt
··· 1 - Copyright (c) 2012 Nate Good <me@nategood.com> 2 - 3 - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 - 5 - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 - 7 - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-137
externals/httpful/README.md
··· 1 - # Httpful 2 - 3 - [![Build Status](https://secure.travis-ci.org/nategood/httpful.png?branch=master)](http://travis-ci.org/nategood/httpful) 4 - 5 - [Httpful](http://phphttpclient.com) is a simple Http Client library for PHP 5.3+. There is an emphasis of readability, simplicity, and flexibility – basically provide the features and flexibility to get the job done and make those features really easy to use. 6 - 7 - Features 8 - 9 - - Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, PATCH and OPTIONS) 10 - - Custom Headers 11 - - Automatic "Smart" Parsing 12 - - Automatic Payload Serialization 13 - - Basic Auth 14 - - Client Side Certificate Auth 15 - - Request "Templates" 16 - 17 - # Sneak Peak 18 - 19 - Here's something to whet your appetite. Search the twitter API for tweets containing "#PHP". Include a trivial header for the heck of it. Notice that the library automatically interprets the response as JSON (can override this if desired) and parses it as an array of objects. 20 - 21 - $url = "http://search.twitter.com/search.json?q=" . urlencode('#PHP'); 22 - $response = Request::get($url) 23 - ->withXTrivialHeader('Just as a demo') 24 - ->send(); 25 - 26 - foreach ($response->body->results as $tweet) { 27 - echo "@{$tweet->from_user} tweets \"{$tweet->text}\"\n"; 28 - } 29 - 30 - # Installation 31 - 32 - ## Phar 33 - 34 - A [PHP Archive](http://php.net/manual/en/book.phar.php) (or .phar) file is available for [downloading](https://github.com/nategood/httpful/downloads). Simply [download](https://github.com/nategood/httpful/downloads) the .phar, drop it into your project, and include it like you would any other php file. _This method is ideal smaller projects, one off scripts, and quick API hacking_. 35 - 36 - <?php 37 - include('httpful.phar'); 38 - $r = \Httpful\Request::get($uri)->sendIt(); 39 - ... 40 - 41 - ## Composer 42 - 43 - Httpful is PSR-0 compliant and can be installed using [composer](http://getcomposer.org/). Simply add `nategood/httpful` to your composer.json file. _Composer is the sane alternative to PEAR. It is excellent for managing dependancies in larger projects_. 44 - 45 - { 46 - "require": { 47 - "nategood/httpful": "*" 48 - } 49 - } 50 - 51 - ## Install from Source 52 - 53 - Because Httpful is PSR-0 compliant, you can also just clone the Httpful repository and use a PSR-0 compatible autoloader to load the library, like [Symfony's](http://symfony.com/doc/current/components/class_loader.html). Alternatively you can use the PSR-0 compliant autoloader included with the Httpful (simply `require("bootstrap.php")`). 54 - 55 - # Show Me More! 56 - 57 - You can checkout the [Httpful Landing Page](http://phphttpclient.com) for more info including many examples and [documentation](http:://phphttpclient.com/docs). 58 - 59 - # Contributing 60 - 61 - Httpful highly encourages sending in pull requests. When submitting a pull request please: 62 - 63 - - All pull requests should target the `dev` branch (not `master`) 64 - - Make sure your code follows the [coding conventions](http://pear.php.net/manual/en/standards.php) 65 - - Please use soft tabs (four spaces) instead of hard tabs 66 - - Make sure you add appropriate test coverage for your changes 67 - - Run all unit tests in the test directory via `phpunit ./tests` 68 - - Include commenting where appropriate and add a descriptive pull request message 69 - 70 - # Changelog 71 - 72 - ## 0.2.3 73 - 74 - - FIX Overriding default Mime Handlers 75 - - FIX [PR #73](https://github.com/nategood/httpful/pull/73) Parsing http status codes 76 - 77 - ## 0.2.2 78 - 79 - - FEATURE Add support for parsing JSON responses as associative arrays instead of objects 80 - - FEATURE Better support for setting constructor arguments on Mime Handlers 81 - 82 - ## 0.2.1 83 - 84 - - FEATURE [PR #72](https://github.com/nategood/httpful/pull/72) Allow support for custom Accept header 85 - 86 - ## 0.2.0 87 - 88 - - REFACTOR [PR #49](https://github.com/nategood/httpful/pull/49) Broke headers out into their own class 89 - - REFACTOR [PR #54](https://github.com/nategood/httpful/pull/54) Added more specific Exceptions 90 - - FIX [PR #58](https://github.com/nategood/httpful/pull/58) Fixes throwing an error on an empty xml response 91 - - FEATURE [PR #57](https://github.com/nategood/httpful/pull/57) Adds support for digest authentication 92 - 93 - ## 0.1.6 94 - 95 - - Ability to set the number of max redirects via overloading `followRedirects(int max_redirects)` 96 - - Standards Compliant fix to `Accepts` header 97 - - Bug fix for bootstrap process when installed via Composer 98 - 99 - ## 0.1.5 100 - 101 - - Use `DIRECTORY_SEPARATOR` constant [PR #33](https://github.com/nategood/httpful/pull/32) 102 - - [PR #35](https://github.com/nategood/httpful/pull/35) 103 - - Added the raw\_headers property reference to response. 104 - - Compose request header and added raw\_header to Request object. 105 - - Fixed response has errors and added more comments for clarity. 106 - - Fixed header parsing to allow the minimum (status line only) and also cater for the actual CRLF ended headers as per RFC2616. 107 - - Added the perfect test Accept: header for all Acceptable scenarios see @b78e9e82cd9614fbe137c01bde9439c4e16ca323 for details. 108 - - Added default User-Agent header 109 - - `User-Agent: Httpful/0.1.5` + curl version + server software + PHP version 110 - - To bypass this "default" operation simply add a User-Agent to the request headers even a blank User-Agent is sufficient and more than simple enough to produce me thinks. 111 - - Completed test units for additions. 112 - - Added phpunit coverage reporting and helped phpunit auto locate the tests a bit easier. 113 - 114 - ## 0.1.4 115 - 116 - - Add support for CSV Handling [PR #32](https://github.com/nategood/httpful/pull/32) 117 - 118 - ## 0.1.3 119 - 120 - - Handle empty responses in JsonParser and XmlParser 121 - 122 - ## 0.1.2 123 - 124 - - Added support for setting XMLHandler configuration options 125 - - Added examples for overriding XmlHandler and registering a custom parser 126 - - Removed the httpful.php download (deprecated in favor of httpful.phar) 127 - 128 - ## 0.1.1 129 - 130 - - Bug fix serialization default case and phpunit tests 131 - 132 - ## 0.1.0 133 - 134 - - Added Support for Registering Mime Handlers 135 - - Created AbstractMimeHandler type that all Mime Handlers must extend 136 - - Pulled out the parsing/serializing logic from the Request/Response classes into their own MimeHandler classes 137 - - Added ability to register new mime handlers for mime types
-4
externals/httpful/bootstrap.php
··· 1 - <?php 2 - 3 - require(__DIR__ . '/src/Httpful/Bootstrap.php'); 4 - \Httpful\Bootstrap::init();
-51
externals/httpful/build
··· 1 - #!/usr/bin/php 2 - <?php 3 - 4 - /** 5 - * Build the whole library into a single file 6 - * as an easy drop in solution as opposed to 7 - * relying on autoloader. Sometimes we just 8 - * want to hack with an API as a one off thing. 9 - * Httpful should make this easy. 10 - */ 11 - 12 - function exit_unless($condition, $msg = null) { 13 - if ($condition) 14 - return; 15 - echo "[FAIL]\n$msg\n"; 16 - exit(1); 17 - } 18 - 19 - // Create the Httpful Phar 20 - echo "Building Phar... "; 21 - $base_dir = dirname(__FILE__); 22 - $source_dir = $base_dir . '/src/Httpful/'; 23 - $phar_path = $base_dir . '/downloads/httpful.phar'; 24 - $phar = new Phar($phar_path, 0, 'httpful.phar'); 25 - $stub = <<<HEREDOC 26 - <?php 27 - // Phar Stub File 28 - Phar::mapPhar('httpful.phar'); 29 - include('phar://httpful.phar/Httpful/Bootstrap.php'); 30 - \Httpful\Bootstrap::pharInit(); 31 - 32 - __HALT_COMPILER(); 33 - HEREDOC; 34 - try { 35 - $phar->setStub($stub); 36 - } catch(Exception $e) { 37 - $phar = false; 38 - } 39 - exit_unless($phar, "Unable to create a phar. Make certain you have phar.readonly=0 set in your ini file."); 40 - $phar->buildFromDirectory(dirname($source_dir)); 41 - echo "[ OK ]\n"; 42 - 43 - 44 - 45 - // Add it to git! 46 - echo "Adding httpful.phar to the repo... "; 47 - $return_code = 0; 48 - passthru("git add $phar_path", $return_code); 49 - exit_unless($return_code === 0, "Unable to add download files to git."); 50 - echo "[ OK ]\n"; 51 - echo "\nBuild completed sucessfully.\n\n";
-24
externals/httpful/composer.json
··· 1 - { 2 - "name": "nategood/httpful", 3 - "description": "A Readable, Chainable, REST friendly, PHP HTTP Client", 4 - "homepage": "http://github.com/nategood/httpful", 5 - "license": "MIT", 6 - "keywords": ["http", "curl", "rest", "restful", "api", "requests"], 7 - "version": "0.2.3", 8 - "authors": [ 9 - { 10 - "name": "Nate Good", 11 - "email": "me@nategood.com", 12 - "homepage": "http://nategood.com" 13 - } 14 - ], 15 - "require": { 16 - "php": ">=5.3", 17 - "ext-curl": "*" 18 - }, 19 - "autoload": { 20 - "psr-0": { 21 - "Httpful": "src/" 22 - } 23 - } 24 - }
-12
externals/httpful/examples/freebase.php
··· 1 - <?php 2 - /** 3 - * Grab some The Dead Weather albums from Freebase 4 - */ 5 - require(__DIR__ . '/../bootstrap.php'); 6 - 7 - $uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D"; 8 - $response = \Httpful\Request::get($uri) 9 - ->expectsJson() 10 - ->sendIt(); 11 - 12 - echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
-9
externals/httpful/examples/github.php
··· 1 - <?php 2 - // XML Example from GitHub 3 - require(__DIR__ . '/../bootstrap.php'); 4 - use \Httpful\Request; 5 - 6 - $uri = 'https://github.com/api/v2/xml/user/show/nategood'; 7 - $request = Request::get($uri)->send(); 8 - 9 - echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n";
-44
externals/httpful/examples/override.php
··· 1 - <?php 2 - require(__DIR__ . '/../bootstrap.php'); 3 - 4 - // We can override the default parser configuration options be registering 5 - // a parser with different configuration options for a particular mime type 6 - 7 - // Example setting a namespace for the XMLHandler parser 8 - $conf = array('namespace' => 'http://example.com'); 9 - \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); 10 - 11 - // We can also add the parsers with our own... 12 - class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter 13 - { 14 - /** 15 - * Takes a response body, and turns it into 16 - * a two dimensional array. 17 - * 18 - * @param string $body 19 - * @return mixed 20 - */ 21 - public function parse($body) 22 - { 23 - return str_getcsv($body); 24 - } 25 - 26 - /** 27 - * Takes a two dimensional array and turns it 28 - * into a serialized string to include as the 29 - * body of a request 30 - * 31 - * @param mixed $payload 32 - * @return string 33 - */ 34 - public function serialize($payload) 35 - { 36 - $serialized = ''; 37 - foreach ($payload as $line) { 38 - $serialized .= '"' . implode('","', $line) . '"' . "\n"; 39 - } 40 - return $serialized; 41 - } 42 - } 43 - 44 - \Httpful\Httpful::register('text/csv', new SimpleCsvHandler());
-24
externals/httpful/examples/showclix.php
··· 1 - <?php 2 - 3 - require(__DIR__ . '/../bootstrap.php'); 4 - 5 - use \Httpful\Request; 6 - 7 - // Get event details for a public event 8 - $uri = "http://api.showclix.com/Event/8175"; 9 - $response = Request::get($uri) 10 - ->expectsType('json') 11 - ->sendIt(); 12 - 13 - // Print out the event details 14 - echo "The event {$response->body->event} will take place on {$response->body->event_start}\n"; 15 - 16 - // Example overriding the default JSON handler with one that encodes the response as an array 17 - \Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true))); 18 - 19 - $response = Request::get($uri) 20 - ->expectsType('json') 21 - ->sendIt(); 22 - 23 - // Print out the event details 24 - echo "The event {$response->body['event']} will take place on {$response->body['event_start']}\n";
-13
externals/httpful/examples/twitter.php
··· 1 - <?php 2 - require(__DIR__ . '/../bootstrap.php'); 3 - 4 - $query = urlencode('#PHP'); 5 - $response = \Httpful\Request::get("http://search.twitter.com/search.json?q=$query")->send(); 6 - 7 - if (!$response->hasErrors()) { 8 - foreach ($response->body->results as $tweet) { 9 - echo "@{$tweet->from_user} tweets \"{$tweet->text}\"\n"; 10 - } 11 - } else { 12 - echo "Uh oh. Twitter gave us the old {$response->code} status.\n"; 13 - }
-97
externals/httpful/src/Httpful/Bootstrap.php
··· 1 - <?php 2 - 3 - namespace Httpful; 4 - 5 - /** 6 - * Bootstrap class that facilitates autoloading. A naive 7 - * PSR-0 autoloader. 8 - * 9 - * @author Nate Good <me@nategood.com> 10 - */ 11 - class Bootstrap 12 - { 13 - 14 - const DIR_GLUE = DIRECTORY_SEPARATOR; 15 - const NS_GLUE = '\\'; 16 - 17 - public static $registered = false; 18 - 19 - /** 20 - * Register the autoloader and any other setup needed 21 - */ 22 - public static function init() 23 - { 24 - spl_autoload_register(array('\Httpful\Bootstrap', 'autoload')); 25 - self::registerHandlers(); 26 - } 27 - 28 - /** 29 - * The autoload magic (PSR-0 style) 30 - * 31 - * @param string $classname 32 - */ 33 - public static function autoload($classname) 34 - { 35 - self::_autoload(dirname(dirname(__FILE__)), $classname); 36 - } 37 - 38 - /** 39 - * Register the autoloader and any other setup needed 40 - */ 41 - public static function pharInit() 42 - { 43 - spl_autoload_register(array('\Httpful\Bootstrap', 'pharAutoload')); 44 - self::registerHandlers(); 45 - } 46 - 47 - /** 48 - * Phar specific autoloader 49 - * 50 - * @param string $classname 51 - */ 52 - public static function pharAutoload($classname) 53 - { 54 - self::_autoload('phar://httpful.phar', $classname); 55 - } 56 - 57 - /** 58 - * @param string base 59 - * @param string classname 60 - */ 61 - private static function _autoload($base, $classname) 62 - { 63 - $parts = explode(self::NS_GLUE, $classname); 64 - $path = $base . self::DIR_GLUE . implode(self::DIR_GLUE, $parts) . '.php'; 65 - 66 - if (file_exists($path)) { 67 - require_once($path); 68 - } 69 - } 70 - /** 71 - * Register default mime handlers. Is idempotent. 72 - */ 73 - public static function registerHandlers() 74 - { 75 - if (self::$registered === true) { 76 - return; 77 - } 78 - 79 - // @todo check a conf file to load from that instead of 80 - // hardcoding into the library? 81 - $handlers = array( 82 - \Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(), 83 - \Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(), 84 - \Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(), 85 - \Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(), 86 - ); 87 - 88 - foreach ($handlers as $mime => $handler) { 89 - // Don't overwrite if the handler has already been registered 90 - if (Httpful::hasParserRegistered($mime)) 91 - continue; 92 - Httpful::register($mime, $handler); 93 - } 94 - 95 - self::$registered = true; 96 - } 97 - }
-7
externals/httpful/src/Httpful/Exception/ConnectionErrorException.php
··· 1 - <?php 2 - 3 - namespace Httpful\Exception; 4 - 5 - class ConnectionErrorException extends \Exception 6 - { 7 - }
-50
externals/httpful/src/Httpful/Handlers/CsvHandler.php
··· 1 - <?php 2 - /** 3 - * Mime Type: text/csv 4 - * @author Raja Kapur <rajak@twistedthrottle.com> 5 - */ 6 - 7 - namespace Httpful\Handlers; 8 - 9 - class CsvHandler extends MimeHandlerAdapter 10 - { 11 - /** 12 - * @param string $body 13 - * @return mixed 14 - */ 15 - public function parse($body) 16 - { 17 - if (empty($body)) 18 - return null; 19 - 20 - $parsed = array(); 21 - $fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r'); 22 - while (($r = fgetcsv($fp)) !== FALSE) { 23 - $parsed[] = $r; 24 - } 25 - 26 - if (empty($parsed)) 27 - throw new \Exception("Unable to parse response as CSV"); 28 - return $parsed; 29 - } 30 - 31 - /** 32 - * @param mixed $payload 33 - * @return string 34 - */ 35 - public function serialize($payload) 36 - { 37 - $fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+'); 38 - $i = 0; 39 - foreach ($payload as $fields) { 40 - if($i++ == 0) { 41 - fputcsv($fp, array_keys($fields)); 42 - } 43 - fputcsv($fp, $fields); 44 - } 45 - rewind($fp); 46 - $data = stream_get_contents($fp); 47 - fclose($fp); 48 - return $data; 49 - } 50 - }
-30
externals/httpful/src/Httpful/Handlers/FormHandler.php
··· 1 - <?php 2 - /** 3 - * Mime Type: application/x-www-urlencoded 4 - * @author Nathan Good <me@nategood.com> 5 - */ 6 - 7 - namespace Httpful\Handlers; 8 - 9 - class FormHandler extends MimeHandlerAdapter 10 - { 11 - /** 12 - * @param string $body 13 - * @return mixed 14 - */ 15 - public function parse($body) 16 - { 17 - $parsed = array(); 18 - parse_str($body, $parsed); 19 - return $parsed; 20 - } 21 - 22 - /** 23 - * @param mixed $payload 24 - * @return string 25 - */ 26 - public function serialize($payload) 27 - { 28 - return http_build_query($payload, null, '&'); 29 - } 30 - }
-40
externals/httpful/src/Httpful/Handlers/JsonHandler.php
··· 1 - <?php 2 - /** 3 - * Mime Type: application/json 4 - * @author Nathan Good <me@nategood.com> 5 - */ 6 - 7 - namespace Httpful\Handlers; 8 - 9 - class JsonHandler extends MimeHandlerAdapter 10 - { 11 - private $decode_as_array = false; 12 - 13 - public function init(array $args) 14 - { 15 - $this->decode_as_array = !!(array_key_exists('decode_as_array', $args) ? $args['decode_as_array'] : false); 16 - } 17 - 18 - /** 19 - * @param string $body 20 - * @return mixed 21 - */ 22 - public function parse($body) 23 - { 24 - if (empty($body)) 25 - return null; 26 - $parsed = json_decode($body, $this->decode_as_array); 27 - if (is_null($parsed)) 28 - throw new \Exception("Unable to parse response as JSON"); 29 - return $parsed; 30 - } 31 - 32 - /** 33 - * @param mixed $payload 34 - * @return string 35 - */ 36 - public function serialize($payload) 37 - { 38 - return json_encode($payload); 39 - } 40 - }
-43
externals/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php
··· 1 - <?php 2 - 3 - /** 4 - * Handlers are used to parse and serialize payloads for specific 5 - * mime types. You can register a custom handler via the register 6 - * method. You can also override a default parser in this way. 7 - */ 8 - 9 - namespace Httpful\Handlers; 10 - 11 - class MimeHandlerAdapter 12 - { 13 - public function __construct(array $args = array()) 14 - { 15 - $this->init($args); 16 - } 17 - 18 - /** 19 - * Initial setup of 20 - * @param array $args 21 - */ 22 - public function init(array $args) 23 - { 24 - } 25 - 26 - /** 27 - * @param string $body 28 - * @return mixed 29 - */ 30 - public function parse($body) 31 - { 32 - return $body; 33 - } 34 - 35 - /** 36 - * @param mixed $payload 37 - * @return string 38 - */ 39 - function serialize($payload) 40 - { 41 - return (string) $payload; 42 - } 43 - }
-44
externals/httpful/src/Httpful/Handlers/README.md
··· 1 - # Handlers 2 - 3 - Handlers are simple classes that are used to parse response bodies and serialize request payloads. All Handlers must extend the `MimeHandlerAdapter` class and implement two methods: `serialize($payload)` and `parse($response)`. Let's build a very basic Handler to register for the `text/csv` mime type. 4 - 5 - <?php 6 - 7 - class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter 8 - { 9 - /** 10 - * Takes a response body, and turns it into 11 - * a two dimensional array. 12 - * 13 - * @param string $body 14 - * @return mixed 15 - */ 16 - public function parse($body) 17 - { 18 - return str_getcsv($body); 19 - } 20 - 21 - /** 22 - * Takes a two dimensional array and turns it 23 - * into a serialized string to include as the 24 - * body of a request 25 - * 26 - * @param mixed $payload 27 - * @return string 28 - */ 29 - public function serialize($payload) 30 - { 31 - $serialized = ''; 32 - foreach ($payload as $line) { 33 - $serialized .= '"' . implode('","', $line) . '"' . "\n"; 34 - } 35 - return $serialized; 36 - } 37 - } 38 - 39 - 40 - Finally, you must register this handler for a particular mime type. 41 - 42 - Httpful::register('text/csv', new SimpleCsvHandler()); 43 - 44 - After this registering the handler in your source code, by default, any responses with a mime type of text/csv should be parsed by this handler.
-15
externals/httpful/src/Httpful/Handlers/XHtmlHandler.php
··· 1 - <?php 2 - /** 3 - * Mime Type: text/html 4 - * Mime Type: application/html+xml 5 - * 6 - * @author Nathan Good <me@nategood.com> 7 - */ 8 - 9 - namespace Httpful\Handlers; 10 - 11 - class XHtmlHandler extends MimeHandlerAdapter 12 - { 13 - // @todo add html specific parsing 14 - // see DomDocument::load http://docs.php.net/manual/en/domdocument.loadhtml.php 15 - }
-120
externals/httpful/src/Httpful/Handlers/XmlHandler.php
··· 1 - <?php 2 - /** 3 - * Mime Type: application/xml 4 - * 5 - * @author Zack Douglas <zack@zackerydouglas.info> 6 - * @author Nathan Good <me@nategood.com> 7 - */ 8 - 9 - namespace Httpful\Handlers; 10 - 11 - class XmlHandler extends MimeHandlerAdapter 12 - { 13 - /** 14 - * @var string $namespace xml namespace to use with simple_load_string 15 - */ 16 - private $namespace; 17 - 18 - /** 19 - * @var int $libxml_opts see http://www.php.net/manual/en/libxml.constants.php 20 - */ 21 - private $libxml_opts; 22 - 23 - /** 24 - * @param array $conf sets configuration options 25 - */ 26 - public function __construct(array $conf = array()) 27 - { 28 - $this->namespace = isset($conf['namespace']) ? $conf['namespace'] : ''; 29 - $this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0; 30 - } 31 - 32 - /** 33 - * @param string $body 34 - * @return mixed 35 - * @throws Exception if unable to parse 36 - */ 37 - public function parse($body) 38 - { 39 - if (empty($body)) 40 - return null; 41 - $parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace); 42 - if ($parsed === false) 43 - throw new \Exception("Unable to parse response as XML"); 44 - return $parsed; 45 - } 46 - 47 - /** 48 - * @param mixed $payload 49 - * @return string 50 - * @throws Exception if unable to serialize 51 - */ 52 - public function serialize($payload) 53 - { 54 - list($_, $dom) = $this->_future_serializeAsXml($payload); 55 - return $dom->saveXml(); 56 - } 57 - 58 - /** 59 - * @author Zack Douglas <zack@zackerydouglas.info> 60 - */ 61 - private function _future_serializeAsXml($value, $node = null, $dom = null) 62 - { 63 - if (!$dom) { 64 - $dom = new \DOMDocument; 65 - } 66 - if (!$node) { 67 - if (!is_object($value)) { 68 - $node = $dom->createElement('response'); 69 - $dom->appendChild($node); 70 - } else { 71 - $node = $dom; 72 - } 73 - } 74 - if (is_object($value)) { 75 - $objNode = $dom->createElement(get_class($value)); 76 - $node->appendChild($objNode); 77 - $this->_future_serializeObjectAsXml($value, $objNode, $dom); 78 - } else if (is_array($value)) { 79 - $arrNode = $dom->createElement('array'); 80 - $node->appendChild($arrNode); 81 - $this->_future_serializeArrayAsXml($value, $arrNode, $dom); 82 - } else if (is_bool($value)) { 83 - $node->appendChild($dom->createTextNode($value?'TRUE':'FALSE')); 84 - } else { 85 - $node->appendChild($dom->createTextNode($value)); 86 - } 87 - return array($node, $dom); 88 - } 89 - /** 90 - * @author Zack Douglas <zack@zackerydouglas.info> 91 - */ 92 - private function _future_serializeArrayAsXml($value, &$parent, &$dom) 93 - { 94 - foreach ($value as $k => &$v) { 95 - $n = $k; 96 - if (is_numeric($k)) { 97 - $n = "child-{$n}"; 98 - } 99 - $el = $dom->createElement($n); 100 - $parent->appendChild($el); 101 - $this->_future_serializeAsXml($v, $el, $dom); 102 - } 103 - return array($parent, $dom); 104 - } 105 - /** 106 - * @author Zack Douglas <zack@zackerydouglas.info> 107 - */ 108 - private function _future_serializeObjectAsXml($value, &$parent, &$dom) 109 - { 110 - $refl = new \ReflectionObject($value); 111 - foreach ($refl->getProperties() as $pr) { 112 - if (!$pr->isPrivate()) { 113 - $el = $dom->createElement($pr->getName()); 114 - $parent->appendChild($el); 115 - $this->_future_serializeAsXml($pr->getValue($value), $el, $dom); 116 - } 117 - } 118 - return array($parent, $dom); 119 - } 120 - }
-86
externals/httpful/src/Httpful/Http.php
··· 1 - <?php 2 - 3 - namespace Httpful; 4 - 5 - /** 6 - * @author Nate Good <me@nategood.com> 7 - */ 8 - class Http 9 - { 10 - const HEAD = 'HEAD'; 11 - const GET = 'GET'; 12 - const POST = 'POST'; 13 - const PUT = 'PUT'; 14 - const DELETE = 'DELETE'; 15 - const PATCH = 'PATCH'; 16 - const OPTIONS = 'OPTIONS'; 17 - const TRACE = 'TRACE'; 18 - 19 - /** 20 - * @return array of HTTP method strings 21 - */ 22 - public static function safeMethods() 23 - { 24 - return array(self::HEAD, self::GET, self::OPTIONS, self::TRACE); 25 - } 26 - 27 - /** 28 - * @return bool 29 - * @param string HTTP method 30 - */ 31 - public static function isSafeMethod($method) 32 - { 33 - return in_array($method, self::safeMethods()); 34 - } 35 - 36 - /** 37 - * @return bool 38 - * @param string HTTP method 39 - */ 40 - public static function isUnsafeMethod($method) 41 - { 42 - return !in_array($method, self::safeMethods()); 43 - } 44 - 45 - /** 46 - * @return array list of (always) idempotent HTTP methods 47 - */ 48 - public static function idempotentMethods() 49 - { 50 - // Though it is possible to be idempotent, POST 51 - // is not guarunteed to be, and more often than 52 - // not, it is not. 53 - return array(self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH); 54 - } 55 - 56 - /** 57 - * @return bool 58 - * @param string HTTP method 59 - */ 60 - public static function isIdempotent($method) 61 - { 62 - return in_array($method, self::safeidempotentMethodsMethods()); 63 - } 64 - 65 - /** 66 - * @return bool 67 - * @param string HTTP method 68 - */ 69 - public static function isNotIdempotent($method) 70 - { 71 - return !in_array($method, self::idempotentMethods()); 72 - } 73 - 74 - /** 75 - * @deprecated Technically anything *can* have a body, 76 - * they just don't have semantic meaning. So say's Roy 77 - * http://tech.groups.yahoo.com/group/rest-discuss/message/9962 78 - * 79 - * @return array of HTTP method strings 80 - */ 81 - public static function canHaveBody() 82 - { 83 - return array(self::POST, self::PUT, self::PATCH, self::OPTIONS); 84 - } 85 - 86 - }
-46
externals/httpful/src/Httpful/Httpful.php
··· 1 - <?php 2 - 3 - namespace Httpful; 4 - 5 - class Httpful { 6 - const VERSION = '0.1.7'; 7 - 8 - private static $mimeRegistrar = array(); 9 - private static $default = null; 10 - 11 - /** 12 - * @param string $mime_type 13 - * @param MimeHandlerAdapter $handler 14 - */ 15 - public static function register($mimeType, \Httpful\Handlers\MimeHandlerAdapter $handler) 16 - { 17 - self::$mimeRegistrar[$mimeType] = $handler; 18 - } 19 - 20 - /** 21 - * @param string $mime_type defaults to MimeHandlerAdapter 22 - * @return MimeHandlerAdapter 23 - */ 24 - public static function get($mimeType = null) 25 - { 26 - if (isset(self::$mimeRegistrar[$mimeType])) { 27 - return self::$mimeRegistrar[$mimeType]; 28 - } 29 - 30 - if (empty(self::$default)) { 31 - self::$default = new \Httpful\Handlers\MimeHandlerAdapter(); 32 - } 33 - 34 - return self::$default; 35 - } 36 - 37 - /** 38 - * Does this particular Mime Type have a parser registered 39 - * for it? 40 - * @return bool 41 - */ 42 - public static function hasParserRegistered($mimeType) 43 - { 44 - return isset(self::$mimeRegistrar[$mimeType]); 45 - } 46 - }
-58
externals/httpful/src/Httpful/Mime.php
··· 1 - <?php 2 - 3 - namespace Httpful; 4 - 5 - /** 6 - * Class to organize the Mime stuff a bit more 7 - * @author Nate Good <me@nategood.com> 8 - */ 9 - class Mime 10 - { 11 - const JSON = 'application/json'; 12 - const XML = 'application/xml'; 13 - const XHTML = 'application/html+xml'; 14 - const FORM = 'application/x-www-form-urlencoded'; 15 - const PLAIN = 'text/plain'; 16 - const JS = 'text/javascript'; 17 - const HTML = 'text/html'; 18 - const YAML = 'application/x-yaml'; 19 - const CSV = 'text/csv'; 20 - 21 - /** 22 - * Map short name for a mime type 23 - * to a full proper mime type 24 - */ 25 - public static $mimes = array( 26 - 'json' => self::JSON, 27 - 'xml' => self::XML, 28 - 'form' => self::FORM, 29 - 'plain' => self::PLAIN, 30 - 'text' => self::PLAIN, 31 - 'html' => self::HTML, 32 - 'xhtml' => self::XHTML, 33 - 'js' => self::JS, 34 - 'javascript'=> self::JS, 35 - 'yaml' => self::YAML, 36 - 'csv' => self::CSV, 37 - ); 38 - 39 - /** 40 - * Get the full Mime Type name from a "short name". 41 - * Returns the short if no mapping was found. 42 - * @return string full mime type (e.g. application/json) 43 - * @param string common name for mime type (e.g. json) 44 - */ 45 - public static function getFullMime($short_name) 46 - { 47 - return array_key_exists($short_name, self::$mimes) ? self::$mimes[$short_name] : $short_name; 48 - } 49 - 50 - /** 51 - * @return bool 52 - * @param string $short_name 53 - */ 54 - public static function supportsMimeType($short_name) 55 - { 56 - return array_key_exists($short_name, self::$mimes); 57 - } 58 - }
-984
externals/httpful/src/Httpful/Request.php
··· 1 - <?php 2 - 3 - namespace Httpful; 4 - 5 - use Httpful\Exception\ConnectionErrorException; 6 - 7 - /** 8 - * Clean, simple class for sending HTTP requests 9 - * in PHP. 10 - * 11 - * There is an emphasis of readability without loosing concise 12 - * syntax. As such, you will notice that the library lends 13 - * itself very nicely to "chaining". You will see several "alias" 14 - * methods: more readable method definitions that wrap 15 - * their more concise counterparts. You will also notice 16 - * no public constructor. This two adds to the readability 17 - * and "chainabilty" of the library. 18 - * 19 - * @author Nate Good <me@nategood.com> 20 - */ 21 - class Request 22 - { 23 - 24 - // Option constants 25 - const SERIALIZE_PAYLOAD_NEVER = 0; 26 - const SERIALIZE_PAYLOAD_ALWAYS = 1; 27 - const SERIALIZE_PAYLOAD_SMART = 2; 28 - 29 - const MAX_REDIRECTS_DEFAULT = 25; 30 - 31 - public $uri, 32 - $method = Http::GET, 33 - $headers = array(), 34 - $raw_headers = '', 35 - $strict_ssl = false, 36 - $content_type, 37 - $expected_type, 38 - $additional_curl_opts = array(), 39 - $auto_parse = true, 40 - $serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART, 41 - $username, 42 - $password, 43 - $serialized_payload, 44 - $payload, 45 - $parse_callback, 46 - $error_callback, 47 - $follow_redirects = false, 48 - $max_redirects = self::MAX_REDIRECTS_DEFAULT, 49 - $payload_serializers = array(); 50 - 51 - // Options 52 - // private $_options = array( 53 - // 'serialize_payload_method' => self::SERIALIZE_PAYLOAD_SMART 54 - // 'auto_parse' => true 55 - // ); 56 - 57 - // Curl Handle 58 - public $_ch, 59 - $_debug; 60 - 61 - // Template Request object 62 - private static $_template; 63 - 64 - /** 65 - * We made the constructor private to force the factory style. This was 66 - * done to keep the syntax cleaner and better the support the idea of 67 - * "default templates". Very basic and flexible as it is only intended 68 - * for internal use. 69 - * @param array $attrs hash of initial attribute values 70 - */ 71 - private function __construct($attrs = null) 72 - { 73 - if (!is_array($attrs)) return; 74 - foreach ($attrs as $attr => $value) { 75 - $this->$attr = $value; 76 - } 77 - } 78 - 79 - // Defaults Management 80 - 81 - /** 82 - * Let's you configure default settings for this 83 - * class from a template Request object. Simply construct a 84 - * Request object as much as you want to and then pass it to 85 - * this method. It will then lock in those settings from 86 - * that template object. 87 - * The most common of which may be default mime 88 - * settings or strict ssl settings. 89 - * Again some slight memory overhead incurred here but in the grand 90 - * scheme of things as it typically only occurs once 91 - * @param Request $template 92 - */ 93 - public static function ini(Request $template) 94 - { 95 - self::$_template = clone $template; 96 - } 97 - 98 - /** 99 - * Reset the default template back to the 100 - * library defaults. 101 - */ 102 - public static function resetIni() 103 - { 104 - self::_initializeDefaults(); 105 - } 106 - 107 - /** 108 - * Get default for a value based on the template object 109 - * @return mixed default value 110 - * @param string|null $attr Name of attribute (e.g. mime, headers) 111 - * if null just return the whole template object; 112 - */ 113 - public static function d($attr) 114 - { 115 - return isset($attr) ? self::$_template->$attr : self::$_template; 116 - } 117 - 118 - // Accessors 119 - 120 - /** 121 - * @return bool does the request have a timeout? 122 - */ 123 - public function hasTimeout() 124 - { 125 - return isset($this->timeout); 126 - } 127 - 128 - /** 129 - * @return bool has the internal curl request been initialized? 130 - */ 131 - public function hasBeenInitialized() 132 - { 133 - return isset($this->_ch); 134 - } 135 - 136 - /** 137 - * @return bool Is this request setup for basic auth? 138 - */ 139 - public function hasBasicAuth() 140 - { 141 - return isset($this->password) && isset($this->username); 142 - } 143 - 144 - /** 145 - * @return bool Is this request setup for digest auth? 146 - */ 147 - public function hasDigestAuth() 148 - { 149 - return isset($this->password) && isset($this->username) && $this->additional_curl_opts['CURLOPT_HTTPAUTH'] = CURLAUTH_DIGEST; 150 - } 151 - 152 - /** 153 - * Specify a HTTP timeout 154 - * @return Request $this 155 - * @param |int $timeout seconds to timeout the HTTP call 156 - */ 157 - public function timeout($timeout) 158 - { 159 - $this->timeout = $timeout; 160 - return $this; 161 - } 162 - 163 - /** 164 - * If the response is a 301 or 302 redirect, automatically 165 - * send off another request to that location 166 - * @return Request $this 167 - * @param bool|int $follow follow or not to follow or maximal number of redirects 168 - */ 169 - public function followRedirects($follow = true) 170 - { 171 - $this->max_redirects = $follow === true ? self::MAX_REDIRECTS_DEFAULT : max(0, $follow); 172 - $this->follow_redirects = (bool) $follow; 173 - return $this; 174 - } 175 - 176 - /** 177 - * @return Request $this 178 - * @see Request::followRedirects() 179 - */ 180 - public function doNotFollowRedirects() 181 - { 182 - return $this->followRedirects(false); 183 - } 184 - 185 - /** 186 - * Actually send off the request, and parse the response 187 - * @return string|associative array of parsed results 188 - * @throws ConnectionErrorException when unable to parse or communicate w server 189 - */ 190 - public function send() 191 - { 192 - if (!$this->hasBeenInitialized()) 193 - $this->_curlPrep(); 194 - 195 - $result = curl_exec($this->_ch); 196 - 197 - if ($result === false) { 198 - $this->_error(curl_error($this->_ch)); 199 - throw new ConnectionErrorException('Unable to connect.'); 200 - } 201 - 202 - $info = curl_getinfo($this->_ch); 203 - $response = explode("\r\n\r\n", $result, 2 + $info['redirect_count']); 204 - 205 - $body = array_pop($response); 206 - $headers = array_pop($response); 207 - 208 - return new Response($body, $headers, $this); 209 - } 210 - public function sendIt() 211 - { 212 - return $this->send(); 213 - } 214 - 215 - // Setters 216 - 217 - /** 218 - * @return Request this 219 - * @param string $uri 220 - */ 221 - public function uri($uri) 222 - { 223 - $this->uri = $uri; 224 - return $this; 225 - } 226 - 227 - /** 228 - * User Basic Auth. 229 - * Only use when over SSL/TSL/HTTPS. 230 - * @return Request this 231 - * @param string $username 232 - * @param string $password 233 - */ 234 - public function basicAuth($username, $password) 235 - { 236 - $this->username = $username; 237 - $this->password = $password; 238 - return $this; 239 - } 240 - // @alias of basicAuth 241 - public function authenticateWith($username, $password) 242 - { 243 - return $this->basicAuth($username, $password); 244 - } 245 - // @alias of basicAuth 246 - public function authenticateWithBasic($username, $password) 247 - { 248 - return $this->basicAuth($username, $password); 249 - } 250 - 251 - /** 252 - * User Digest Auth. 253 - * @return Request this 254 - * @param string $username 255 - * @param string $password 256 - */ 257 - public function digestAuth($username, $password) 258 - { 259 - $this->addOnCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); 260 - return $this->basicAuth($username, $password); 261 - } 262 - 263 - // @alias of digestAuth 264 - public function authenticateWithDigest($username, $password) 265 - { 266 - return $this->digestAuth($username, $password); 267 - } 268 - 269 - /** 270 - * @return is this request setup for client side cert? 271 - */ 272 - public function hasClientSideCert() { 273 - return isset($this->client_cert) && isset($this->client_key); 274 - } 275 - 276 - /** 277 - * Use Client Side Cert Authentication 278 - * @return Response $this 279 - * @param string $key file path to client key 280 - * @param string $cert file path to client cert 281 - * @param string $passphrase for client key 282 - * @param string $encoding default PEM 283 - */ 284 - public function clientSideCert($cert, $key, $passphrase = null, $encoding = 'PEM') 285 - { 286 - $this->client_cert = $cert; 287 - $this->client_key = $key; 288 - $this->client_passphrase = $passphrase; 289 - $this->client_encoding = $encoding; 290 - 291 - return $this; 292 - } 293 - // @alias of basicAuth 294 - public function authenticateWithCert($cert, $key, $passphrase = null, $encoding = 'PEM') 295 - { 296 - return $this->clientSideCert($cert, $key, $passphrase, $encoding); 297 - } 298 - 299 - /** 300 - * Set the body of the request 301 - * @return Request this 302 - * @param mixed $payload 303 - * @param string $mimeType 304 - */ 305 - public function body($payload, $mimeType = null) 306 - { 307 - $this->mime($mimeType); 308 - $this->payload = $payload; 309 - // Iserntentially don't call _serializePayload yet. Wait until 310 - // we actually send off the request to convert payload to string. 311 - // At that time, the `serialized_payload` is set accordingly. 312 - return $this; 313 - } 314 - 315 - /** 316 - * Helper function to set the Content type and Expected as same in 317 - * one swoop 318 - * @return Request this 319 - * @param string $mime mime type to use for content type and expected return type 320 - */ 321 - public function mime($mime) 322 - { 323 - if (empty($mime)) return $this; 324 - $this->content_type = $this->expected_type = Mime::getFullMime($mime); 325 - return $this; 326 - } 327 - // @alias of mime 328 - public function sendsAndExpectsType($mime) 329 - { 330 - return $this->mime($mime); 331 - } 332 - // @alias of mime 333 - public function sendsAndExpects($mime) 334 - { 335 - return $this->mime($mime); 336 - } 337 - 338 - /** 339 - * Set the method. Shouldn't be called often as the preferred syntax 340 - * for instantiation is the method specific factory methods. 341 - * @return Request this 342 - * @param string $method 343 - */ 344 - public function method($method) 345 - { 346 - if (empty($method)) return $this; 347 - $this->method = $method; 348 - return $this; 349 - } 350 - 351 - /** 352 - * @return Request this 353 - * @param string $mime 354 - */ 355 - public function expects($mime) 356 - { 357 - if (empty($mime)) return $this; 358 - $this->expected_type = Mime::getFullMime($mime); 359 - return $this; 360 - } 361 - // @alias of expects 362 - public function expectsType($mime) 363 - { 364 - return $this->expects($mime); 365 - } 366 - 367 - /** 368 - * @return Request this 369 - * @param string $mime 370 - */ 371 - public function contentType($mime) 372 - { 373 - if (empty($mime)) return $this; 374 - $this->content_type = Mime::getFullMime($mime); 375 - return $this; 376 - } 377 - // @alias of contentType 378 - public function sends($mime) 379 - { 380 - return $this->contentType($mime); 381 - } 382 - // @alias of contentType 383 - public function sendsType($mime) 384 - { 385 - return $this->contentType($mime); 386 - } 387 - 388 - /** 389 - * Do we strictly enforce SSL verification? 390 - * @return Request this 391 - * @param bool $strict 392 - */ 393 - public function strictSSL($strict) 394 - { 395 - $this->strict_ssl = $strict; 396 - return $this; 397 - } 398 - public function withoutStrictSSL() 399 - { 400 - return $this->strictSSL(false); 401 - } 402 - public function withStrictSSL() 403 - { 404 - return $this->strictSSL(true); 405 - } 406 - 407 - /** 408 - * Determine how/if we use the built in serialization by 409 - * setting the serialize_payload_method 410 - * The default (SERIALIZE_PAYLOAD_SMART) is... 411 - * - if payload is not a scalar (object/array) 412 - * use the appropriate serialize method according to 413 - * the Content-Type of this request. 414 - * - if the payload IS a scalar (int, float, string, bool) 415 - * than just return it as is. 416 - * When this option is set SERIALIZE_PAYLOAD_ALWAYS, 417 - * it will always use the appropriate 418 - * serialize option regardless of whether payload is scalar or not 419 - * When this option is set SERIALIZE_PAYLOAD_NEVER, 420 - * it will never use any of the serialization methods. 421 - * Really the only use for this is if you want the serialize methods 422 - * to handle strings or not (e.g. Blah is not valid JSON, but "Blah" 423 - * is). Forcing the serialization helps prevent that kind of error from 424 - * happening. 425 - * @return Request $this 426 - * @param int $mode 427 - */ 428 - public function serializePayload($mode) 429 - { 430 - $this->serialize_payload_method = $mode; 431 - return $this; 432 - } 433 - 434 - /** 435 - * @see Request::serializePayload() 436 - * @return Request 437 - */ 438 - public function neverSerializePayload() 439 - { 440 - return $this->serializePayload(self::SERIALIZE_PAYLOAD_NEVER); 441 - } 442 - 443 - /** 444 - * This method is the default behavior 445 - * @see Request::serializePayload() 446 - * @return Request 447 - */ 448 - public function smartSerializePayload() 449 - { 450 - return $this->serializePayload(self::SERIALIZE_PAYLOAD_SMART); 451 - } 452 - 453 - /** 454 - * @see Request::serializePayload() 455 - * @return Request 456 - */ 457 - public function alwaysSerializePayload() 458 - { 459 - return $this->serializePayload(self::SERIALIZE_PAYLOAD_ALWAYS); 460 - } 461 - 462 - /** 463 - * Add an additional header to the request 464 - * Can also use the cleaner syntax of 465 - * $Request->withMyHeaderName($my_value); 466 - * @see Request::__call() 467 - * 468 - * @return Request this 469 - * @param string $header_name 470 - * @param string $value 471 - */ 472 - public function addHeader($header_name, $value) 473 - { 474 - $this->headers[$header_name] = $value; 475 - return $this; 476 - } 477 - 478 - /** 479 - * Add group of headers all at once. Note: This is 480 - * here just as a convenience in very specific cases. 481 - * The preferred "readable" way would be to leverage 482 - * the support for custom header methods. 483 - * @return Response $this 484 - * @param array $headers 485 - */ 486 - public function addHeaders(array $headers) 487 - { 488 - foreach ($headers as $header => $value) { 489 - $this->addHeader($header, $value); 490 - } 491 - return $this; 492 - } 493 - 494 - /** 495 - * @return Request 496 - * @param bool $auto_parse perform automatic "smart" 497 - * parsing based on Content-Type or "expectedType" 498 - * If not auto parsing, Response->body returns the body 499 - * as a string. 500 - */ 501 - public function autoParse($auto_parse = true) 502 - { 503 - $this->auto_parse = $auto_parse; 504 - return $this; 505 - } 506 - 507 - /** 508 - * @see Request::autoParse() 509 - * @return Request 510 - */ 511 - public function withoutAutoParsing() 512 - { 513 - return $this->autoParse(false); 514 - } 515 - 516 - /** 517 - * @see Request::autoParse() 518 - * @return Request 519 - */ 520 - public function withAutoParsing() 521 - { 522 - return $this->autoParse(true); 523 - } 524 - 525 - /** 526 - * Use a custom function to parse the response. 527 - * @return Request this 528 - * @param \Closure $callback Takes the raw body of 529 - * the http response and returns a mixed 530 - */ 531 - public function parseWith(\Closure $callback) 532 - { 533 - $this->parse_callback = $callback; 534 - return $this; 535 - } 536 - 537 - /** 538 - * @see Request::parseResponsesWith() 539 - * @return Request $this 540 - * @param \Closure $callback 541 - */ 542 - public function parseResponsesWith(\Closure $callback) 543 - { 544 - return $this->parseWith($callback); 545 - } 546 - 547 - /** 548 - * Register a callback that will be used to serialize the payload 549 - * for a particular mime type. When using "*" for the mime 550 - * type, it will use that parser for all responses regardless of the mime 551 - * type. If a custom '*' and 'application/json' exist, the custom 552 - * 'application/json' would take precedence over the '*' callback. 553 - * 554 - * @return Request $this 555 - * @param string $mime mime type we're registering 556 - * @param Closure $callback takes one argument, $payload, 557 - * which is the payload that we'll be 558 - */ 559 - public function registerPayloadSerializer($mime, \Closure $callback) 560 - { 561 - $this->payload_serializers[Mime::getFullMime($mime)] = $callback; 562 - return $this; 563 - } 564 - 565 - /** 566 - * @see Request::registerPayloadSerializer() 567 - * @return Request $this 568 - * @param Closure $callback 569 - */ 570 - public function serializePayloadWith(\Closure $callback) 571 - { 572 - return $this->regregisterPayloadSerializer('*', $callback); 573 - } 574 - 575 - /** 576 - * Magic method allows for neatly setting other headers in a 577 - * similar syntax as the other setters. This method also allows 578 - * for the sends* syntax. 579 - * @return Request this 580 - * @param string $method "missing" method name called 581 - * the method name called should be the name of the header that you 582 - * are trying to set in camel case without dashes e.g. to set a 583 - * header for Content-Type you would use contentType() or more commonly 584 - * to add a custom header like X-My-Header, you would use xMyHeader(). 585 - * To promote readability, you can optionally prefix these methods with 586 - * "with" (e.g. withXMyHeader("blah") instead of xMyHeader("blah")). 587 - * @param array $args in this case, there should only ever be 1 argument provided 588 - * and that argument should be a string value of the header we're setting 589 - */ 590 - public function __call($method, $args) 591 - { 592 - // This method supports the sends* methods 593 - // like sendsJSON, sendsForm 594 - //!method_exists($this, $method) && 595 - if (substr($method, 0, 5) === 'sends') { 596 - $mime = strtolower(substr($method, 5)); 597 - if (Mime::supportsMimeType($mime)) { 598 - $this->sends(Mime::getFullMime($mime)); 599 - return $this; 600 - } 601 - // else { 602 - // throw new \Exception("Unsupported Content-Type $mime"); 603 - // } 604 - } 605 - if (substr($method, 0, 7) === 'expects') { 606 - $mime = strtolower(substr($method, 7)); 607 - if (Mime::supportsMimeType($mime)) { 608 - $this->expects(Mime::getFullMime($mime)); 609 - return $this; 610 - } 611 - // else { 612 - // throw new \Exception("Unsupported Content-Type $mime"); 613 - // } 614 - } 615 - 616 - // This method also adds the custom header support as described in the 617 - // method comments 618 - if (count($args) === 0) 619 - return; 620 - 621 - // Strip the sugar. If it leads with "with", strip. 622 - // This is okay because: No defined HTTP headers begin with with, 623 - // and if you are defining a custom header, the standard is to prefix it 624 - // with an "X-", so that should take care of any collisions. 625 - if (substr($method, 0, 4) === 'with') 626 - $method = substr($method, 4); 627 - 628 - // Precede upper case letters with dashes, uppercase the first letter of method 629 - $header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY))); 630 - $this->addHeader($header, $args[0]); 631 - return $this; 632 - } 633 - 634 - // Internal Functions 635 - 636 - /** 637 - * This is the default template to use if no 638 - * template has been provided. The template 639 - * tells the class which default values to use. 640 - * While there is a slight overhead for object 641 - * creation once per execution (not once per 642 - * Request instantiation), it promotes readability 643 - * and flexibility within the class. 644 - */ 645 - private static function _initializeDefaults() 646 - { 647 - // This is the only place you will 648 - // see this constructor syntax. It 649 - // is only done here to prevent infinite 650 - // recusion. Do not use this syntax elsewhere. 651 - // It goes against the whole readability 652 - // and transparency idea. 653 - self::$_template = new Request(array('method' => Http::GET)); 654 - 655 - // This is more like it... 656 - self::$_template 657 - ->withoutStrictSSL(); 658 - } 659 - 660 - /** 661 - * Set the defaults on a newly instantiated object 662 - * Doesn't copy variables prefixed with _ 663 - * @return Request this 664 - */ 665 - private function _setDefaults() 666 - { 667 - if (!isset(self::$_template)) 668 - self::_initializeDefaults(); 669 - foreach (self::$_template as $k=>$v) { 670 - if ($k[0] != '_') 671 - $this->$k = $v; 672 - } 673 - return $this; 674 - } 675 - 676 - private function _error($error) 677 - { 678 - // Default actions write to error log 679 - // TODO add in support for various Loggers 680 - error_log($error); 681 - } 682 - 683 - /** 684 - * Factory style constructor works nicer for chaining. This 685 - * should also really only be used internally. The Request::get, 686 - * Request::post syntax is preferred as it is more readable. 687 - * @return Request 688 - * @param string $method Http Method 689 - * @param string $mime Mime Type to Use 690 - */ 691 - public static function init($method = null, $mime = null) 692 - { 693 - // Setup our handlers, can call it here as it's idempotent 694 - Bootstrap::init(); 695 - 696 - // Setup the default template if need be 697 - if (!isset(self::$_template)) 698 - self::_initializeDefaults(); 699 - 700 - $request = new Request(); 701 - return $request 702 - ->_setDefaults() 703 - ->method($method) 704 - ->sendsType($mime) 705 - ->expectsType($mime); 706 - } 707 - 708 - /** 709 - * Does the heavy lifting. Uses de facto HTTP 710 - * library cURL to set up the HTTP request. 711 - * Note: It does NOT actually send the request 712 - * @return Request $this; 713 - */ 714 - public function _curlPrep() 715 - { 716 - // Check for required stuff 717 - if (!isset($this->uri)) 718 - throw new \Exception('Attempting to send a request before defining a URI endpoint.'); 719 - 720 - $ch = curl_init($this->uri); 721 - 722 - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method); 723 - 724 - if ($this->hasBasicAuth()) { 725 - curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password); 726 - } 727 - 728 - if ($this->hasClientSideCert()) { 729 - 730 - if (!file_exists($this->client_key)) 731 - throw new \Exception('Could not read Client Key'); 732 - 733 - if (!file_exists($this->client_cert)) 734 - throw new \Exception('Could not read Client Certificate'); 735 - 736 - curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding); 737 - curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding); 738 - curl_setopt($ch, CURLOPT_SSLCERT, $this->client_cert); 739 - curl_setopt($ch, CURLOPT_SSLKEY, $this->client_key); 740 - curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $this->client_passphrase); 741 - // curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->client_cert_passphrase); 742 - } 743 - 744 - if ($this->hasTimeout()) { 745 - curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); 746 - } 747 - 748 - if ($this->follow_redirects) { 749 - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 750 - curl_setopt($ch, CURLOPT_MAXREDIRS, $this->max_redirects); 751 - } 752 - 753 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->strict_ssl); 754 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 755 - 756 - $headers = array(); 757 - // https://github.com/nategood/httpful/issues/37 758 - // Except header removes any HTTP 1.1 Continue from response headers 759 - $headers[] = 'Expect:'; 760 - 761 - if (!isset($this->headers['User-Agent'])) { 762 - $headers[] = $this->buildUserAgent(); 763 - } 764 - 765 - $headers[] = "Content-Type: {$this->content_type}"; 766 - 767 - // allow custom Accept header if set 768 - if (!isset($this->headers['Accept'])) { 769 - // http://pretty-rfc.herokuapp.com/RFC2616#header.accept 770 - $accept = 'Accept: */*; q=0.5, text/plain; q=0.8, text/html;level=3;'; 771 - 772 - if (!empty($this->expected_type)) { 773 - $accept .= "q=0.9, {$this->expected_type}"; 774 - } 775 - 776 - $headers[] = $accept; 777 - } 778 - 779 - foreach ($this->headers as $header => $value) { 780 - $headers[] = "$header: $value"; 781 - } 782 - 783 - $url = \parse_url($this->uri); 784 - $path = (isset($url['path']) ? $url['path'] : '/').(isset($url['query']) ? '?'.$url['query'] : ''); 785 - $this->raw_headers = "{$this->method} $path HTTP/1.1\r\n"; 786 - $host = (isset($url['host']) ? $url['host'] : 'localhost').(isset($url['port']) ? ':'.$url['port'] : ''); 787 - $this->raw_headers .= "Host: $host\r\n"; 788 - $this->raw_headers .= \implode("\r\n", $headers); 789 - $this->raw_headers .= "\r\n"; 790 - 791 - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 792 - 793 - if (isset($this->payload)) { 794 - $this->serialized_payload = $this->_serializePayload($this->payload); 795 - curl_setopt($ch, CURLOPT_POSTFIELDS, $this->serialized_payload); 796 - } 797 - 798 - if ($this->_debug) { 799 - curl_setopt($ch, CURLOPT_VERBOSE, true); 800 - } 801 - 802 - curl_setopt($ch, CURLOPT_HEADER, 1); 803 - 804 - // If there are some additional curl opts that the user wants 805 - // to set, we can tack them in here 806 - foreach ($this->additional_curl_opts as $curlopt => $curlval) { 807 - curl_setopt($ch, $curlopt, $curlval); 808 - } 809 - 810 - $this->_ch = $ch; 811 - 812 - return $this; 813 - } 814 - 815 - public function buildUserAgent() { 816 - $user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/'; 817 - $curl = \curl_version(); 818 - 819 - if (isset($curl['version'])) { 820 - $user_agent .= $curl['version']; 821 - } else { 822 - $user_agent .= '?.?.?'; 823 - } 824 - 825 - $user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')'; 826 - 827 - if (isset($_SERVER['SERVER_SOFTWARE'])) { 828 - $user_agent .= ' ' . \preg_replace('~PHP/[\d\.]+~U', '', 829 - $_SERVER['SERVER_SOFTWARE']); 830 - } else { 831 - if (isset($_SERVER['TERM_PROGRAM'])) { 832 - $user_agent .= " {$_SERVER['TERM_PROGRAM']}"; 833 - } 834 - 835 - if (isset($_SERVER['TERM_PROGRAM_VERSION'])) { 836 - $user_agent .= "/{$_SERVER['TERM_PROGRAM_VERSION']}"; 837 - } 838 - } 839 - 840 - if (isset($_SERVER['HTTP_USER_AGENT'])) { 841 - $user_agent .= " {$_SERVER['HTTP_USER_AGENT']}"; 842 - } 843 - 844 - $user_agent .= ')'; 845 - 846 - return $user_agent; 847 - } 848 - 849 - /** 850 - * Semi-reluctantly added this as a way to add in curl opts 851 - * that are not otherwise accessible from the rest of the API. 852 - * @return Request $this 853 - * @param string $curlopt 854 - * @param mixed $curloptval 855 - */ 856 - public function addOnCurlOption($curlopt, $curloptval) 857 - { 858 - $this->additional_curl_opts[$curlopt] = $curloptval; 859 - return $this; 860 - } 861 - 862 - /** 863 - * Turn payload from structured data into 864 - * a string based on the current Mime type. 865 - * This uses the auto_serialize option to determine 866 - * it's course of action. See serialize method for more. 867 - * Renamed from _detectPayload to _serializePayload as of 868 - * 2012-02-15. 869 - * 870 - * Added in support for custom payload serializers. 871 - * The serialize_payload_method stuff still holds true though. 872 - * @see Request::registerPayloadSerializer() 873 - * 874 - * @return string 875 - * @param mixed $payload 876 - */ 877 - private function _serializePayload($payload) 878 - { 879 - if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) 880 - return $payload; 881 - 882 - // When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized 883 - if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) 884 - return $payload; 885 - 886 - // Use a custom serializer if one is registered for this mime type 887 - if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) { 888 - $key = isset($this->payload_serializers[$this->content_type]) ? $this->content_type : '*'; 889 - return call_user_func($this->payload_serializers[$key], $payload); 890 - } 891 - 892 - return Httpful::get($this->content_type)->serialize($payload); 893 - } 894 - 895 - /** 896 - * HTTP Method Get 897 - * @return Request 898 - * @param string $uri optional uri to use 899 - * @param string $mime expected 900 - */ 901 - public static function get($uri, $mime = null) 902 - { 903 - return self::init(Http::GET)->uri($uri)->mime($mime); 904 - } 905 - 906 - 907 - /** 908 - * Like Request:::get, except that it sends off the request as well 909 - * returning a response 910 - * @return Response 911 - * @param string $uri optional uri to use 912 - * @param string $mime expected 913 - */ 914 - public static function getQuick($uri, $mime = null) 915 - { 916 - return self::get($uri, $mime)->send(); 917 - } 918 - 919 - /** 920 - * HTTP Method Post 921 - * @return Request 922 - * @param string $uri optional uri to use 923 - * @param string $payload data to send in body of request 924 - * @param string $mime MIME to use for Content-Type 925 - */ 926 - public static function post($uri, $payload = null, $mime = null) 927 - { 928 - return self::init(Http::POST)->uri($uri)->body($payload, $mime); 929 - } 930 - 931 - /** 932 - * HTTP Method Put 933 - * @return Request 934 - * @param string $uri optional uri to use 935 - * @param string $payload data to send in body of request 936 - * @param string $mime MIME to use for Content-Type 937 - */ 938 - public static function put($uri, $payload = null, $mime = null) 939 - { 940 - return self::init(Http::PUT)->uri($uri)->body($payload, $mime); 941 - } 942 - 943 - /** 944 - * HTTP Method Patch 945 - * @return Request 946 - * @param string $uri optional uri to use 947 - * @param string $payload data to send in body of request 948 - * @param string $mime MIME to use for Content-Type 949 - */ 950 - public static function patch($uri, $payload = null, $mime = null) 951 - { 952 - return self::init(Http::PATCH)->uri($uri)->body($payload, $mime); 953 - } 954 - 955 - /** 956 - * HTTP Method Delete 957 - * @return Request 958 - * @param string $uri optional uri to use 959 - */ 960 - public static function delete($uri, $mime = null) 961 - { 962 - return self::init(Http::DELETE)->uri($uri)->mime($mime); 963 - } 964 - 965 - /** 966 - * HTTP Method Head 967 - * @return Request 968 - * @param string $uri optional uri to use 969 - */ 970 - public static function head($uri) 971 - { 972 - return self::init(Http::HEAD)->uri($uri); 973 - } 974 - 975 - /** 976 - * HTTP Method Options 977 - * @return Request 978 - * @param string $uri optional uri to use 979 - */ 980 - public static function options($uri) 981 - { 982 - return self::init(Http::OPTIONS)->uri($uri); 983 - } 984 - }
-189
externals/httpful/src/Httpful/Response.php
··· 1 - <?php 2 - 3 - namespace Httpful; 4 - 5 - /** 6 - * Models an HTTP response 7 - * 8 - * @author Nate Good <me@nategood.com> 9 - */ 10 - class Response 11 - { 12 - 13 - public $body, 14 - $raw_body, 15 - $headers, 16 - $raw_headers, 17 - $request, 18 - $code = 0, 19 - $content_type, 20 - $parent_type, 21 - $charset, 22 - $is_mime_vendor_specific = false, 23 - $is_mime_personal = false; 24 - 25 - private $parsers; 26 - /** 27 - * @param string $body 28 - * @param string $headers 29 - * @param Request $request 30 - */ 31 - public function __construct($body, $headers, Request $request) 32 - { 33 - $this->request = $request; 34 - $this->raw_headers = $headers; 35 - $this->raw_body = $body; 36 - 37 - $this->code = $this->_parseCode($headers); 38 - $this->headers = Response\Headers::fromString($headers); 39 - 40 - $this->_interpretHeaders(); 41 - 42 - $this->body = $this->_parse($body); 43 - } 44 - 45 - /** 46 - * Status Code Definitions 47 - * 48 - * Informational 1xx 49 - * Successful 2xx 50 - * Redirection 3xx 51 - * Client Error 4xx 52 - * Server Error 5xx 53 - * 54 - * http://pretty-rfc.herokuapp.com/RFC2616#status.codes 55 - * 56 - * @return bool Did we receive a 4xx or 5xx? 57 - */ 58 - public function hasErrors() 59 - { 60 - return $this->code >= 400; 61 - } 62 - 63 - /** 64 - * @return return bool 65 - */ 66 - public function hasBody() 67 - { 68 - return !empty($this->body); 69 - } 70 - 71 - /** 72 - * Parse the response into a clean data structure 73 - * (most often an associative array) based on the expected 74 - * Mime type. 75 - * @return array|string|object the response parse accordingly 76 - * @param string Http response body 77 - */ 78 - public function _parse($body) 79 - { 80 - // If the user decided to forgo the automatic 81 - // smart parsing, short circuit. 82 - if (!$this->request->auto_parse) { 83 - return $body; 84 - } 85 - 86 - // If provided, use custom parsing callback 87 - if (isset($this->request->parse_callback)) { 88 - return call_user_func($this->request->parse_callback, $body); 89 - } 90 - 91 - // Decide how to parse the body of the response in the following order 92 - // 1. If provided, use the mime type specifically set as part of the `Request` 93 - // 2. If a MimeHandler is registered for the content type, use it 94 - // 3. If provided, use the "parent type" of the mime type from the response 95 - // 4. Default to the content-type provided in the response 96 - $parse_with = $this->request->expected_type; 97 - if (empty($this->request->expected_type)) { 98 - $parse_with = Httpful::hasParserRegistered($this->content_type) 99 - ? $this->content_type 100 - : $this->parent_type; 101 - } 102 - 103 - return Httpful::get($parse_with)->parse($body); 104 - } 105 - 106 - /** 107 - * Parse text headers from response into 108 - * array of key value pairs 109 - * @return array parse headers 110 - * @param string $headers raw headers 111 - */ 112 - public function _parseHeaders($headers) 113 - { 114 - $headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY); 115 - $parse_headers = array(); 116 - for ($i = 1; $i < count($headers); $i++) { 117 - list($key, $raw_value) = explode(':', $headers[$i], 2); 118 - $key = trim($key); 119 - $value = trim($raw_value); 120 - if (array_key_exists($key, $parse_headers)) { 121 - // See HTTP RFC Sec 4.2 Paragraph 5 122 - // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 123 - // If a header appears more than once, it must also be able to 124 - // be represented as a single header with a comma-separated 125 - // list of values. We transform accordingly. 126 - $parse_headers[$key] .= ',' . $value; 127 - } else { 128 - $parse_headers[$key] = $value; 129 - } 130 - } 131 - return $parse_headers; 132 - } 133 - 134 - public function _parseCode($headers) 135 - { 136 - $parts = explode(' ', substr($headers, 0, strpos($headers, "\r\n"))); 137 - if (count($parts) < 2 || !is_numeric($parts[1])) { 138 - throw new \Exception("Unable to parse response code from HTTP response due to malformed response"); 139 - } 140 - return intval($parts[1]); 141 - } 142 - 143 - /** 144 - * After we've parse the headers, let's clean things 145 - * up a bit and treat some headers specially 146 - */ 147 - public function _interpretHeaders() 148 - { 149 - // Parse the Content-Type and charset 150 - $content_type = isset($this->headers['Content-Type']) ? $this->headers['Content-Type'] : ''; 151 - $content_type = explode(';', $content_type); 152 - 153 - $this->content_type = $content_type[0]; 154 - if (count($content_type) == 2 && strpos($content_type[1], '=') !== false) { 155 - list($nill, $this->charset) = explode('=', $content_type[1]); 156 - } 157 - 158 - // RFC 2616 states "text/*" Content-Types should have a default 159 - // charset of ISO-8859-1. "application/*" and other Content-Types 160 - // are assumed to have UTF-8 unless otherwise specified. 161 - // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 162 - // http://www.w3.org/International/O-HTTP-charset.en.php 163 - if (!isset($this->charset)) { 164 - $this->charset = substr($this->content_type, 5) === 'text/' ? 'iso-8859-1' : 'utf-8'; 165 - } 166 - 167 - // Is vendor type? Is personal type? 168 - if (strpos($this->content_type, '/') !== false) { 169 - list($type, $sub_type) = explode('/', $this->content_type); 170 - $this->is_mime_vendor_specific = substr($sub_type, 0, 4) === 'vnd.'; 171 - $this->is_mime_personal = substr($sub_type, 0, 4) === 'prs.'; 172 - } 173 - 174 - // Parent type (e.g. xml for application/vnd.github.message+xml) 175 - $this->parent_type = $this->content_type; 176 - if (strpos($this->content_type, '+') !== false) { 177 - list($vendor, $this->parent_type) = explode('+', $this->content_type, 2); 178 - $this->parent_type = Mime::getFullMime($this->parent_type); 179 - } 180 - } 181 - 182 - /** 183 - * @return string 184 - */ 185 - public function __toString() 186 - { 187 - return $this->raw_body; 188 - } 189 - }
-58
externals/httpful/src/Httpful/Response/Headers.php
··· 1 - <?php 2 - 3 - namespace Httpful\Response; 4 - 5 - final class Headers implements \ArrayAccess, \Countable { 6 - 7 - private $headers; 8 - 9 - private function __construct($headers) 10 - { 11 - $this->headers = $headers; 12 - } 13 - 14 - public static function fromString($string) 15 - { 16 - $lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY); 17 - array_shift($lines); // HTTP HEADER 18 - $headers = array(); 19 - foreach ($lines as $line) { 20 - list($name, $value) = explode(':', $line, 2); 21 - $headers[strtolower(trim($name))] = trim($value); 22 - } 23 - return new self($headers); 24 - } 25 - 26 - public function offsetExists($offset) 27 - { 28 - return isset($this->headers[strtolower($offset)]); 29 - } 30 - 31 - public function offsetGet($offset) 32 - { 33 - if (isset($this->headers[$name = strtolower($offset)])) { 34 - return $this->headers[$name]; 35 - } 36 - } 37 - 38 - public function offsetSet($offset, $value) 39 - { 40 - throw new \Exception("Headers are read-only."); 41 - } 42 - 43 - public function offsetUnset($offset) 44 - { 45 - throw new \Exception("Headers are read-only."); 46 - } 47 - 48 - public function count() 49 - { 50 - return count($this->headers); 51 - } 52 - 53 - public function toArray() 54 - { 55 - return $this->headers; 56 - } 57 - 58 - }
-458
externals/httpful/tests/Httpful/HttpfulTest.php
··· 1 - <?php 2 - /** 3 - * Port over the original tests into a more traditional PHPUnit 4 - * format. Still need to hook into a lightweight HTTP server to 5 - * better test some things (e.g. obscure cURL settings). I've moved 6 - * the old tests and node.js server to the tests/.legacy directory. 7 - * 8 - * @author Nate Good <me@nategood.com> 9 - */ 10 - namespace Httpful\Test; 11 - 12 - require(dirname(dirname(dirname(__FILE__))) . '/bootstrap.php'); 13 - \Httpful\Bootstrap::init(); 14 - 15 - use Httpful\Httpful; 16 - use Httpful\Request; 17 - use Httpful\Mime; 18 - use Httpful\Http; 19 - use Httpful\Response; 20 - 21 - class HttpfulTest extends \PHPUnit_Framework_TestCase 22 - { 23 - const TEST_SERVER = '127.0.0.1:8008'; 24 - const TEST_URL = 'http://127.0.0.1:8008'; 25 - const TEST_URL_400 = 'http://127.0.0.1:8008/400'; 26 - 27 - const SAMPLE_JSON_HEADER = 28 - "HTTP/1.1 200 OK 29 - Content-Type: application/json 30 - Connection: keep-alive 31 - Transfer-Encoding: chunked\r\n"; 32 - const SAMPLE_JSON_RESPONSE = '{"key":"value","object":{"key":"value"},"array":[1,2,3,4]}'; 33 - const SAMPLE_CSV_HEADER = 34 - "HTTP/1.1 200 OK 35 - Content-Type: text/csv 36 - Connection: keep-alive 37 - Transfer-Encoding: chunked\r\n"; 38 - const SAMPLE_CSV_RESPONSE = 39 - "Key1,Key2 40 - Value1,Value2 41 - \"40.0\",\"Forty\""; 42 - const SAMPLE_XML_RESPONSE = '<stdClass><arrayProp><array><k1><myClass><intProp>2</intProp></myClass></k1></array></arrayProp><stringProp>a string</stringProp><boolProp>TRUE</boolProp></stdClass>'; 43 - const SAMPLE_XML_HEADER = 44 - "HTTP/1.1 200 OK 45 - Content-Type: application/xml 46 - Connection: keep-alive 47 - Transfer-Encoding: chunked\r\n"; 48 - const SAMPLE_VENDOR_HEADER = 49 - "HTTP/1.1 200 OK 50 - Content-Type: application/vnd.nategood.message+xml 51 - Connection: keep-alive 52 - Transfer-Encoding: chunked\r\n"; 53 - const SAMPLE_VENDOR_TYPE = "application/vnd.nategood.message+xml"; 54 - const SAMPLE_MULTI_HEADER = 55 - "HTTP/1.1 200 OK 56 - Content-Type: application/json 57 - Connection: keep-alive 58 - Transfer-Encoding: chunked 59 - X-My-Header:Value1 60 - X-My-Header:Value2\r\n"; 61 - function testInit() 62 - { 63 - $r = Request::init(); 64 - // Did we get a 'Request' object? 65 - $this->assertEquals('Httpful\Request', get_class($r)); 66 - } 67 - 68 - function testMethods() 69 - { 70 - $valid_methods = array('get', 'post', 'delete', 'put', 'options', 'head'); 71 - $url = 'http://example.com/'; 72 - foreach ($valid_methods as $method) { 73 - $r = call_user_func(array('Httpful\Request', $method), $url); 74 - $this->assertEquals('Httpful\Request', get_class($r)); 75 - $this->assertEquals(strtoupper($method), $r->method); 76 - } 77 - } 78 - 79 - function testDefaults() 80 - { 81 - // Our current defaults are as follows 82 - $r = Request::init(); 83 - $this->assertEquals(Http::GET, $r->method); 84 - $this->assertFalse($r->strict_ssl); 85 - } 86 - 87 - function testShortMime() 88 - { 89 - // Valid short ones 90 - $this->assertEquals(Mime::JSON, Mime::getFullMime('json')); 91 - $this->assertEquals(Mime::XML, Mime::getFullMime('xml')); 92 - $this->assertEquals(Mime::HTML, Mime::getFullMime('html')); 93 - $this->assertEquals(Mime::CSV, Mime::getFullMime('csv')); 94 - 95 - // Valid long ones 96 - $this->assertEquals(Mime::JSON, Mime::getFullMime(Mime::JSON)); 97 - $this->assertEquals(Mime::XML, Mime::getFullMime(Mime::XML)); 98 - $this->assertEquals(Mime::HTML, Mime::getFullMime(Mime::HTML)); 99 - $this->assertEquals(Mime::CSV, Mime::getFullMime(Mime::CSV)); 100 - 101 - // No false positives 102 - $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::HTML)); 103 - $this->assertNotEquals(Mime::JSON, Mime::getFullMime(Mime::XML)); 104 - $this->assertNotEquals(Mime::HTML, Mime::getFullMime(Mime::JSON)); 105 - $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::CSV)); 106 - } 107 - 108 - function testSettingStrictSsl() 109 - { 110 - $r = Request::init() 111 - ->withStrictSsl(); 112 - 113 - $this->assertTrue($r->strict_ssl); 114 - 115 - $r = Request::init() 116 - ->withoutStrictSsl(); 117 - 118 - $this->assertFalse($r->strict_ssl); 119 - } 120 - 121 - function testSendsAndExpectsType() 122 - { 123 - $r = Request::init() 124 - ->sendsAndExpectsType(Mime::JSON); 125 - $this->assertEquals(Mime::JSON, $r->expected_type); 126 - $this->assertEquals(Mime::JSON, $r->content_type); 127 - 128 - $r = Request::init() 129 - ->sendsAndExpectsType('html'); 130 - $this->assertEquals(Mime::HTML, $r->expected_type); 131 - $this->assertEquals(Mime::HTML, $r->content_type); 132 - 133 - $r = Request::init() 134 - ->sendsAndExpectsType('form'); 135 - $this->assertEquals(Mime::FORM, $r->expected_type); 136 - $this->assertEquals(Mime::FORM, $r->content_type); 137 - 138 - $r = Request::init() 139 - ->sendsAndExpectsType('application/x-www-form-urlencoded'); 140 - $this->assertEquals(Mime::FORM, $r->expected_type); 141 - $this->assertEquals(Mime::FORM, $r->content_type); 142 - 143 - $r = Request::init() 144 - ->sendsAndExpectsType(Mime::CSV); 145 - $this->assertEquals(Mime::CSV, $r->expected_type); 146 - $this->assertEquals(Mime::CSV, $r->content_type); 147 - } 148 - 149 - function testIni() 150 - { 151 - // Test setting defaults/templates 152 - 153 - // Create the template 154 - $template = Request::init() 155 - ->method(Http::POST) 156 - ->withStrictSsl() 157 - ->expectsType(Mime::HTML) 158 - ->sendsType(Mime::FORM); 159 - 160 - Request::ini($template); 161 - 162 - $r = Request::init(); 163 - 164 - $this->assertTrue($r->strict_ssl); 165 - $this->assertEquals(Http::POST, $r->method); 166 - $this->assertEquals(Mime::HTML, $r->expected_type); 167 - $this->assertEquals(Mime::FORM, $r->content_type); 168 - 169 - // Test the default accessor as well 170 - $this->assertTrue(Request::d('strict_ssl')); 171 - $this->assertEquals(Http::POST, Request::d('method')); 172 - $this->assertEquals(Mime::HTML, Request::d('expected_type')); 173 - $this->assertEquals(Mime::FORM, Request::d('content_type')); 174 - 175 - Request::resetIni(); 176 - } 177 - 178 - function testAccept() 179 - { 180 - $r = Request::get('http://example.com/') 181 - ->expectsType(Mime::JSON); 182 - 183 - $this->assertEquals(Mime::JSON, $r->expected_type); 184 - $r->_curlPrep(); 185 - $this->assertContains('application/json', $r->raw_headers); 186 - } 187 - 188 - function testCustomAccept() 189 - { 190 - $accept = 'application/api-1.0+json'; 191 - $r = Request::get('http://example.com/') 192 - ->addHeader('Accept', $accept); 193 - 194 - $r->_curlPrep(); 195 - $this->assertContains($accept, $r->raw_headers); 196 - $this->assertEquals($accept, $r->headers['Accept']); 197 - } 198 - 199 - function testUserAgent() 200 - { 201 - $r = Request::get('http://example.com/') 202 - ->withUserAgent('ACME/1.2.3'); 203 - 204 - $this->assertArrayHasKey('User-Agent', $r->headers); 205 - $r->_curlPrep(); 206 - $this->assertContains('User-Agent: ACME/1.2.3', $r->raw_headers); 207 - $this->assertNotContains('User-Agent: HttpFul/1.0', $r->raw_headers); 208 - 209 - $r = Request::get('http://example.com/') 210 - ->withUserAgent(''); 211 - 212 - $this->assertArrayHasKey('User-Agent', $r->headers); 213 - $r->_curlPrep(); 214 - $this->assertContains('User-Agent:', $r->raw_headers); 215 - $this->assertNotContains('User-Agent: HttpFul/1.0', $r->raw_headers); 216 - } 217 - 218 - function testAuthSetup() 219 - { 220 - $username = 'nathan'; 221 - $password = 'opensesame'; 222 - 223 - $r = Request::get('http://example.com/') 224 - ->authenticateWith($username, $password); 225 - 226 - $this->assertEquals($username, $r->username); 227 - $this->assertEquals($password, $r->password); 228 - $this->assertTrue($r->hasBasicAuth()); 229 - } 230 - 231 - function testDigestAuthSetup() 232 - { 233 - $username = 'nathan'; 234 - $password = 'opensesame'; 235 - 236 - $r = Request::get('http://example.com/') 237 - ->authenticateWithDigest($username, $password); 238 - 239 - $this->assertEquals($username, $r->username); 240 - $this->assertEquals($password, $r->password); 241 - $this->assertTrue($r->hasDigestAuth()); 242 - } 243 - 244 - function testJsonResponseParse() 245 - { 246 - $req = Request::init()->sendsAndExpects(Mime::JSON); 247 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); 248 - 249 - $this->assertEquals("value", $response->body->key); 250 - $this->assertEquals("value", $response->body->object->key); 251 - $this->assertInternalType('array', $response->body->array); 252 - $this->assertEquals(1, $response->body->array[0]); 253 - } 254 - 255 - function testXMLResponseParse() 256 - { 257 - $req = Request::init()->sendsAndExpects(Mime::XML); 258 - $response = new Response(self::SAMPLE_XML_RESPONSE, self::SAMPLE_XML_HEADER, $req); 259 - $sxe = $response->body; 260 - $this->assertEquals("object", gettype($sxe)); 261 - $this->assertEquals("SimpleXMLElement", get_class($sxe)); 262 - $bools = $sxe->xpath('/stdClass/boolProp'); 263 - list( , $bool ) = each($bools); 264 - $this->assertEquals("TRUE", (string) $bool); 265 - $ints = $sxe->xpath('/stdClass/arrayProp/array/k1/myClass/intProp'); 266 - list( , $int ) = each($ints); 267 - $this->assertEquals("2", (string) $int); 268 - $strings = $sxe->xpath('/stdClass/stringProp'); 269 - list( , $string ) = each($strings); 270 - $this->assertEquals("a string", (string) $string); 271 - } 272 - 273 - function testCsvResponseParse() 274 - { 275 - $req = Request::init()->sendsAndExpects(Mime::CSV); 276 - $response = new Response(self::SAMPLE_CSV_RESPONSE, self::SAMPLE_CSV_HEADER, $req); 277 - 278 - $this->assertEquals("Key1", $response->body[0][0]); 279 - $this->assertEquals("Value1", $response->body[1][0]); 280 - $this->assertInternalType('string', $response->body[2][0]); 281 - $this->assertEquals("40.0", $response->body[2][0]); 282 - } 283 - 284 - function testParsingContentTypeCharset() 285 - { 286 - $req = Request::init()->sendsAndExpects(Mime::JSON); 287 - // $response = new Response(SAMPLE_JSON_RESPONSE, "", $req); 288 - // // Check default content type of iso-8859-1 289 - $response = new Response(self::SAMPLE_JSON_RESPONSE, "HTTP/1.1 200 OK 290 - Content-Type: text/plain; charset=utf-8\r\n", $req); 291 - $this->assertInstanceOf('Httpful\Response\Headers', $response->headers); 292 - $this->assertEquals($response->headers['Content-Type'], 'text/plain; charset=utf-8'); 293 - $this->assertEquals($response->content_type, 'text/plain'); 294 - $this->assertEquals($response->charset, 'utf-8'); 295 - } 296 - 297 - function testEmptyResponseParse() 298 - { 299 - $req = Request::init()->sendsAndExpects(Mime::JSON); 300 - $response = new Response("", self::SAMPLE_JSON_HEADER, $req); 301 - $this->assertEquals(null, $response->body); 302 - 303 - $reqXml = Request::init()->sendsAndExpects(Mime::XML); 304 - $responseXml = new Response("", self::SAMPLE_XML_HEADER, $reqXml); 305 - $this->assertEquals(null, $responseXml->body); 306 - } 307 - 308 - function testNoAutoParse() 309 - { 310 - $req = Request::init()->sendsAndExpects(Mime::JSON)->withoutAutoParsing(); 311 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); 312 - $this->assertInternalType('string', $response->body); 313 - $req = Request::init()->sendsAndExpects(Mime::JSON)->withAutoParsing(); 314 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); 315 - $this->assertInternalType('object', $response->body); 316 - } 317 - 318 - function testParseHeaders() 319 - { 320 - $req = Request::init()->sendsAndExpects(Mime::JSON); 321 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); 322 - $this->assertEquals('application/json', $response->headers['Content-Type']); 323 - } 324 - 325 - function testRawHeaders() 326 - { 327 - $req = Request::init()->sendsAndExpects(Mime::JSON); 328 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); 329 - $this->assertContains('Content-Type: application/json', $response->raw_headers); 330 - } 331 - 332 - function testHasErrors() 333 - { 334 - $req = Request::init()->sendsAndExpects(Mime::JSON); 335 - $response = new Response('', "HTTP/1.1 100 Continue\r\n", $req); 336 - $this->assertFalse($response->hasErrors()); 337 - $response = new Response('', "HTTP/1.1 200 OK\r\n", $req); 338 - $this->assertFalse($response->hasErrors()); 339 - $response = new Response('', "HTTP/1.1 300 Multiple Choices\r\n", $req); 340 - $this->assertFalse($response->hasErrors()); 341 - $response = new Response('', "HTTP/1.1 400 Bad Request\r\n", $req); 342 - $this->assertTrue($response->hasErrors()); 343 - $response = new Response('', "HTTP/1.1 500 Internal Server Error\r\n", $req); 344 - $this->assertTrue($response->hasErrors()); 345 - } 346 - 347 - function test_parseCode() 348 - { 349 - $req = Request::init()->sendsAndExpects(Mime::JSON); 350 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); 351 - $code = $response->_parseCode("HTTP/1.1 406 Not Acceptable\r\n"); 352 - $this->assertEquals(406, $code); 353 - } 354 - 355 - function testToString() 356 - { 357 - $req = Request::init()->sendsAndExpects(Mime::JSON); 358 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); 359 - $this->assertEquals(self::SAMPLE_JSON_RESPONSE, (string)$response); 360 - } 361 - 362 - function test_parseHeaders() 363 - { 364 - $parse_headers = Response\Headers::fromString(self::SAMPLE_JSON_HEADER); 365 - $this->assertCount(3, $parse_headers); 366 - $this->assertEquals('application/json', $parse_headers['Content-Type']); 367 - $this->assertTrue(isset($parse_headers['Connection'])); 368 - } 369 - 370 - function testMultiHeaders() 371 - { 372 - $req = Request::init(); 373 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_MULTI_HEADER, $req); 374 - $parse_headers = $response->_parseHeaders(self::SAMPLE_MULTI_HEADER); 375 - $this->assertEquals('Value1,Value2', $parse_headers['X-My-Header']); 376 - } 377 - 378 - function testDetectContentType() 379 - { 380 - $req = Request::init(); 381 - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); 382 - $this->assertEquals('application/json', $response->headers['Content-Type']); 383 - } 384 - 385 - function testMissingBodyContentType() 386 - { 387 - $body = 'A string'; 388 - $request = Request::post(HttpfulTest::TEST_URL, $body)->_curlPrep(); 389 - $this->assertEquals($body, $request->serialized_payload); 390 - } 391 - 392 - function testParentType() 393 - { 394 - // Parent type 395 - $request = Request::init()->sendsAndExpects(Mime::XML); 396 - $response = new Response('<xml><name>Nathan</name></xml>', self::SAMPLE_VENDOR_HEADER, $request); 397 - 398 - $this->assertEquals("application/xml", $response->parent_type); 399 - $this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type); 400 - $this->assertTrue($response->is_mime_vendor_specific); 401 - 402 - // Make sure we still parsed as if it were plain old XML 403 - $this->assertEquals("Nathan", $response->body->name->__toString()); 404 - } 405 - 406 - function testMissingContentType() 407 - { 408 - // Parent type 409 - $request = Request::init()->sendsAndExpects(Mime::XML); 410 - $response = new Response('<xml><name>Nathan</name></xml>', 411 - "HTTP/1.1 200 OK 412 - Connection: keep-alive 413 - Transfer-Encoding: chunked\r\n", $request); 414 - 415 - $this->assertEquals("", $response->content_type); 416 - } 417 - 418 - function testCustomMimeRegistering() 419 - { 420 - // Register new mime type handler for "application/vnd.nategood.message+xml" 421 - Httpful::register(self::SAMPLE_VENDOR_TYPE, new DemoMimeHandler()); 422 - 423 - $this->assertTrue(Httpful::hasParserRegistered(self::SAMPLE_VENDOR_TYPE)); 424 - 425 - $request = Request::init(); 426 - $response = new Response('<xml><name>Nathan</name></xml>', self::SAMPLE_VENDOR_HEADER, $request); 427 - 428 - $this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type); 429 - $this->assertEquals('custom parse', $response->body); 430 - } 431 - 432 - public function testShorthandMimeDefinition() 433 - { 434 - $r = Request::init()->expects('json'); 435 - $this->assertEquals(Mime::JSON, $r->expected_type); 436 - 437 - $r = Request::init()->expectsJson(); 438 - $this->assertEquals(Mime::JSON, $r->expected_type); 439 - } 440 - 441 - public function testOverrideXmlHandler() 442 - { 443 - // Lazy test... 444 - $prev = \Httpful\Httpful::get(\Httpful\Mime::XML); 445 - $this->assertEquals($prev, new \Httpful\Handlers\XmlHandler()); 446 - $conf = array('namespace' => 'http://example.com'); 447 - \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); 448 - $new = \Httpful\Httpful::get(\Httpful\Mime::XML); 449 - $this->assertNotEquals($prev, $new); 450 - } 451 - } 452 - 453 - class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter { 454 - public function parse($body) { 455 - return 'custom parse'; 456 - } 457 - } 458 -
-9
externals/httpful/tests/phpunit.xml
··· 1 - <phpunit> 2 - <testsuite name="Httpful"> 3 - <directory>.</directory> 4 - </testsuite> 5 - <logging> 6 - <log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/> 7 - </logging> 8 - </phpunit> 9 -
-12
externals/restful/.gitignore
··· 1 - # composer 2 - .buildpath 3 - composer.lock 4 - composer.phar 5 - vendor 6 - 7 - # phar 8 - *.phar 9 - 10 - # eclipse-pdt 11 - .settings 12 - .project
-8
externals/restful/.travis.yml
··· 1 - language: php 2 - before_script: 3 - - curl -s http://getcomposer.org/installer | php 4 - - php composer.phar install --prefer-source 5 - script: phpunit --bootstrap vendor/autoload.php tests/ 6 - php: 7 - - 5.3 8 - - 5.4
-22
externals/restful/LICENSE
··· 1 - Copyright (c) 2012 Noone 2 - 3 - MIT License 4 - 5 - Permission is hereby granted, free of charge, to any person obtaining 6 - a copy of this software and associated documentation files (the 7 - "Software"), to deal in the Software without restriction, including 8 - without limitation the rights to use, copy, modify, merge, publish, 9 - distribute, sublicense, and/or sell copies of the Software, and to 10 - permit persons to whom the Software is furnished to do so, subject to 11 - the following conditions: 12 - 13 - The above copyright notice and this permission notice shall be 14 - included in all copies or substantial portions of the Software. 15 - 16 - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-111
externals/restful/README.md
··· 1 - # RESTful 2 - 3 - Library for writing RESTful PHP clients. 4 - 5 - [![Build Status](https://secure.travis-ci.org/bninja/restful.png)](http://travis-ci.org/bninja/restful) 6 - 7 - The design of this library was heavily influenced by [Httpful](https://github.com/nategood/httpful). 8 - 9 - ## Requirements 10 - 11 - - [PHP](http://www.php.net) >= 5.3 **with** [cURL](http://www.php.net/manual/en/curl.installation.php) 12 - - [Httpful](https://github.com/nategood/httpful) >= 0.1 13 - 14 - ## Issues 15 - 16 - Please use appropriately tagged github [issues](https://github.com/bninja/restful/issues) to request features or report bugs. 17 - 18 - ## Installation 19 - 20 - You can install using [composer](#composer), a [phar](#phar) package or from [source](#source). Note that RESTful is [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) compliant: 21 - 22 - ### Composer 23 - 24 - If you don't have Composer [install](http://getcomposer.org/doc/00-intro.md#installation) it: 25 - 26 - $ curl -s https://getcomposer.org/installer | php 27 - 28 - Add this to your `composer.json`: 29 - 30 - { 31 - "require": { 32 - "bninja/restful": "*" 33 - } 34 - } 35 - 36 - Refresh your dependencies: 37 - 38 - $ php composer.phar update 39 - 40 - 41 - Then make sure to `require` the autoloader and initialize both: 42 - 43 - <?php 44 - require(__DIR__ . '/vendor/autoload.php'); 45 - 46 - Httpful\Bootstrap::init(); 47 - RESTful\Bootstrap::init(); 48 - ... 49 - 50 - ### Phar 51 - 52 - Download an Httpful [phar](http://php.net/manual/en/book.phar.php) file, which are all [here](https://github.com/nategood/httpful/downloads): 53 - 54 - $ curl -s -L -o httpful.phar https://github.com/downloads/nategood/httpful/httpful.phar 55 - 56 - Download a RESTful [phar](http://php.net/manual/en/book.phar.php) file, which are all [here](https://github.com/bninja/restful/downloads): 57 - 58 - $ curl -s -L -o restful.phar https://github.com/bninja/restful/downloads/restful-{VERSION}.phar 59 - 60 - And then `include` both: 61 - 62 - <?php 63 - include(__DIR__ . '/httpful.phar'); 64 - include(__DIR__ . '/restful.phar'); 65 - ... 66 - 67 - ### Source 68 - 69 - Download [Httpful](https://github.com/nategood/httpful) source: 70 - 71 - $ curl -s -L -o httpful.zip https://github.com/nategood/httpful/zipball/master; 72 - $ unzip httpful.zip; mv nategood-httpful* httpful; rm httpful.zip 73 - 74 - Download the RESTful source: 75 - 76 - $ curl -s -L -o restful.zip https://github.com/bninja/restful/zipball/master 77 - $ unzip restful.zip; mv bninja-restful-* restful; rm restful.zip 78 - 79 - And then `require` both bootstrap files: 80 - 81 - <?php 82 - require(__DIR__ . "/httpful/bootstrap.php") 83 - require(__DIR__ . "/restful/bootstrap.php") 84 - ... 85 - 86 - ## Usage 87 - 88 - TODO 89 - 90 - ## Testing 91 - 92 - $ phpunit --bootstrap vendor/autoload.php tests/ 93 - 94 - ## Publishing 95 - 96 - 1. Ensure that **all** [tests](#testing) pass 97 - 2. Increment minor `VERSION` in `src/RESTful/Settings` and `composer.json` (`git commit -am 'v{VERSION} release'`) 98 - 3. Tag it (`git tag -a v{VERSION} -m 'v{VERSION} release'`) 99 - 4. Push the tag (`git push --tag`) 100 - 5. [Packagist](http://packagist.org/packages/bninja/restful) will see the new tag and take it from there 101 - 6. Build (`build-phar`) and upload a [phar](http://php.net/manual/en/book.phar.php) file 102 - 103 - ## Contributing 104 - 105 - 1. Fork it 106 - 2. Create your feature branch (`git checkout -b my-new-feature`) 107 - 3. Write your code **and [tests](#testing)** 108 - 4. Ensure all tests still pass (`phpunit --bootstrap vendor/autoload.php tests/`) 109 - 5. Commit your changes (`git commit -am 'Add some feature'`) 110 - 6. Push to the branch (`git push origin my-new-feature`) 111 - 7. Create new pull request
-4
externals/restful/bootstrap.php
··· 1 - <?php 2 - 3 - require(__DIR__ . '/src/RESTful/Bootstrap.php'); 4 - \RESTful\Bootstrap::init();
-36
externals/restful/build-phar
··· 1 - #!/usr/bin/php 2 - <?php 3 - include('src/RESTful/Settings.php'); 4 - 5 - function exit_unless($condition, $msg = null) { 6 - if ($condition) 7 - return; 8 - echo "[FAIL] $msg"; 9 - exit(1); 10 - } 11 - 12 - echo "Building Phar... "; 13 - $base_dir = dirname(__FILE__); 14 - $source_dir = $base_dir . '/src/RESTful/'; 15 - $phar_name = 'restful.phar'; 16 - $phar_path = $base_dir . '/' . $phar_name; 17 - $phar = new Phar($phar_path, 0, $phar_name); 18 - $stub = <<<HEREDOC 19 - <?php 20 - // Phar Stub File 21 - Phar::mapPhar('restful.phar'); 22 - include('phar://restful.phar/RESTful/Bootstrap.php'); 23 - \RESTful\Bootstrap::pharInit(); 24 - 25 - __HALT_COMPILER(); 26 - HEREDOC; 27 - $phar->setStub($stub); 28 - exit_unless($phar, "Unable to create a phar. Make sure you have phar.readonly=0 set in your ini file."); 29 - $phar->buildFromDirectory(dirname($source_dir)); 30 - echo "[ OK ]\n"; 31 - 32 - echo "Renaming Phar... "; 33 - $phar_versioned_name = 'restful-' . \RESTful\Settings::VERSION . '.phar'; 34 - $phar_versioned_path = $base_dir . '/' . $phar_versioned_name; 35 - rename($phar_path, $phar_versioned_path); 36 - echo "[ OK ]\n";
-18
externals/restful/composer.json
··· 1 - { 2 - "name": "bninja/restful", 3 - "description": "Library for writing RESTful PHP clients.", 4 - "homepage": "http://github.com/bninja/restful", 5 - "license": "MIT", 6 - "keywords": ["http", "api", "client", "rest"], 7 - "version": "0.1.7", 8 - "authors": [ 9 - ], 10 - "require": { 11 - "nategood/httpful": "*" 12 - }, 13 - "autoload": { 14 - "psr-0": { 15 - "RESTful": "src/" 16 - } 17 - } 18 - }
-44
externals/restful/src/RESTful/Bootstrap.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - /** 6 - * Bootstrapper for RESTful does autoloading. 7 - */ 8 - class Bootstrap 9 - { 10 - const DIR_SEPARATOR = DIRECTORY_SEPARATOR; 11 - const NAMESPACE_SEPARATOR = '\\'; 12 - 13 - public static $initialized = false; 14 - 15 - 16 - public static function init() 17 - { 18 - spl_autoload_register(array('\RESTful\Bootstrap', 'autoload')); 19 - } 20 - 21 - public static function autoload($classname) 22 - { 23 - self::_autoload(dirname(dirname(__FILE__)), $classname); 24 - } 25 - 26 - public static function pharInit() 27 - { 28 - spl_autoload_register(array('\RESTful\Bootstrap', 'pharAutoload')); 29 - } 30 - 31 - public static function pharAutoload($classname) 32 - { 33 - self::_autoload('phar://restful.phar', $classname); 34 - } 35 - 36 - private static function _autoload($base, $classname) 37 - { 38 - $parts = explode(self::NAMESPACE_SEPARATOR, $classname); 39 - $path = $base . self::DIR_SEPARATOR . implode(self::DIR_SEPARATOR, $parts) . '.php'; 40 - if (file_exists($path)) { 41 - require_once($path); 42 - } 43 - } 44 - }
-78
externals/restful/src/RESTful/Client.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - use RESTful\Exceptions\HTTPError; 6 - use RESTful\Settings; 7 - 8 - class Client 9 - { 10 - public function __construct($settings_class, $request_class = null, $convert_error = null) 11 - { 12 - $this->request_class = $request_class == null ? '\Httpful\Request' : $request_class; 13 - $this->settings_class = $settings_class; 14 - $this->convert_error = $convert_error; 15 - } 16 - 17 - public function get($uri) 18 - { 19 - $settings_class = $this->settings_class; 20 - $url = $settings_class::$url_root . $uri; 21 - $request_class = $this->request_class; 22 - $request = $request_class::get($url); 23 - 24 - return $this->_op($request); 25 - } 26 - 27 - public function post($uri, $payload) 28 - { 29 - $settings_class = $this->settings_class; 30 - $url = $settings_class::$url_root . $uri; 31 - $request_class = $this->request_class; 32 - $request = $request_class::post($url, $payload, 'json'); 33 - 34 - return $this->_op($request); 35 - } 36 - 37 - public function put($uri, $payload) 38 - { 39 - $settings_class = $this->settings_class; 40 - $url = $settings_class::$url_root . $uri; 41 - $request_class = $this->request_class; 42 - $request = $request_class::put($url, $payload, 'json'); 43 - 44 - return $this->_op($request); 45 - } 46 - 47 - public function delete($uri) 48 - { 49 - $settings_class = $this->settings_class; 50 - $url = $settings_class::$url_root . $uri; 51 - $request_class = $this->request_class; 52 - $request = $request_class::delete($url); 53 - 54 - return $this->_op($request); 55 - } 56 - 57 - private function _op($request) 58 - { 59 - $settings_class = $this->settings_class; 60 - $user_agent = $settings_class::$agent . '/' . $settings_class::$version; 61 - $request->headers['User-Agent'] = $user_agent; 62 - if ($settings_class::$api_key != null) { 63 - $request = $request->authenticateWith($settings_class::$api_key, ''); 64 - } 65 - $request->expects('json'); 66 - $response = $request->sendIt(); 67 - if ($response->hasErrors() || $response->code == 300) { 68 - if ($this->convert_error != null) { 69 - $error = call_user_func($this->convert_error, $response); 70 - } else { 71 - $error = new HTTPError($response); 72 - } 73 - throw $error; 74 - } 75 - 76 - return $response; 77 - } 78 - }
-49
externals/restful/src/RESTful/Collection.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class Collection extends Itemization 6 - { 7 - public function __construct($resource, $uri, $data = null) 8 - { 9 - parent::__construct($resource, $uri, $data); 10 - $this->_parseUri(); 11 - } 12 - 13 - private function _parseUri() 14 - { 15 - $parsed = parse_url($this->uri); 16 - $this->_uri = $parsed['path']; 17 - if (array_key_exists('query', $parsed)) { 18 - foreach (explode('&', $parsed['query']) as $param) { 19 - $param = explode('=', $param); 20 - $key = urldecode($param[0]); 21 - $val = (count($param) == 1) ? null : urldecode($param[1]); 22 - 23 - // size 24 - if ($key == 'limit') { 25 - $this->_size = $val; 26 - } 27 - } 28 - } 29 - } 30 - 31 - public function create($payload) 32 - { 33 - $class = $this->resource; 34 - $client = $class::getClient(); 35 - $response = $client->post($this->uri, $payload); 36 - 37 - return new $this->resource($response->body); 38 - } 39 - 40 - public function query() 41 - { 42 - return new Query($this->resource, $this->uri); 43 - } 44 - 45 - public function paginate() 46 - { 47 - return new Pagination($this->resource, $this->uri); 48 - } 49 - }
-10
externals/restful/src/RESTful/Exceptions/Base.php
··· 1 - <?php 2 - 3 - namespace RESTful\Exceptions; 4 - 5 - /** 6 - * Base class for all RESTful\Exceptions. 7 - */ 8 - class Base extends \Exception 9 - { 10 - }
-28
externals/restful/src/RESTful/Exceptions/HTTPError.php
··· 1 - <?php 2 - 3 - namespace RESTful\Exceptions; 4 - 5 - /** 6 - * Indicates an HTTP level error has occurred. The underlying HTTP response is 7 - * stored as response member. The response payload fields if any are stored as 8 - * members of the same name. 9 - * 10 - * @see \Httpful\Response 11 - */ 12 - class HTTPError extends Base 13 - { 14 - public $response; 15 - 16 - public function __construct($response) 17 - { 18 - $this->response = $response; 19 - $this->_objectify($this->response->body); 20 - } 21 - 22 - protected function _objectify($fields) 23 - { 24 - foreach ($fields as $key => $val) { 25 - $this->$key = $val; 26 - } 27 - } 28 - }
-11
externals/restful/src/RESTful/Exceptions/MultipleResultsFound.php
··· 1 - <?php 2 - 3 - namespace RESTful\Exceptions; 4 - 5 - /** 6 - * Indicates that a query unexpectedly returned multiple results when at most 7 - * one was expected. 8 - */ 9 - class MultipleResultsFound extends Base 10 - { 11 - }
-10
externals/restful/src/RESTful/Exceptions/NoResultFound.php
··· 1 - <?php 2 - 3 - namespace RESTful\Exceptions; 4 - 5 - /** 6 - * Indicates that a query unexpectedly returned no results. 7 - */ 8 - class NoResultFound extends Base 9 - { 10 - }
-85
externals/restful/src/RESTful/Field.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class Field 6 - { 7 - public $name; 8 - 9 - public function __construct($name) 10 - { 11 - $this->name = $name; 12 - } 13 - 14 - public function __get($name) 15 - { 16 - return new Field($this->name . '.' . $name); 17 - } 18 - 19 - public function in($vals) 20 - { 21 - return new FilterExpression($this->name, 'in', $vals, '!in'); 22 - } 23 - 24 - public function startswith($prefix) 25 - { 26 - if (!is_string($prefix)) { 27 - throw new \InvalidArgumentException('"startswith" prefix must be a string'); 28 - } 29 - 30 - return new FilterExpression($this->name, 'contains', $prefix); 31 - } 32 - 33 - public function endswith($suffix) 34 - { 35 - if (!is_string($suffix)) { 36 - throw new \InvalidArgumentException('"endswith" suffix must be a string'); 37 - } 38 - 39 - return new FilterExpression($this->name, 'contains', $suffix); 40 - } 41 - 42 - public function contains($fragment) 43 - { 44 - if (!is_string($fragment)) { 45 - throw new \InvalidArgumentException('"contains" fragment must be a string'); 46 - } 47 - 48 - return new FilterExpression($this->name, 'contains', $fragment, '!contains'); 49 - } 50 - 51 - public function eq($val) 52 - { 53 - return new FilterExpression($this->name, '=', $val, '!eq'); 54 - } 55 - 56 - public function lt($val) 57 - { 58 - return new FilterExpression($this->name, '<', $val, '>='); 59 - } 60 - 61 - public function lte($val) 62 - { 63 - return new FilterExpression($this->name, '<=', $val, '>'); 64 - } 65 - 66 - public function gt($val) 67 - { 68 - return new FilterExpression($this->name, '>', $val, '<='); 69 - } 70 - 71 - public function gte($val) 72 - { 73 - return new FilterExpression($this->name, '>=', $val, '<'); 74 - } 75 - 76 - public function asc() 77 - { 78 - return new SortExpression($this->name, true); 79 - } 80 - 81 - public function desc() 82 - { 83 - return new SortExpression($this->name, false); 84 - } 85 - }
-11
externals/restful/src/RESTful/Fields.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class Fields 6 - { 7 - public function __get($name) 8 - { 9 - return new Field($name); 10 - } 11 - }
-31
externals/restful/src/RESTful/FilterExpression.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class FilterExpression 6 - { 7 - public $field, 8 - $op, 9 - $val, 10 - $not_op; 11 - 12 - public function __construct($field, $op, $val, $not_op = null) 13 - { 14 - $this->field = $field; 15 - $this->op = $op; 16 - $this->val = $val; 17 - $this->not_op = $not_op; 18 - } 19 - 20 - public function not() 21 - { 22 - if (null === $this->not_op) { 23 - throw new \LogicException(sprintf('Filter cannot be inverted')); 24 - } 25 - $temp = $this->op; 26 - $this->op = $this->not_op; 27 - $this->not_op = $temp; 28 - 29 - return $this; 30 - } 31 - }
-99
externals/restful/src/RESTful/Itemization.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class Itemization implements \IteratorAggregate, \ArrayAccess 6 - { 7 - public $resource, 8 - $uri; 9 - 10 - protected $_page, 11 - $_offset = 0, 12 - $_size = 25; 13 - 14 - public function __construct($resource, $uri, $data = null) 15 - { 16 - $this->resource = $resource; 17 - $this->uri = $uri; 18 - if ($data != null) { 19 - $this->_page = new Page($resource, $uri, $data); 20 - } else { 21 - $this->_page = null; 22 - } 23 - } 24 - 25 - protected function _getPage($offset = null) 26 - { 27 - if ($this->_page == null) { 28 - $this->_offset = ($offset == null) ? 0 : $offset * $this->_size; 29 - $uri = $this->_buildUri(); 30 - $this->_page = new Page($this->resource, $uri); 31 - } elseif ($offset != null) { 32 - $offset = $offset * $this->_size; 33 - if ($offset != $this->_offset) { 34 - $this->_offset = $offset; 35 - $uri = $this->_buildUri(); 36 - $this->_page = new Page($this->resource, $uri); 37 - } 38 - } 39 - 40 - return $this->_page; 41 - } 42 - 43 - protected function _getItem($offset) 44 - { 45 - $page_offset = floor($offset / $this->_size); 46 - $page = $this->_getPage($page_offset); 47 - 48 - return $page->items[$offset - $page->offset]; 49 - } 50 - 51 - public function total() 52 - { 53 - return $this->_getPage()->total; 54 - } 55 - 56 - protected function _buildUri($offset = null) 57 - { 58 - # TODO: hacky but works for now 59 - $offset = ($offset == null) ? $this->_offset : $offset; 60 - if (strpos($this->uri, '?') === false) { 61 - $uri = $this->uri . '?'; 62 - } else { 63 - $uri = $this->uri . '&'; 64 - } 65 - $uri = $uri . 'offset=' . strval($offset); 66 - 67 - return $uri; 68 - } 69 - 70 - // IteratorAggregate 71 - public function getIterator() 72 - { 73 - $uri = $this->_buildUri($offset = 0); 74 - $uri = $this->_buildUri($offset = 0); 75 - 76 - return new ItemizationIterator($this->resource, $uri); 77 - } 78 - 79 - // ArrayAccess 80 - public function offsetSet($offset, $value) 81 - { 82 - throw new \BadMethodCallException(get_class($this) . ' array access is read-only'); 83 - } 84 - 85 - public function offsetExists($offset) 86 - { 87 - return (0 <= $offset && $offset < $this->total()); 88 - } 89 - 90 - public function offsetUnset($offset) 91 - { 92 - throw new \BadMethodCallException(get_class($this) . ' array access is read-only'); 93 - } 94 - 95 - public function offsetGet($offset) 96 - { 97 - return $this->_getItem($offset); 98 - } 99 - }
-45
externals/restful/src/RESTful/ItemizationIterator.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class ItemizationIterator implements \Iterator 6 - { 7 - protected $_page, 8 - $_offset = 0; 9 - 10 - public function __construct($resource, $uri, $data = null) 11 - { 12 - $this->_page = new Page($resource, $uri, $data); 13 - } 14 - 15 - // Iterator 16 - public function current() 17 - { 18 - return $this->_page->items[$this->_offset]; 19 - } 20 - 21 - public function key() 22 - { 23 - return $this->_page->offset + $this->_offset; 24 - } 25 - 26 - public function next() 27 - { 28 - $this->_offset += 1; 29 - if ($this->_offset >= count($this->_page->items)) { 30 - $this->_offset = 0; 31 - $this->_page = $this->_page->next(); 32 - } 33 - } 34 - 35 - public function rewind() 36 - { 37 - $this->_page = $this->_page->first(); 38 - $this->_offset = 0; 39 - } 40 - 41 - public function valid() 42 - { 43 - return ($this->_page != null && $this->_offset < count($this->_page->items)); 44 - } 45 - }
-72
externals/restful/src/RESTful/Page.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class Page 6 - { 7 - public $resource, 8 - $total, 9 - $items, 10 - $offset, 11 - $limit; 12 - 13 - private $_first_uri, 14 - $_previous_uri, 15 - $_next_uri, 16 - $_last_uri; 17 - 18 - public function __construct($resource, $uri, $data = null) 19 - { 20 - $this->resource = $resource; 21 - if ($data == null) { 22 - $client = $resource::getClient(); 23 - $data = $client->get($uri)->body; 24 - } 25 - $this->total = $data->total; 26 - $this->items = array_map( 27 - function ($x) use ($resource) { 28 - return new $resource($x); 29 - }, 30 - $data->items); 31 - $this->offset = $data->offset; 32 - $this->limit = $data->limit; 33 - $this->_first_uri = property_exists($data, 'first_uri') ? $data->first_uri : null; 34 - $this->_previous_uri = property_exists($data, 'previous_uri') ? $data->previous_uri : null; 35 - $this->_next_uri = property_exists($data, 'next_uri') ? $data->next_uri : null; 36 - $this->_last_uri = property_exists($data, 'last_uri') ? $data->last_uri : null; 37 - } 38 - 39 - public function first() 40 - { 41 - return new Page($this->resource, $this->_first_uri); 42 - } 43 - 44 - public function next() 45 - { 46 - if (!$this->hasNext()) { 47 - return null; 48 - } 49 - 50 - return new Page($this->resource, $this->_next_uri); 51 - } 52 - 53 - public function hasNext() 54 - { 55 - return $this->_next_uri != null; 56 - } 57 - 58 - public function previous() 59 - { 60 - return new Page($this->resource, $this->_previous_uri); 61 - } 62 - 63 - public function hasPrevious() 64 - { 65 - return $this->_previous_uri != null; 66 - } 67 - 68 - public function last() 69 - { 70 - return new Page($this->resource, $this->_last_uri); 71 - } 72 - }
-90
externals/restful/src/RESTful/Pagination.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class Pagination implements \IteratorAggregate, \ArrayAccess 6 - { 7 - public $resource, 8 - $uri; 9 - 10 - protected $_page, 11 - $_offset = 0, 12 - $_size = 25; 13 - 14 - public function __construct($resource, $uri, $data = null) 15 - { 16 - $this->resource = $resource; 17 - $this->uri = $uri; 18 - if ($data != null) { 19 - $this->_page = new Page($resource, $uri, $data); 20 - } else { 21 - $this->_page = null; 22 - } 23 - } 24 - 25 - protected function _getPage($offset = null) 26 - { 27 - if ($this->_page == null) { 28 - $this->_offset = ($offset == null) ? 0 : $offset * $this->_size; 29 - $uri = $this->_buildUri(); 30 - $this->_page = new Page($this->resource, $uri); 31 - } elseif ($offset != null) { 32 - $offset = $offset * $this->_size; 33 - if ($offset != $this->_offset) { 34 - $this->_offset = $offset; 35 - $uri = $this->_buildUri(); 36 - $this->_page = new Page($this->resource, $uri); 37 - } 38 - } 39 - 40 - return $this->_page; 41 - } 42 - 43 - public function total() 44 - { 45 - return floor($this->_getPage()->total / $this->_size); 46 - } 47 - 48 - protected function _buildUri($offset = null) 49 - { 50 - # TODO: hacky but works for now 51 - $offset = ($offset == null) ? $this->_offset : $offset; 52 - if (strpos($this->uri, '?') === false) { 53 - $uri = $this->uri . '?'; 54 - } else { 55 - $uri = $this->uri . '&'; 56 - } 57 - $uri = $uri . 'offset=' . strval($offset); 58 - 59 - return $uri; 60 - } 61 - 62 - // IteratorAggregate 63 - public function getIterator() 64 - { 65 - $uri = $this->_buildUri($offset = 0); 66 - 67 - return new PaginationIterator($this->resource, $uri); 68 - } 69 - 70 - // ArrayAccess 71 - public function offsetSet($offset, $value) 72 - { 73 - throw new \BadMethodCallException(get_class($this) . ' array access is read-only'); 74 - } 75 - 76 - public function offsetExists($offset) 77 - { 78 - return (0 <= $offset && $offset < $this->total()); 79 - } 80 - 81 - public function offsetUnset($offset) 82 - { 83 - throw new \BadMethodCallException(get_class($this) . ' array access is read-only'); 84 - } 85 - 86 - public function offsetGet($offset) 87 - { 88 - return $this->_getPage($offset); 89 - } 90 - }
-37
externals/restful/src/RESTful/PaginationIterator.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class PaginationIterator implements \Iterator 6 - { 7 - public function __construct($resource, $uri, $data = null) 8 - { 9 - $this->_page = new Page($resource, $uri, $data); 10 - } 11 - 12 - // Iterator 13 - public function current() 14 - { 15 - return $this->_page; 16 - } 17 - 18 - public function key() 19 - { 20 - return $this->_page->index; 21 - } 22 - 23 - public function next() 24 - { 25 - $this->_page = $this->_page->next(); 26 - } 27 - 28 - public function rewind() 29 - { 30 - $this->_page = $this->_page->first(); 31 - } 32 - 33 - public function valid() 34 - { 35 - return $this->_page != null; 36 - } 37 - }
-161
externals/restful/src/RESTful/Query.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - use RESTful\Exceptions\NoResultFound; 6 - use RESTful\Exceptions\MultipleResultsFound; 7 - 8 - class Query extends Itemization 9 - { 10 - public $filters = array(), 11 - $sorts = array(), 12 - $size; 13 - 14 - public function __construct($resource, $uri) 15 - { 16 - parent::__construct($resource, $uri); 17 - $this->size = $this->_size; 18 - $this->_parseUri($uri); 19 - } 20 - 21 - private function _parseUri($uri) 22 - { 23 - $parsed = parse_url($uri); 24 - $this->uri = $parsed['path']; 25 - if (array_key_exists('query', $parsed)) { 26 - foreach (explode('&', $parsed['query']) as $param) { 27 - $param = explode('=', $param); 28 - $key = urldecode($param[0]); 29 - $val = (count($param) == 1) ? null : urldecode($param[1]); 30 - 31 - // limit 32 - if ($key == 'limit') { 33 - $this->size = $this->_size = $val; 34 - } // sorts 35 - else if ($key == 'sort') { 36 - array_push($this->sorts, $val); 37 - } // everything else 38 - else { 39 - if (!array_key_exists($key, $this->filters)) { 40 - $this->filters[$key] = array(); 41 - } 42 - if (!is_array($val)) { 43 - $val = array($val); 44 - } 45 - $this->filters[$key] = array_merge($this->filters[$key], $val); 46 - } 47 - } 48 - } 49 - } 50 - 51 - protected function _buildUri($offset = null) 52 - { 53 - // params 54 - $params = array_merge( 55 - $this->filters, 56 - array( 57 - 'sort' => $this->sorts, 58 - 'limit' => $this->_size, 59 - 'offset' => ($offset == null) ? $this->_offset : $offset 60 - ) 61 - ); 62 - $getSingle = function ($v) { 63 - if (is_array($v) && count($v) == 1) 64 - return $v[0]; 65 - return $v; 66 - }; 67 - $params = array_map($getSingle, $params); 68 - 69 - // url encode params 70 - // NOTE: http://stackoverflow.com/a/8171667/1339571 71 - $qs = http_build_query($params); 72 - $qs = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $qs); 73 - 74 - return $this->uri . '?' . $qs; 75 - } 76 - 77 - private function _reset() 78 - { 79 - $this->_page = null; 80 - } 81 - 82 - public function filter($expression) 83 - { 84 - if ($expression->op == '=') { 85 - $field = $expression->field; 86 - } else { 87 - $field = $expression->field . '[' . $expression->op . ']'; 88 - } 89 - if (is_array($expression->val)) { 90 - $val = implode(',', $expression->val); 91 - } else { 92 - $val = $expression->val; 93 - } 94 - if (!array_key_exists($field, $this->filters)) { 95 - $this->filters[$field] = array(); 96 - } 97 - array_push($this->filters[$field], $val); 98 - $this->_reset(); 99 - 100 - return $this; 101 - } 102 - 103 - public function sort($expression) 104 - { 105 - $dir = $expression->ascending ? 'asc' : 'desc'; 106 - array_push($this->sorts, $expression->field . ',' . $dir); 107 - $this->_reset(); 108 - 109 - return $this; 110 - } 111 - 112 - public function limit($limit) 113 - { 114 - $this->size = $this->_size = $limit; 115 - $this->_reset(); 116 - 117 - return $this; 118 - } 119 - 120 - public function all() 121 - { 122 - $items = array(); 123 - foreach ($this as $item) { 124 - array_push($items, $item); 125 - } 126 - 127 - return $items; 128 - } 129 - 130 - public function first() 131 - { 132 - $prev_size = $this->_size; 133 - $this->_size = 1; 134 - $page = new Page($this->resource, $this->_buildUri()); 135 - $this->_size = $prev_size; 136 - $item = count($page->items) != 0 ? $page->items[0] : null; 137 - 138 - return $item; 139 - } 140 - 141 - public function one() 142 - { 143 - $prev_size = $this->_size; 144 - $this->_size = 2; 145 - $page = new Page($this->resource, $this->_buildUri()); 146 - $this->_size = $prev_size; 147 - if (count($page->items) == 1) { 148 - return $page->items[0]; 149 - } 150 - if (count($page->items) == 0) { 151 - throw new NoResultFound(); 152 - } 153 - 154 - throw new MultipleResultsFound(); 155 - } 156 - 157 - public function paginate() 158 - { 159 - return new Pagination($this->resource, $this->_buildUri()); 160 - } 161 - }
-29
externals/restful/src/RESTful/Registry.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class Registry 6 - { 7 - protected $_resources = array(); 8 - 9 - public function add($resource) 10 - { 11 - array_push($this->_resources, $resource); 12 - } 13 - 14 - public function match($uri) 15 - { 16 - foreach ($this->_resources as $resource) { 17 - $spec = $resource::getURISpec(); 18 - $result = $spec->match($uri); 19 - if ($result == null) { 20 - continue; 21 - } 22 - $result['class'] = $resource; 23 - 24 - return $result; 25 - } 26 - 27 - return null; 28 - } 29 - }
-205
externals/restful/src/RESTful/Resource.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - abstract class Resource 6 - { 7 - protected $_collection_uris, 8 - $_member_uris; 9 - 10 - public static function getClient() 11 - { 12 - $class = get_called_class(); 13 - 14 - return $class::$_client; 15 - } 16 - 17 - public static function getRegistry() 18 - { 19 - $class = get_called_class(); 20 - 21 - return $class::$_registry; 22 - } 23 - 24 - public static function getURISpec() 25 - { 26 - $class = get_called_class(); 27 - 28 - return $class::$_uri_spec; 29 - } 30 - 31 - public function __construct($fields = null) 32 - { 33 - if ($fields == null) { 34 - $fields = array(); 35 - } 36 - $this->_objectify($fields); 37 - } 38 - 39 - public function __get($name) 40 - { 41 - // collection uri 42 - if (array_key_exists($name, $this->_collection_uris)) { 43 - $result = $this->_collection_uris[$name]; 44 - $this->$name = new Collection($result['class'], $result['uri']); 45 - 46 - return $this->$name; 47 - } // member uri 48 - else if (array_key_exists($name, $this->_member_uris)) { 49 - $result = $this->$_collection_uris[$name]; 50 - $response = self::getClient() . get($result['uri']); 51 - $class = $result['class']; 52 - $this->$name = new $class($response->body); 53 - 54 - return $this->$name; 55 - } 56 - 57 - // unknown 58 - $trace = debug_backtrace(); 59 - trigger_error( 60 - sprintf('Undefined property via __get(): %s in %s on line %s', $name, $trace[0]['file'], $trace[0]['line']), 61 - E_USER_NOTICE 62 - ); 63 - 64 - return null; 65 - } 66 - 67 - public function __isset($name) 68 - { 69 - if (array_key_exists($name, $this->_collection_uris) || array_key_exists($name, $this->_member_uris)) { 70 - return true; 71 - } 72 - 73 - return false; 74 - } 75 - 76 - protected function _objectify($fields) 77 - { 78 - // initialize uris 79 - $this->_collection_uris = array(); 80 - $this->_member_uris = array(); 81 - 82 - foreach ($fields as $key => $val) { 83 - // nested uri 84 - if ((strlen($key) - 3) == strrpos($key, 'uri', 0) && $key != 'uri') { 85 - $result = self::getRegistry()->match($val); 86 - if ($result != null) { 87 - $name = substr($key, 0, -4); 88 - $class = $result['class']; 89 - if ($result['collection']) { 90 - $this->_collection_uris[$name] = array( 91 - 'class' => $class, 92 - 'uri' => $val, 93 - ); 94 - } else { 95 - $this->_member_uris[$name] = array( 96 - 'class' => $class, 97 - 'uri' => $val, 98 - ); 99 - } 100 - 101 - continue; 102 - } 103 - } elseif (is_object($val) && property_exists($val, 'uri')) { 104 - // nested 105 - $result = self::getRegistry()->match($val->uri); 106 - if ($result != null) { 107 - $class = $result['class']; 108 - if ($result['collection']) { 109 - $this->$key = new Collection($class, $val['uri'], $val); 110 - } else { 111 - $this->$key = new $class($val); 112 - } 113 - 114 - continue; 115 - } 116 - } elseif (is_array($val) && array_key_exists('uri', $val)) { 117 - $result = self::getRegistry()->match($val['uri']); 118 - if ($result != null) { 119 - $class = $result['class']; 120 - if ($result['collection']) { 121 - $this->$key = new Collection($class, $val['uri'], $val); 122 - } else { 123 - $this->$key = new $class($val); 124 - } 125 - 126 - continue; 127 - } 128 - } 129 - 130 - // default 131 - $this->$key = $val; 132 - } 133 - } 134 - 135 - public static function query() 136 - { 137 - $uri_spec = self::getURISpec(); 138 - if ($uri_spec == null || $uri_spec->collection_uri == null) { 139 - $msg = sprintf('Cannot directly query %s resources', get_called_class()); 140 - throw new \LogicException($msg); 141 - } 142 - 143 - return new Query(get_called_class(), $uri_spec->collection_uri); 144 - } 145 - 146 - public static function get($uri) 147 - { 148 - # id 149 - if (strncmp($uri, '/', 1)) { 150 - $uri_spec = self::getURISpec(); 151 - if ($uri_spec == null || $uri_spec->collection_uri == null) { 152 - $msg = sprintf('Cannot get %s resources by id %s', $class, $uri); 153 - throw new \LogicException($msg); 154 - } 155 - $uri = $uri_spec->collection_uri . '/' . $uri; 156 - } 157 - 158 - $response = self::getClient()->get($uri); 159 - $class = get_called_class(); 160 - 161 - return new $class($response->body); 162 - } 163 - 164 - public function save() 165 - { 166 - // payload 167 - $payload = array(); 168 - foreach ($this as $key => $val) { 169 - if ($key[0] == '_' || is_object($val)) { 170 - continue; 171 - } 172 - $payload[$key] = $val; 173 - } 174 - 175 - // update 176 - if (array_key_exists('uri', $payload)) { 177 - $uri = $payload['uri']; 178 - unset($payload['uri']); 179 - $response = self::getClient()->put($uri, $payload); 180 - } else { 181 - // create 182 - $class = get_class($this); 183 - if ($class::$_uri_spec == null || $class::$_uri_spec->collection_uri == null) { 184 - $msg = sprintf('Cannot directly create %s resources', $class); 185 - throw new \LogicException($msg); 186 - } 187 - $response = self::getClient()->post($class::$_uri_spec->collection_uri, $payload); 188 - } 189 - 190 - // re-objectify 191 - foreach ($this as $key => $val) { 192 - unset($this->$key); 193 - } 194 - $this->_objectify($response->body); 195 - 196 - return $this; 197 - } 198 - 199 - public function delete() 200 - { 201 - self::getClient()->delete($this->uri); 202 - 203 - return $this; 204 - } 205 - }
-12
externals/restful/src/RESTful/Settings.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - /** 6 - * Settings. 7 - * 8 - */ 9 - class Settings 10 - { 11 - const VERSION = '0.1.7'; 12 - }
-15
externals/restful/src/RESTful/SortExpression.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class SortExpression 6 - { 7 - public $name, 8 - $ascending; 9 - 10 - public function __construct($field, $ascending = true) 11 - { 12 - $this->field = $field; 13 - $this->ascending = $ascending; 14 - } 15 - }
-58
externals/restful/src/RESTful/URISpec.php
··· 1 - <?php 2 - 3 - namespace RESTful; 4 - 5 - class URISpec 6 - { 7 - public $collection_uri = null, 8 - $name, 9 - $idNames; 10 - 11 - public function __construct($name, $idNames, $root = null) 12 - { 13 - $this->name = $name; 14 - if (!is_array($idNames)) { 15 - $idNames = array($idNames); 16 - } 17 - $this->idNames = $idNames; 18 - if ($root != null) { 19 - if ($root == '' || substr($root, -1) == '/') { 20 - $this->collection_uri = $root . $name; 21 - } else { 22 - $this->collection_uri = $root . '/' . $name; 23 - } 24 - } 25 - } 26 - 27 - public function match($uri) 28 - { 29 - $parts = explode('/', rtrim($uri, "/")); 30 - 31 - // collection 32 - if ($parts[count($parts) - 1] == $this->name) { 33 - 34 - return array( 35 - 'collection' => true, 36 - ); 37 - } 38 - 39 - // non-member 40 - if (count($parts) < count($this->idNames) + 1 || 41 - $parts[count($parts) - 1 - count($this->idNames)] != $this->name 42 - ) { 43 - return null; 44 - } 45 - 46 - // member 47 - $ids = array_combine( 48 - $this->idNames, 49 - array_slice($parts, -count($this->idNames)) 50 - ); 51 - $result = array( 52 - 'collection' => false, 53 - 'ids' => $ids, 54 - ); 55 - 56 - return $result; 57 - } 58 - }
-241
externals/restful/tests/RESTful/CoreTest.php
··· 1 - <?php 2 - 3 - namespace RESTful\Test; 4 - 5 - \RESTful\Bootstrap::init(); 6 - \Httpful\Bootstrap::init(); 7 - 8 - use RESTful\URISpec; 9 - use RESTful\Client; 10 - use RESTful\Registry; 11 - use RESTful\Fields; 12 - use RESTful\Query; 13 - use RESTful\Page; 14 - 15 - class Settings 16 - { 17 - public static $url_root = 'http://api.example.com'; 18 - 19 - public static $agent = 'example-php'; 20 - 21 - public static $version = '0.1.0'; 22 - 23 - public static $api_key = null; 24 - } 25 - 26 - class Resource extends \RESTful\Resource 27 - { 28 - public static $fields, $f; 29 - 30 - protected static $_client, $_registry, $_uri_spec; 31 - 32 - public static function init() 33 - { 34 - self::$_client = new Client('Settings'); 35 - self::$_registry = new Registry(); 36 - self::$f = self::$fields = new Fields(); 37 - } 38 - 39 - public static function getClient() 40 - { 41 - $class = get_called_class(); 42 - return $class::$_client; 43 - } 44 - 45 - public static function getRegistry() 46 - { 47 - $class = get_called_class(); 48 - return $class::$_registry; 49 - } 50 - 51 - public static function getURISpec() 52 - { 53 - $class = get_called_class(); 54 - return $class::$_uri_spec; 55 - } 56 - } 57 - 58 - Resource::init(); 59 - 60 - class A extends Resource 61 - { 62 - protected static $_uri_spec = null; 63 - 64 - public static function init() 65 - { 66 - self::$_uri_spec = new URISpec('as', 'id', '/'); 67 - self::$_registry->add(get_called_class()); 68 - } 69 - } 70 - 71 - A::init(); 72 - 73 - class B extends Resource 74 - { 75 - protected static $_uri_spec = null; 76 - 77 - public static function init() 78 - { 79 - self::$_uri_spec = new URISpec('bs', 'id', '/'); 80 - self::$_registry->add(get_called_class()); 81 - } 82 - } 83 - 84 - B::init(); 85 - 86 - class URISpecTest extends \PHPUnit_Framework_TestCase 87 - { 88 - public function testNoRoot() 89 - { 90 - $uri_spec = new URISpec('grapes', 'seed'); 91 - $this->assertEquals($uri_spec->collection_uri, null); 92 - 93 - $result = $uri_spec->match('/some/raisins'); 94 - $this->assertEquals($result, null); 95 - 96 - $result = $uri_spec->match('/some/grapes'); 97 - $this->assertEquals($result, array('collection' => true)); 98 - 99 - $result = $uri_spec->match('/some/grapes/1234'); 100 - $expected = array( 101 - 'collection' => false, 102 - 'ids' => array('seed' => '1234') 103 - ); 104 - $this->assertEquals($expected, $result); 105 - } 106 - 107 - public function testSingleId() 108 - { 109 - $uri_spec = new URISpec('tomatoes', 'stem', '/v1'); 110 - $this->assertNotEquals($uri_spec->collection_uri, null); 111 - 112 - $result = $uri_spec->match('/some/tomatoes/that/are/green'); 113 - $this->assertEquals($result, null); 114 - 115 - $result = $uri_spec->match('/some/tomatoes'); 116 - $this->assertEquals($result, array('collection' => true)); 117 - 118 - $result = $uri_spec->match('/some/tomatoes/4321'); 119 - $expected = array( 120 - 'collection' => false, 121 - 'ids' => array('stem' => '4321') 122 - ); 123 - $this->assertEquals($expected, $result); 124 - } 125 - 126 - public function testMultipleIds() 127 - { 128 - $uri_spec = new URISpec('tomatoes', array('stem', 'root'), '/v1'); 129 - $this->assertNotEquals($uri_spec->collection_uri, null); 130 - 131 - $result = $uri_spec->match('/some/tomatoes/that/are/green'); 132 - $this->assertEquals($result, null); 133 - 134 - $result = $uri_spec->match('/some/tomatoes'); 135 - $this->assertEquals($result, array('collection' => true)); 136 - 137 - $result = $uri_spec->match('/some/tomatoes/4321/1234'); 138 - $expected = array( 139 - 'collection' => false, 140 - 'ids' => array('stem' => '4321', 'root' => '1234') 141 - ); 142 - $this->assertEquals($expected, $result); 143 - } 144 - } 145 - 146 - class QueryTest extends \PHPUnit_Framework_TestCase 147 - { 148 - public function testParse() 149 - { 150 - $uri = '/some/uri?field2=123&sort=field5%2Cdesc&limit=101&field3.field4%5Bcontains%5D=hi'; 151 - $query = new Query('Resource', $uri); 152 - $expected = array( 153 - 'field2' => array('123'), 154 - 'field3.field4[contains]' => array('hi') 155 - ); 156 - $this->assertEquals($query->filters, $expected); 157 - $expected = array('field5,desc'); 158 - $this->assertEquals($query->sorts, $expected); 159 - $this->assertEquals($query->size, 101); 160 - } 161 - 162 - public function testBuild() 163 - { 164 - $query = new Query('Resource', '/some/uri'); 165 - $query->filter(Resource::$f->name->eq('Wonka Chocs')) 166 - ->filter(Resource::$f->support_email->endswith('gmail.com')) 167 - ->filter(Resource::$f->variable_fee_percentage->gte(3.5)) 168 - ->sort(Resource::$f->name->asc()) 169 - ->sort(Resource::$f->variable_fee_percentage->desc()) 170 - ->limit(101); 171 - $this->assertEquals( 172 - $query->filters, 173 - array( 174 - 'name' => array('Wonka Chocs'), 175 - 'support_email[contains]' => array('gmail.com'), 176 - 'variable_fee_percentage[>=]'=> array(3.5) 177 - ) 178 - ); 179 - $this->assertEquals( 180 - $query->sorts, 181 - array('name,asc', 'variable_fee_percentage,desc') 182 - ); 183 - $this->assertEquals( 184 - $query->size, 185 - 101 186 - ); 187 - } 188 - } 189 - 190 - class PageTest extends \PHPUnit_Framework_TestCase 191 - { 192 - public function testConstruct() 193 - { 194 - $data = new \stdClass(); 195 - $data->first_uri = 'some/first/uri'; 196 - $data->previous_uri = 'some/previous/uri'; 197 - $data->next_uri = null; 198 - $data->last_uri = 'some/last/uri'; 199 - $data->limit= 25; 200 - $data->offset = 0; 201 - $data->total = 101; 202 - $data->items = array(); 203 - 204 - $page = new Page( 205 - 'Resource', 206 - '/some/uri', 207 - $data 208 - ); 209 - 210 - $this->assertEquals($page->resource, 'Resource'); 211 - $this->assertEquals($page->total, 101); 212 - $this->assertEquals($page->items, array()); 213 - $this->assertTrue($page->hasPrevious()); 214 - $this->assertFalse($page->hasNext()); 215 - } 216 - } 217 - 218 - class ResourceTest extends \PHPUnit_Framework_TestCase 219 - { 220 - public function testQuery() 221 - { 222 - $query = A::query(); 223 - $this->assertEquals(get_class($query), 'RESTful\Query'); 224 - } 225 - 226 - public function testObjectify() 227 - { 228 - $a = new A(array( 229 - 'uri' => '/as/123', 230 - 'field1' => 123, 231 - 'b' => array( 232 - 'uri' => '/bs/321', 233 - 'field2' => 321 234 - )) 235 - ); 236 - $this->assertEquals(get_class($a), 'RESTful\Test\A'); 237 - $this->assertEquals($a->field1, 123); 238 - $this->assertEquals(get_class($a->b), 'RESTful\Test\B'); 239 - $this->assertEquals($a->b->field2, 321); 240 - } 241 - }
-8
externals/restful/tests/phpunit.xml
··· 1 - <phpunit> 2 - <testsuite name="RESTful"> 3 - <directory>.</directory> 4 - </testsuite> 5 - <logging> 6 - <log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/> 7 - </logging> 8 - </phpunit>
-21
externals/wepay/LICENSE
··· 1 - MIT License 2 - 3 - Copyright (C) 2013, WePay, Inc. <api at wepay dot com> 4 - 5 - Permission is hereby granted, free of charge, to any person obtaining a copy of 6 - this software and associated documentation files (the "Software"), to deal in 7 - the Software without restriction, including without limitation the rights to 8 - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 9 - of the Software, and to permit persons to whom the Software is furnished to do 10 - so, subject to the following conditions: 11 - 12 - The above copyright notice and this permission notice shall be included in all 13 - copies or substantial portions of the Software. 14 - 15 - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 - SOFTWARE.
-85
externals/wepay/README.md
··· 1 - WePay PHP SDK 2 - ============= 3 - 4 - WePay's API allows you to easily add payments into your application. 5 - 6 - For full documentation, see [WePay's developer documentation](https://www.wepay.com/developer) 7 - 8 - Usage 9 - ----- 10 - 11 - In addition to the samples below, we have included a very basic demo application in the `demoapp` directory. See its README file for additional information. 12 - 13 - ### Configuration ### 14 - 15 - For all requests, you must initialize the SDK with your Client ID and Client Secret, into either Staging or Production mode. All API calls made against WePay's staging environment mirror production in functionality, but do not actually move money. This allows you to develop your application and test the checkout experience from the perspective of your users without spending any money on payments. Our [full documentation](https://www.wepay.com/developer) contains additional information on test account numbers you can use in addition to "magic" amounts you can use to trigger payment failures and reversals (helpful for testing IPNs). 16 - 17 - **Note:** Staging and Production are two completely independent environments and share NO data with each other. This means that in order to use staging, you must register at [stage.wepay.com](https://stage.wepay.com/developer) and get a set of API keys for your Staging application, and must do the same on Production when you are ready to go live. API keys and access tokens granted on stage *can not* be used on Production, and vice-versa. 18 - 19 - <?php 20 - require './wepay.php'; 21 - WePay::useProduction('YOUR CLIENT ID', 'YOUR CLIENT SECRET'); // To initialize staging, use WePay::useStaging('ID','SECRET'); instead. 22 - 23 - ### Authentication ### 24 - 25 - To obtain an access token for your user, you must redirect the user to WePay for authentication. WePay uses OAuth2 for authorization, which is detailed [in our documentation](https://www.wepay.com/developer/reference/oauth2). To generate the URI to which you must redirect your user, the SDK contains `WePay::getAuthorizationUri($scope, $redirect_uri)`. `$scope` should be an array of scope strings detailed in the documentation. To request full access (most useful for testing, since users may be weary of granting permission to your application if it wants to do too much), you pay pass in `WePay::getAllScopes()`. `$redirect_uri` must be a fully qualified URI where we will send the user after permission is granted (or not granted), and the domain must match your application settings. 26 - 27 - If the user grants permission, he or she will be redirected to your `$redirect_uri` with `code=XXXX` appended to the query string. If permission is not granted, we will instead put `error=XXXX` in the query string. If `code` is present, the following will exchange it for an access token. Note that codes are only valid for several minutes, so you should do this immediately after the user is redirected back to your website or application. 28 - 29 - <?php 30 - if (!empty($_GET['error'])) { 31 - // user did not grant permissions 32 - } 33 - elseif (empty($_GET['code'])) { 34 - // set $scope and $redirect_uri before doing this 35 - // this will send the user to WePay to authenticate 36 - $uri = WePay::getAuthorizationUri($scope, $redirect_uri); 37 - header("Location: $uri"); 38 - exit; 39 - } 40 - else { 41 - $info = WePay::getToken($_GET['code'], $redirect_uri); 42 - if ($info) { 43 - // YOUR ACCESS TOKEN IS HERE 44 - $access_token = $info->access_token; 45 - } 46 - else { 47 - // Unable to obtain access token 48 - } 49 - } 50 - 51 - Full details on the access token response are [here](https://www.wepay.com/developer/reference/oauth2#token). 52 - 53 - **Note:** If you only need access for yourself (e.g., for a personal storefront), the application settings page automatically creates an access token for you. Simply copy and paste it into your code rather than manually going through the authentication flow. 54 - 55 - ### Making API Calls ### 56 - 57 - With the `$access_token` from above, get a new SDK object: 58 - 59 - <?php 60 - $wepay = new WePay($access_token); 61 - 62 - Then you can make a simple API call. This will list the user's accounts available to your application: 63 - 64 - // (continued from above) 65 - try { 66 - $accounts = $wepay->request('account/find'); 67 - foreach ($accounts as $account) { 68 - echo "<a href=\"$account->account_uri\">$account->name</a>: $account->description <br />"; 69 - } 70 - } 71 - catch (WePayException $e) { 72 - // Something went wrong - normally you would log 73 - // this and give your user a more informative message 74 - echo $e->getMessage(); 75 - } 76 - 77 - And that's it! For more detail on what API calls are available, their parameters and responses, and what permissions they require, please see [our documentation](https://www.wepay.com/developer/reference). For some more detailed examples, look in the `demoapp` directory and check the README. Dropping the entire directory in a web-accessible location and adding your API keys should allow you to be up and running in just a few seconds. 78 - 79 - ### SSL Certificate ### 80 - 81 - If making an API call causes the following problem: 82 - 83 - Uncaught exception 'Exception' with message 'cURL error while making API call to WePay: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed' 84 - 85 - You can read the solution here: https://support.wepay.com/entries/21095813-problem-with-ssl-certificate-verification
-13
externals/wepay/composer.json
··· 1 - { 2 - "name": "wepay/php-sdk", 3 - "description": "WePay APIv2 SDK for PHP", 4 - "authors": [ 5 - { 6 - "name": "WePay", 7 - "email": "api@wepay.com" 8 - } 9 - ], 10 - "autoload": { 11 - "files": ["wepay.php"] 12 - } 13 - }
-19
externals/wepay/demoapp/README
··· 1 - After registering your application at wepay.com (or stage.wepay.com), you 2 - need to make two updates to this application: 3 - 4 - 1 - set your client_id and client_secret in _shared.php 5 - 2 - set the redirect_uri in login.php 6 - 7 - That should be enough to start making API calls against WePay's API. While 8 - this is by no means a production-ready example, it should provide you a 9 - couple ideas on how to get running. 10 - 11 - It also defaults to requesting all possible scope fields in the 12 - authentication request. We suggest limiting the request to the minimum 13 - your application requires, which will maximize the chance the user 14 - grants permissions to your application. You can customize this in 15 - login.php. 16 - 17 - If you have any questions, please contact the API team: api@wepay.com 18 - 19 - - WePay
-4
externals/wepay/demoapp/_shared.php
··· 1 - <?php 2 - require '../wepay.php'; 3 - Wepay::useStaging('YOUR CLIENT ID', 'YOUR CLIENT SECRET'); 4 - session_start();
-20
externals/wepay/demoapp/accountlist.php
··· 1 - <?php 2 - require './_shared.php'; 3 - ?> 4 - <h1>WePay Demo App: Account List</h1> 5 - <a href="index.php">Back</a> 6 - <br /> 7 - 8 - <?php 9 - try { 10 - $wepay = new WePay($_SESSION['wepay_access_token']); 11 - $accounts = $wepay->request('account/find'); 12 - foreach ($accounts as $account) { 13 - echo "<a href=\"$account->account_uri\">$account->name</a>: $account->description <br />"; 14 - } 15 - } 16 - catch (WePayException $e) { 17 - // Something went wrong - normally you would log 18 - // this and give your user a more informative message 19 - echo $e->getMessage(); 20 - }
-20
externals/wepay/demoapp/index.php
··· 1 - <?php 2 - require './_shared.php'; 3 - ?> 4 - 5 - <h1>WePay Demo App</h1> 6 - <?php if (empty($_SESSION['wepay_access_token'])): ?> 7 - 8 - <a href="login.php">Log in with WePay</a> 9 - 10 - <?php else: ?> 11 - 12 - <a href="user.php">User info</a> 13 - <br /> 14 - <a href="openaccount.php">Open new account</a> 15 - <br /> 16 - <a href="accountlist.php">Account list</a> 17 - <br /> 18 - <a href="logout.php">Log out</a> 19 - 20 - <?php endif; ?>
-41
externals/wepay/demoapp/login.php
··· 1 - <?php 2 - require './_shared.php'; 3 - 4 - // ** YOU MUST CHANGE THIS FOR THE SAMPLE APP TO WORK ** 5 - $redirect_uri = 'http://YOUR SERVER NAME/login.php'; 6 - $scope = WePay::getAllScopes(); 7 - 8 - // If we are already logged in, send the user home 9 - if (!empty($_SESSION['wepay_access_token'])) { 10 - header('Location: index.php'); 11 - exit; 12 - } 13 - 14 - // If the authentication dance returned an error, catch it to avoid a 15 - // redirect loop. This usually indicates some sort of application issue, 16 - // like a domain mismatch on your redirect_uri 17 - if (!empty($_GET['error'])) { 18 - echo 'Error during user authentication: '; 19 - echo htmlentities($_GET['error_description']); 20 - exit; 21 - } 22 - 23 - // If we don't have a code from being redirected back here, 24 - // send the user to WePay to grant permissions. 25 - if (empty($_GET['code'])) { 26 - $uri = WePay::getAuthorizationUri($scope, $redirect_uri); 27 - header("Location: $uri"); 28 - } 29 - else { 30 - $info = WePay::getToken($_GET['code'], $redirect_uri); 31 - if ($info) { 32 - // Normally you'd integrate this into your existing auth system 33 - $_SESSION['wepay_access_token'] = $info->access_token; 34 - // If desired, you can also store $info->user_id somewhere 35 - header('Location: index.php'); 36 - } 37 - else { 38 - // Unable to obtain access token 39 - echo 'Unable to obtain access token from WePay.'; 40 - } 41 - }
-6
externals/wepay/demoapp/logout.php
··· 1 - <?php 2 - session_start(); 3 - $_SESSION = array(); 4 - session_destroy(); 5 - header('Location: index.php'); 6 - exit;
-50
externals/wepay/demoapp/openaccount.php
··· 1 - <?php 2 - require './_shared.php'; 3 - ?> 4 - <h1>WePay Demo App: Open Account</h1> 5 - <a href="index.php">Back</a> 6 - <br /> 7 - 8 - <?php 9 - if ($_SERVER['REQUEST_METHOD'] == 'POST') { 10 - if (isset($_POST['account_name']) && isset($_POST['account_description'])) { 11 - // WePay sanitizes its own data, but displaying raw POST data on your own site is a XSS security hole. 12 - $name = htmlentities($_POST['account_name']); 13 - $desc = htmlentities($_POST['account_description']); 14 - try { 15 - $wepay = new WePay($_SESSION['wepay_access_token']); 16 - $account = $wepay->request('account/create', array( 17 - 'name' => $name, 18 - 'description' => $desc, 19 - )); 20 - echo "Created account $name for '$desc'! View on WePay at <a href=\"$account->account_uri\">$account->account_uri</a>. See all of your accounts <a href=\"accountlist.php\">here</a>."; 21 - } 22 - catch (WePayException $e) { 23 - // Something went wrong - normally you would log 24 - // this and give your user a more informative message 25 - echo $e->getMessage(); 26 - } 27 - } 28 - else { 29 - echo 'Account name and description are both required.'; 30 - } 31 - } 32 - ?> 33 - 34 - <form method="post"> 35 - <fieldset> 36 - <legend>Account Info</legend> 37 - 38 - <label for="account_name">Account Name:</label><br /> 39 - <input type="text" id="account_name" name="account_name" placeholder="Ski Trip Savings"/> 40 - 41 - <br /><br /> 42 - 43 - <label for="account_description">Account Description: </label><br /> 44 - <textarea name="account_description" rows="10" cols="40" placeholder="Saving up some dough for our ski trip!"></textarea> 45 - 46 - <br /><br /> 47 - 48 - <input type="submit" value="Open account" /> 49 - </fieldset> 50 - </form>
-22
externals/wepay/demoapp/user.php
··· 1 - <?php 2 - require './_shared.php'; 3 - ?> 4 - <h1>WePay Demo App: User Info</h1> 5 - <a href="index.php">Back</a> 6 - <br /> 7 - 8 - <?php 9 - try { 10 - $wepay = new WePay($_SESSION['wepay_access_token']); 11 - $user = $wepay->request('user'); 12 - echo '<dl>'; 13 - foreach ($user as $key => $value) { 14 - echo "<dt>$key</dt><dd>$value</dd>"; 15 - } 16 - echo '</dl>'; 17 - } 18 - catch (WePayException $e) { 19 - // Something went wrong - normally you would log 20 - // this and give your user a more informative message 21 - echo $e->getMessage(); 22 - }
-69
externals/wepay/iframe_demoapp/checkout.php
··· 1 - <?php 2 - /** 3 - * This PHP script helps you do the iframe checkout 4 - * 5 - */ 6 - 7 - 8 - /** 9 - * Put your API credentials here: 10 - * Get these from your API app details screen 11 - * https://stage.wepay.com/app 12 - */ 13 - $client_id = "PUT YOUR CLIENT_ID HERE"; 14 - $client_secret = "PUT YOUR CLIENT_SECRET HERE"; 15 - $access_token = "PUT YOUR ACCESS TOKEN HERE"; 16 - $account_id = "PUT YOUR ACCOUNT_ID HERE"; // you can find your account ID via list_accounts.php which users the /account/find call 17 - 18 - /** 19 - * Initialize the WePay SDK object 20 - */ 21 - require '../wepay.php'; 22 - Wepay::useStaging($client_id, $client_secret); 23 - $wepay = new WePay($access_token); 24 - 25 - /** 26 - * Make the API request to get the checkout_uri 27 - * 28 - */ 29 - try { 30 - $checkout = $wepay->request('/checkout/create', array( 31 - 'account_id' => $account_id, // ID of the account that you want the money to go to 32 - 'amount' => 100, // dollar amount you want to charge the user 33 - 'short_description' => "this is a test payment", // a short description of what the payment is for 34 - 'type' => "GOODS", // the type of the payment - choose from GOODS SERVICE DONATION or PERSONAL 35 - 'mode' => "iframe", // put iframe here if you want the checkout to be in an iframe, regular if you want the user to be sent to WePay 36 - ) 37 - ); 38 - } catch (WePayException $e) { // if the API call returns an error, get the error message for display later 39 - $error = $e->getMessage(); 40 - } 41 - 42 - ?> 43 - 44 - <html> 45 - <head> 46 - </head> 47 - 48 - <body> 49 - 50 - <h1>Checkout:</h1> 51 - 52 - <p>The user will checkout here:</p> 53 - 54 - <?php if (isset($error)): ?> 55 - <h2 style="color:red">ERROR: <?php echo $error ?></h2> 56 - <?php else: ?> 57 - <div id="checkout_div"></div> 58 - 59 - <script type="text/javascript" src="https://stage.wepay.com/js/iframe.wepay.js"> 60 - </script> 61 - 62 - <script type="text/javascript"> 63 - WePay.iframe_checkout("checkout_div", "<?php echo $checkout->checkout_uri ?>"); 64 - </script> 65 - <?php endif; ?> 66 - 67 - </body> 68 - 69 - </html>
-74
externals/wepay/iframe_demoapp/list_accounts.php
··· 1 - <?php 2 - /** 3 - * This PHP script helps you find your account_id 4 - * 5 - */ 6 - 7 - 8 - 9 - /** 10 - * Put your API credentials here: 11 - * Get these from your API app details screen 12 - * https://stage.wepay.com/app 13 - */ 14 - $client_id = "PUT YOUR CLIENT_ID HERE"; 15 - $client_secret = "PUT YOUR CLIENT_SECRET HERE"; 16 - $access_token = "PUT YOUR ACCESS TOKEN HERE"; 17 - 18 - /** 19 - * Initialize the WePay SDK object 20 - */ 21 - require '../wepay.php'; 22 - Wepay::useStaging($client_id, $client_secret); 23 - $wepay = new WePay($access_token); 24 - 25 - /** 26 - * Make the API request to get a list of all accounts this user owns 27 - * 28 - */ 29 - try { 30 - $accounts = $wepay->request('/account/find'); 31 - } catch (WePayException $e) { // if the API call returns an error, get the error message for display later 32 - $error = $e->getMessage(); 33 - } 34 - 35 - ?> 36 - 37 - <html> 38 - <head> 39 - </head> 40 - 41 - <body> 42 - 43 - <h1>List all accounts:</h1> 44 - 45 - <p>The following is a list of all accounts that this user owns</p> 46 - 47 - <?php if (isset($error)): ?> 48 - <h2 style="color:red">ERROR: <?php echo $error ?></h2> 49 - <?php elseif (empty($accounts)) : ?> 50 - <h2>You do not have any accounts. Go to <a href="https://stage.wepay.com.com">https://stage.wepay.com</a> to open an account.<h2> 51 - <?php else: ?> 52 - <table border="1"> 53 - <thead> 54 - <tr> 55 - <td>Account ID</td> 56 - <td>Account Name</td> 57 - <td>Account Description</td> 58 - </tr> 59 - </thead> 60 - <tbody> 61 - <?php foreach ($accounts as $a): ?> 62 - <tr> 63 - <td><?php echo $a->account_id ?></td> 64 - <td><?php echo $a->name ?></td> 65 - <td><?php echo $a->description ?></td> 66 - </tr> 67 - <?php endforeach;?> 68 - </tbody> 69 - </table> 70 - <?php endif; ?> 71 - 72 - </body> 73 - 74 - </html>
-291
externals/wepay/wepay.php
··· 1 - <?php 2 - 3 - class WePay { 4 - 5 - /** 6 - * Version number - sent in user agent string 7 - */ 8 - const VERSION = '0.1.4'; 9 - 10 - /** 11 - * Scope fields 12 - * Passed into Wepay::getAuthorizationUri as array 13 - */ 14 - const SCOPE_MANAGE_ACCOUNTS = 'manage_accounts'; // Open and interact with accounts 15 - const SCOPE_VIEW_BALANCE = 'view_balance'; // View account balances 16 - const SCOPE_COLLECT_PAYMENTS = 'collect_payments'; // Create and interact with checkouts 17 - const SCOPE_VIEW_USER = 'view_user'; // Get details about authenticated user 18 - const SCOPE_PREAPPROVE_PAYMENTS = 'preapprove_payments'; // Create and interact with preapprovals 19 - const SCOPE_SEND_MONEY = 'send_money'; // For withdrawals 20 - 21 - /** 22 - * Application's client ID 23 - */ 24 - private static $client_id; 25 - 26 - /** 27 - * Application's client secret 28 - */ 29 - private static $client_secret; 30 - 31 - /** 32 - * @deprecated Use WePay::getAllScopes() instead. 33 - */ 34 - public static $all_scopes = array( 35 - self::SCOPE_MANAGE_ACCOUNTS, 36 - self::SCOPE_VIEW_BALANCE, 37 - self::SCOPE_COLLECT_PAYMENTS, 38 - self::SCOPE_PREAPPROVE_PAYMENTS, 39 - self::SCOPE_VIEW_USER, 40 - self::SCOPE_SEND_MONEY, 41 - ); 42 - 43 - /** 44 - * Determines whether to use WePay's staging or production servers 45 - */ 46 - private static $production = null; 47 - 48 - /** 49 - * cURL handle 50 - */ 51 - private static $ch = NULL; 52 - 53 - /** 54 - * Authenticated user's access token 55 - */ 56 - private $token; 57 - 58 - /** 59 - * Pass WePay::getAllScopes() into getAuthorizationUri if your application desires full access 60 - */ 61 - public static function getAllScopes() { 62 - return array( 63 - self::SCOPE_MANAGE_ACCOUNTS, 64 - self::SCOPE_VIEW_BALANCE, 65 - self::SCOPE_COLLECT_PAYMENTS, 66 - self::SCOPE_PREAPPROVE_PAYMENTS, 67 - self::SCOPE_VIEW_USER, 68 - self::SCOPE_SEND_MONEY, 69 - ); 70 - } 71 - 72 - /** 73 - * Generate URI used during oAuth authorization 74 - * Redirect your user to this URI where they can grant your application 75 - * permission to make API calls 76 - * @link https://www.wepay.com/developer/reference/oauth2 77 - * @param array $scope List of scope fields for which your application wants access 78 - * @param string $redirect_uri Where user goes after logging in at WePay (domain must match application settings) 79 - * @param array $options optional user_name,user_email which will be pre-filled on login form, state to be returned in querystring of redirect_uri 80 - * @return string URI to which you must redirect your user to grant access to your application 81 - */ 82 - public static function getAuthorizationUri(array $scope, $redirect_uri, array $options = array()) { 83 - // This does not use WePay::getDomain() because the user authentication 84 - // domain is different than the API call domain 85 - if (self::$production === null) { 86 - throw new RuntimeException('You must initialize the WePay SDK with WePay::useStaging() or WePay::useProduction()'); 87 - } 88 - $domain = self::$production ? 'https://www.wepay.com' : 'https://stage.wepay.com'; 89 - $uri = $domain . '/v2/oauth2/authorize?'; 90 - $uri .= http_build_query(array( 91 - 'client_id' => self::$client_id, 92 - 'redirect_uri' => $redirect_uri, 93 - 'scope' => implode(',', $scope), 94 - 'state' => empty($options['state']) ? '' : $options['state'], 95 - 'user_name' => empty($options['user_name']) ? '' : $options['user_name'], 96 - 'user_email' => empty($options['user_email']) ? '' : $options['user_email'], 97 - ), '', '&'); 98 - return $uri; 99 - } 100 - 101 - private static function getDomain() { 102 - if (self::$production === true) { 103 - return 'https://wepayapi.com/v2/'; 104 - } 105 - elseif (self::$production === false) { 106 - return 'https://stage.wepayapi.com/v2/'; 107 - } 108 - else { 109 - throw new RuntimeException('You must initialize the WePay SDK with WePay::useStaging() or WePay::useProduction()'); 110 - } 111 - } 112 - 113 - /** 114 - * Exchange a temporary access code for a (semi-)permanent access token 115 - * @param string $code 'code' field from query string passed to your redirect_uri page 116 - * @param string $redirect_uri Where user went after logging in at WePay (must match value from getAuthorizationUri) 117 - * @return StdClass|false 118 - * user_id 119 - * access_token 120 - * token_type 121 - */ 122 - public static function getToken($code, $redirect_uri) { 123 - $params = (array( 124 - 'client_id' => self::$client_id, 125 - 'client_secret' => self::$client_secret, 126 - 'redirect_uri' => $redirect_uri, 127 - 'code' => $code, 128 - 'state' => '', // do not hardcode 129 - )); 130 - $result = self::make_request('oauth2/token', $params); 131 - return $result; 132 - } 133 - 134 - /** 135 - * Configure SDK to run against WePay's production servers 136 - * @param string $client_id Your application's client id 137 - * @param string $client_secret Your application's client secret 138 - * @return void 139 - * @throws RuntimeException 140 - */ 141 - public static function useProduction($client_id, $client_secret) { 142 - if (self::$production !== null) { 143 - throw new RuntimeException('API mode has already been set.'); 144 - } 145 - self::$production = true; 146 - self::$client_id = $client_id; 147 - self::$client_secret = $client_secret; 148 - } 149 - 150 - /** 151 - * Configure SDK to run against WePay's staging servers 152 - * @param string $client_id Your application's client id 153 - * @param string $client_secret Your application's client secret 154 - * @return void 155 - * @throws RuntimeException 156 - */ 157 - public static function useStaging($client_id, $client_secret) { 158 - if (self::$production !== null) { 159 - throw new RuntimeException('API mode has already been set.'); 160 - } 161 - self::$production = false; 162 - self::$client_id = $client_id; 163 - self::$client_secret = $client_secret; 164 - } 165 - 166 - /** 167 - * Create a new API session 168 - * @param string $token - access_token returned from WePay::getToken 169 - */ 170 - public function __construct($token) { 171 - if ($token && !is_string($token)) { 172 - throw new InvalidArgumentException('$token must be a string, ' . gettype($token) . ' provided'); 173 - } 174 - $this->token = $token; 175 - } 176 - 177 - /** 178 - * Clean up cURL handle 179 - */ 180 - public function __destruct() { 181 - if (self::$ch) { 182 - curl_close(self::$ch); 183 - self::$ch = NULL; 184 - } 185 - } 186 - 187 - /** 188 - * create the cURL request and execute it 189 - */ 190 - private static function make_request($endpoint, $values, $headers = array()) 191 - { 192 - self::$ch = curl_init(); 193 - $headers = array_merge(array("Content-Type: application/json"), $headers); // always pass the correct Content-Type header 194 - curl_setopt(self::$ch, CURLOPT_USERAGENT, 'WePay v2 PHP SDK v' . self::VERSION); 195 - curl_setopt(self::$ch, CURLOPT_RETURNTRANSFER, true); 196 - curl_setopt(self::$ch, CURLOPT_HTTPHEADER, $headers); 197 - curl_setopt(self::$ch, CURLOPT_TIMEOUT, 30); // 30-second timeout, adjust to taste 198 - curl_setopt(self::$ch, CURLOPT_POST, !empty($values)); // WePay's API is not strictly RESTful, so all requests are sent as POST unless there are no request values 199 - 200 - $uri = self::getDomain() . $endpoint; 201 - curl_setopt(self::$ch, CURLOPT_URL, $uri); 202 - 203 - if (!empty($values)) { 204 - curl_setopt(self::$ch, CURLOPT_POSTFIELDS, json_encode($values)); 205 - } 206 - 207 - $raw = curl_exec(self::$ch); 208 - if ($errno = curl_errno(self::$ch)) { 209 - // Set up special handling for request timeouts 210 - if ($errno == CURLE_OPERATION_TIMEOUTED) { 211 - throw new WePayServerException("Timeout occurred while trying to connect to WePay"); 212 - } 213 - throw new Exception('cURL error while making API call to WePay: ' . curl_error(self::$ch), $errno); 214 - } 215 - $result = json_decode($raw); 216 - $httpCode = curl_getinfo(self::$ch, CURLINFO_HTTP_CODE); 217 - if ($httpCode >= 400) { 218 - if (!isset($result->error_code)) { 219 - throw new WePayServerException("WePay returned an error response with no error_code, please alert api@wepay.com. Original message: $result->error_description", $httpCode, $result, 0); 220 - } 221 - if ($httpCode >= 500) { 222 - throw new WePayServerException($result->error_description, $httpCode, $result, $result->error_code); 223 - } 224 - switch ($result->error) { 225 - case 'invalid_request': 226 - throw new WePayRequestException($result->error_description, $httpCode, $result, $result->error_code); 227 - case 'access_denied': 228 - default: 229 - throw new WePayPermissionException($result->error_description, $httpCode, $result, $result->error_code); 230 - } 231 - } 232 - 233 - return $result; 234 - } 235 - 236 - /** 237 - * Make API calls against authenticated user 238 - * @param string $endpoint - API call to make (ex. 'user', 'account/find') 239 - * @param array $values - Associative array of values to send in API call 240 - * @return StdClass 241 - * @throws WePayException on failure 242 - * @throws Exception on catastrophic failure (non-WePay-specific cURL errors) 243 - */ 244 - public function request($endpoint, array $values = array()) { 245 - $headers = array(); 246 - 247 - if ($this->token) { // if we have an access_token, add it to the Authorization header 248 - $headers[] = "Authorization: Bearer $this->token"; 249 - } 250 - 251 - $result = self::make_request($endpoint, $values, $headers); 252 - 253 - return $result; 254 - } 255 - } 256 - 257 - /** 258 - * Different problems will have different exception types so you can 259 - * catch and handle them differently. 260 - * 261 - * WePayServerException indicates some sort of 500-level error code and 262 - * was unavoidable from your perspective. You may need to re-run the 263 - * call, or check whether it was received (use a "find" call with your 264 - * reference_id and make a decision based on the response) 265 - * 266 - * WePayRequestException indicates a development error - invalid endpoint, 267 - * erroneous parameter, etc. 268 - * 269 - * WePayPermissionException indicates your authorization token has expired, 270 - * was revoked, or is lacking in scope for the call you made 271 - */ 272 - class WePayException extends Exception { 273 - public function __construct($description = '', $http_code = FALSE, $response = FALSE, $code = 0, $previous = NULL) 274 - { 275 - $this->response = $response; 276 - 277 - if (!defined('PHP_VERSION_ID')) { 278 - $version = explode('.', PHP_VERSION); 279 - define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2])); 280 - } 281 - 282 - if (PHP_VERSION_ID < 50300) { 283 - parent::__construct($description, $code); 284 - } else { 285 - parent::__construct($description, $code, $previous); 286 - } 287 - } 288 - } 289 - class WePayRequestException extends WePayException {} 290 - class WePayPermissionException extends WePayException {} 291 - class WePayServerException extends WePayException {}
-2
src/__phutil_library_map__.php
··· 5248 5248 'PhortuneSubscriptionViewController' => 'applications/phortune/controller/subscription/PhortuneSubscriptionViewController.php', 5249 5249 'PhortuneSubscriptionWorker' => 'applications/phortune/worker/PhortuneSubscriptionWorker.php', 5250 5250 'PhortuneTestPaymentProvider' => 'applications/phortune/provider/PhortuneTestPaymentProvider.php', 5251 - 'PhortuneWePayPaymentProvider' => 'applications/phortune/provider/PhortuneWePayPaymentProvider.php', 5252 5251 'PhragmentBrowseController' => 'applications/phragment/controller/PhragmentBrowseController.php', 5253 5252 'PhragmentCanCreateCapability' => 'applications/phragment/capability/PhragmentCanCreateCapability.php', 5254 5253 'PhragmentConduitAPIMethod' => 'applications/phragment/conduit/PhragmentConduitAPIMethod.php', ··· 11697 11696 'PhortuneSubscriptionViewController' => 'PhortuneController', 11698 11697 'PhortuneSubscriptionWorker' => 'PhabricatorWorker', 11699 11698 'PhortuneTestPaymentProvider' => 'PhortunePaymentProvider', 11700 - 'PhortuneWePayPaymentProvider' => 'PhortunePaymentProvider', 11701 11699 'PhragmentBrowseController' => 'PhragmentController', 11702 11700 'PhragmentCanCreateCapability' => 'PhabricatorPolicyCapability', 11703 11701 'PhragmentConduitAPIMethod' => 'ConduitAPIMethod',
-405
src/applications/phortune/provider/PhortuneWePayPaymentProvider.php
··· 1 - <?php 2 - 3 - final class PhortuneWePayPaymentProvider extends PhortunePaymentProvider { 4 - 5 - const WEPAY_CLIENT_ID = 'wepay.client-id'; 6 - const WEPAY_CLIENT_SECRET = 'wepay.client-secret'; 7 - const WEPAY_ACCESS_TOKEN = 'wepay.access-token'; 8 - const WEPAY_ACCOUNT_ID = 'wepay.account-id'; 9 - 10 - public function isAcceptingLivePayments() { 11 - return preg_match('/^PRODUCTION_/', $this->getWePayAccessToken()); 12 - } 13 - 14 - public function getName() { 15 - return pht('WePay'); 16 - } 17 - 18 - public function getConfigureName() { 19 - return pht('Add WePay Payments Account'); 20 - } 21 - 22 - public function getConfigureDescription() { 23 - return pht( 24 - 'Allows you to accept credit or debit card payments with a '. 25 - 'wepay.com account.'); 26 - } 27 - 28 - public function getConfigureProvidesDescription() { 29 - return pht('This merchant accepts credit and debit cards via WePay.'); 30 - } 31 - 32 - public function getConfigureInstructions() { 33 - return pht( 34 - "To configure WePay, register or log in to an existing account on ". 35 - "[[https://wepay.com | wepay.com]] (for live payments) or ". 36 - "[[https://stage.wepay.com | stage.wepay.com]] (for testing). ". 37 - "Once logged in:\n\n". 38 - " - Create an API application if you don't already have one.\n". 39 - " - Click the API application name to go to the detail page.\n". 40 - " - Copy **Client ID**, **Client Secret**, **Access Token** and ". 41 - " **AccountID** from that page to the fields above.\n\n". 42 - "You can either use `stage.wepay.com` to retrieve test credentials, ". 43 - "or `wepay.com` to retrieve live credentials for accepting live ". 44 - "payments."); 45 - } 46 - 47 - public function canRunConfigurationTest() { 48 - return true; 49 - } 50 - 51 - public function runConfigurationTest() { 52 - $this->loadWePayAPILibraries(); 53 - 54 - WePay::useStaging( 55 - $this->getWePayClientID(), 56 - $this->getWePayClientSecret()); 57 - 58 - $wepay = new WePay($this->getWePayAccessToken()); 59 - $params = array( 60 - 'client_id' => $this->getWePayClientID(), 61 - 'client_secret' => $this->getWePayClientSecret(), 62 - ); 63 - 64 - $wepay->request('app', $params); 65 - } 66 - 67 - public function getAllConfigurableProperties() { 68 - return array( 69 - self::WEPAY_CLIENT_ID, 70 - self::WEPAY_CLIENT_SECRET, 71 - self::WEPAY_ACCESS_TOKEN, 72 - self::WEPAY_ACCOUNT_ID, 73 - ); 74 - } 75 - 76 - public function getAllConfigurableSecretProperties() { 77 - return array( 78 - self::WEPAY_CLIENT_SECRET, 79 - ); 80 - } 81 - 82 - public function processEditForm( 83 - AphrontRequest $request, 84 - array $values) { 85 - 86 - $errors = array(); 87 - $issues = array(); 88 - 89 - if (!strlen($values[self::WEPAY_CLIENT_ID])) { 90 - $errors[] = pht('WePay Client ID is required.'); 91 - $issues[self::WEPAY_CLIENT_ID] = pht('Required'); 92 - } 93 - 94 - if (!strlen($values[self::WEPAY_CLIENT_SECRET])) { 95 - $errors[] = pht('WePay Client Secret is required.'); 96 - $issues[self::WEPAY_CLIENT_SECRET] = pht('Required'); 97 - } 98 - 99 - if (!strlen($values[self::WEPAY_ACCESS_TOKEN])) { 100 - $errors[] = pht('WePay Access Token is required.'); 101 - $issues[self::WEPAY_ACCESS_TOKEN] = pht('Required'); 102 - } 103 - 104 - if (!strlen($values[self::WEPAY_ACCOUNT_ID])) { 105 - $errors[] = pht('WePay Account ID is required.'); 106 - $issues[self::WEPAY_ACCOUNT_ID] = pht('Required'); 107 - } 108 - 109 - return array($errors, $issues, $values); 110 - } 111 - 112 - public function extendEditForm( 113 - AphrontRequest $request, 114 - AphrontFormView $form, 115 - array $values, 116 - array $issues) { 117 - 118 - $form 119 - ->appendChild( 120 - id(new AphrontFormTextControl()) 121 - ->setName(self::WEPAY_CLIENT_ID) 122 - ->setValue($values[self::WEPAY_CLIENT_ID]) 123 - ->setError(idx($issues, self::WEPAY_CLIENT_ID, true)) 124 - ->setLabel(pht('WePay Client ID'))) 125 - ->appendChild( 126 - id(new AphrontFormTextControl()) 127 - ->setName(self::WEPAY_CLIENT_SECRET) 128 - ->setValue($values[self::WEPAY_CLIENT_SECRET]) 129 - ->setError(idx($issues, self::WEPAY_CLIENT_SECRET, true)) 130 - ->setLabel(pht('WePay Client Secret'))) 131 - ->appendChild( 132 - id(new AphrontFormTextControl()) 133 - ->setName(self::WEPAY_ACCESS_TOKEN) 134 - ->setValue($values[self::WEPAY_ACCESS_TOKEN]) 135 - ->setError(idx($issues, self::WEPAY_ACCESS_TOKEN, true)) 136 - ->setLabel(pht('WePay Access Token'))) 137 - ->appendChild( 138 - id(new AphrontFormTextControl()) 139 - ->setName(self::WEPAY_ACCOUNT_ID) 140 - ->setValue($values[self::WEPAY_ACCOUNT_ID]) 141 - ->setError(idx($issues, self::WEPAY_ACCOUNT_ID, true)) 142 - ->setLabel(pht('WePay Account ID'))); 143 - 144 - } 145 - 146 - public function getPaymentMethodDescription() { 147 - return pht('Credit or Debit Card'); 148 - } 149 - 150 - public function getPaymentMethodIcon() { 151 - return 'WePay'; 152 - } 153 - 154 - public function getPaymentMethodProviderDescription() { 155 - return 'WePay'; 156 - } 157 - 158 - protected function executeCharge( 159 - PhortunePaymentMethod $payment_method, 160 - PhortuneCharge $charge) { 161 - throw new Exception('!'); 162 - } 163 - 164 - private function getWePayClientID() { 165 - return $this 166 - ->getProviderConfig() 167 - ->getMetadataValue(self::WEPAY_CLIENT_ID); 168 - } 169 - 170 - private function getWePayClientSecret() { 171 - return $this 172 - ->getProviderConfig() 173 - ->getMetadataValue(self::WEPAY_CLIENT_SECRET); 174 - } 175 - 176 - private function getWePayAccessToken() { 177 - return $this 178 - ->getProviderConfig() 179 - ->getMetadataValue(self::WEPAY_ACCESS_TOKEN); 180 - } 181 - 182 - private function getWePayAccountID() { 183 - return $this 184 - ->getProviderConfig() 185 - ->getMetadataValue(self::WEPAY_ACCOUNT_ID); 186 - } 187 - 188 - protected function executeRefund( 189 - PhortuneCharge $charge, 190 - PhortuneCharge $refund) { 191 - $wepay = $this->loadWePayAPILibraries(); 192 - 193 - $checkout_id = $this->getWePayCheckoutID($charge); 194 - 195 - $params = array( 196 - 'checkout_id' => $checkout_id, 197 - 'refund_reason' => pht('Refund'), 198 - 'amount' => $refund->getAmountAsCurrency()->negate()->formatBareValue(), 199 - ); 200 - 201 - $wepay->request('checkout/refund', $params); 202 - } 203 - 204 - public function updateCharge(PhortuneCharge $charge) { 205 - $wepay = $this->loadWePayAPILibraries(); 206 - 207 - $params = array( 208 - 'checkout_id' => $this->getWePayCheckoutID($charge), 209 - ); 210 - $wepay_checkout = $wepay->request('checkout', $params); 211 - 212 - // TODO: Deal with disputes / chargebacks / surprising refunds. 213 - } 214 - 215 - 216 - /* -( One-Time Payments )-------------------------------------------------- */ 217 - 218 - public function canProcessOneTimePayments() { 219 - return true; 220 - } 221 - 222 - 223 - /* -( Controllers )-------------------------------------------------------- */ 224 - 225 - 226 - public function canRespondToControllerAction($action) { 227 - switch ($action) { 228 - case 'checkout': 229 - case 'charge': 230 - case 'cancel': 231 - return true; 232 - } 233 - return parent::canRespondToControllerAction(); 234 - } 235 - 236 - /** 237 - * @phutil-external-symbol class WePay 238 - */ 239 - public function processControllerRequest( 240 - PhortuneProviderActionController $controller, 241 - AphrontRequest $request) { 242 - $wepay = $this->loadWePayAPILibraries(); 243 - 244 - $viewer = $request->getUser(); 245 - 246 - $cart = $controller->loadCart($request->getInt('cartID')); 247 - if (!$cart) { 248 - return new Aphront404Response(); 249 - } 250 - 251 - $charge = $controller->loadActiveCharge($cart); 252 - switch ($controller->getAction()) { 253 - case 'checkout': 254 - if ($charge) { 255 - throw new Exception(pht('Cart is already charging!')); 256 - } 257 - break; 258 - case 'charge': 259 - case 'cancel': 260 - if (!$charge) { 261 - throw new Exception(pht('Cart is not charging yet!')); 262 - } 263 - break; 264 - } 265 - 266 - switch ($controller->getAction()) { 267 - case 'checkout': 268 - $return_uri = $this->getControllerURI( 269 - 'charge', 270 - array( 271 - 'cartID' => $cart->getID(), 272 - )); 273 - 274 - $cancel_uri = $this->getControllerURI( 275 - 'cancel', 276 - array( 277 - 'cartID' => $cart->getID(), 278 - )); 279 - 280 - $price = $cart->getTotalPriceAsCurrency(); 281 - 282 - $params = array( 283 - 'account_id' => $this->getWePayAccountID(), 284 - 'short_description' => $cart->getName(), 285 - 'type' => 'SERVICE', 286 - 'amount' => $price->formatBareValue(), 287 - 'long_description' => $cart->getName(), 288 - 'reference_id' => $cart->getPHID(), 289 - 'app_fee' => 0, 290 - 'fee_payer' => 'Payee', 291 - 'redirect_uri' => $return_uri, 292 - 'fallback_uri' => $cancel_uri, 293 - 294 - // NOTE: If we don't `auto_capture`, we might get a result back in 295 - // either an "authorized" or a "reserved" state. We can't capture 296 - // an "authorized" result, so just autocapture. 297 - 298 - 'auto_capture' => true, 299 - 'require_shipping' => 0, 300 - 'shipping_fee' => 0, 301 - 'charge_tax' => 0, 302 - 'mode' => 'regular', 303 - 304 - // TODO: We could accept bank accounts but the hold/capture rules 305 - // are not quite clear. Just accept credit cards for now. 306 - 'funding_sources' => 'cc', 307 - ); 308 - 309 - $charge = $cart->willApplyCharge($viewer, $this); 310 - $result = $wepay->request('checkout/create', $params); 311 - 312 - $cart->setMetadataValue('provider.checkoutURI', $result->checkout_uri); 313 - $cart->save(); 314 - 315 - $charge->setMetadataValue('wepay.checkoutID', $result->checkout_id); 316 - $charge->save(); 317 - 318 - $uri = new PhutilURI($result->checkout_uri); 319 - return id(new AphrontRedirectResponse()) 320 - ->setIsExternal(true) 321 - ->setURI($uri); 322 - case 'charge': 323 - if ($cart->getStatus() !== PhortuneCart::STATUS_PURCHASING) { 324 - return id(new AphrontRedirectResponse()) 325 - ->setURI($cart->getCheckoutURI()); 326 - } 327 - 328 - $checkout_id = $request->getInt('checkout_id'); 329 - $params = array( 330 - 'checkout_id' => $checkout_id, 331 - ); 332 - 333 - $checkout = $wepay->request('checkout', $params); 334 - if ($checkout->reference_id != $cart->getPHID()) { 335 - throw new Exception( 336 - pht('Checkout reference ID does not match cart PHID!')); 337 - } 338 - 339 - $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); 340 - switch ($checkout->state) { 341 - case 'authorized': 342 - case 'reserved': 343 - case 'captured': 344 - // TODO: Are these all really "done" states, and not "hold" 345 - // states? Cards and bank accounts both come back as "authorized" 346 - // on the staging environment. Figure out what happens in 347 - // production? 348 - 349 - $cart->didApplyCharge($charge); 350 - 351 - $response = id(new AphrontRedirectResponse())->setURI( 352 - $cart->getCheckoutURI()); 353 - break; 354 - default: 355 - // It's not clear if we can ever get here on the web workflow, 356 - // WePay doesn't seem to return back to us after a failure (the 357 - // workflow dead-ends instead). 358 - 359 - $cart->didFailCharge($charge); 360 - 361 - $response = $controller 362 - ->newDialog() 363 - ->setTitle(pht('Charge Failed')) 364 - ->appendParagraph( 365 - pht( 366 - 'Unable to make payment (checkout state is "%s").', 367 - $checkout->state)) 368 - ->addCancelButton($cart->getCheckoutURI(), pht('Continue')); 369 - break; 370 - } 371 - unset($unguarded); 372 - 373 - return $response; 374 - case 'cancel': 375 - // TODO: I don't know how it's possible to cancel out of a WePay 376 - // charge workflow. 377 - throw new Exception( 378 - pht('How did you get here? WePay has no cancel flow in its UI...?')); 379 - break; 380 - } 381 - 382 - throw new Exception( 383 - pht('Unsupported action "%s".', $controller->getAction())); 384 - } 385 - 386 - private function loadWePayAPILibraries() { 387 - $root = dirname(phutil_get_library_root('phabricator')); 388 - require_once $root.'/externals/wepay/wepay.php'; 389 - 390 - WePay::useStaging( 391 - $this->getWePayClientID(), 392 - $this->getWePayClientSecret()); 393 - 394 - return new WePay($this->getWePayAccessToken()); 395 - } 396 - 397 - private function getWePayCheckoutID(PhortuneCharge $charge) { 398 - $checkout_id = $charge->getMetadataValue('wepay.checkoutID'); 399 - if ($checkout_id === null) { 400 - throw new Exception(pht('No WePay Checkout ID present on charge!')); 401 - } 402 - return $checkout_id; 403 - } 404 - 405 - }