Update to drupal 8.0.0-rc1. For more information, see https://www.drupal.org/node/2582663

This commit is contained in:
Greg Anderson 2015-10-08 11:40:12 -07:00
parent eb34d130a8
commit f32e58e4b1
8476 changed files with 211648 additions and 170042 deletions

View file

@ -0,0 +1,291 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub;
use Traversable;
use Zend\Http\PhpEnvironment\Response as PhpResponse;
use Zend\Stdlib\ArrayUtils;
abstract class AbstractCallback implements CallbackInterface
{
/**
* An instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistenceInterface
* used to background save any verification tokens associated with a subscription
* or other.
*
* @var Model\SubscriptionPersistenceInterface
*/
protected $storage = null;
/**
* An instance of a class handling Http Responses. This is implemented in
* Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with
* (i.e. not inherited from) Zend\Controller\Response\Http.
*
* @var HttpResponse|PhpResponse
*/
protected $httpResponse = null;
/**
* The number of Subscribers for which any updates are on behalf of.
*
* @var int
*/
protected $subscriberCount = 1;
/**
* Constructor; accepts an array or Traversable object to preset
* options for the Subscriber without calling all supported setter
* methods in turn.
*
* @param array|Traversable $options Options array or Traversable object
*/
public function __construct($options = null)
{
if ($options !== null) {
$this->setOptions($options);
}
}
/**
* Process any injected configuration options
*
* @param array|Traversable $options Options array or Traversable object
* @return AbstractCallback
* @throws Exception\InvalidArgumentException
*/
public function setOptions($options)
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (!is_array($options)) {
throw new Exception\InvalidArgumentException('Array or Traversable object'
. 'expected, got ' . gettype($options));
}
if (is_array($options)) {
$this->setOptions($options);
}
if (array_key_exists('storage', $options)) {
$this->setStorage($options['storage']);
}
return $this;
}
/**
* Send the response, including all headers.
* If you wish to handle this via Zend\Http, use the getter methods
* to retrieve any data needed to be set on your HTTP Response object, or
* simply give this object the HTTP Response instance to work with for you!
*
* @return void
*/
public function sendResponse()
{
$this->getHttpResponse()->send();
}
/**
* Sets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used
* to background save any verification tokens associated with a subscription
* or other.
*
* @param Model\SubscriptionPersistenceInterface $storage
* @return AbstractCallback
*/
public function setStorage(Model\SubscriptionPersistenceInterface $storage)
{
$this->storage = $storage;
return $this;
}
/**
* Gets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used
* to background save any verification tokens associated with a subscription
* or other.
*
* @return Model\SubscriptionPersistenceInterface
* @throws Exception\RuntimeException
*/
public function getStorage()
{
if ($this->storage === null) {
throw new Exception\RuntimeException('No storage object has been'
. ' set that subclasses Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence');
}
return $this->storage;
}
/**
* An instance of a class handling Http Responses. This is implemented in
* Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with
* (i.e. not inherited from) Zend\Controller\Response\Http.
*
* @param HttpResponse|PhpResponse $httpResponse
* @return AbstractCallback
* @throws Exception\InvalidArgumentException
*/
public function setHttpResponse($httpResponse)
{
if (!$httpResponse instanceof HttpResponse && !$httpResponse instanceof PhpResponse) {
throw new Exception\InvalidArgumentException('HTTP Response object must'
. ' implement one of Zend\Feed\Pubsubhubbub\HttpResponse or'
. ' Zend\Http\PhpEnvironment\Response');
}
$this->httpResponse = $httpResponse;
return $this;
}
/**
* An instance of a class handling Http Responses. This is implemented in
* Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with
* (i.e. not inherited from) Zend\Controller\Response\Http.
*
* @return HttpResponse|PhpResponse
*/
public function getHttpResponse()
{
if ($this->httpResponse === null) {
$this->httpResponse = new HttpResponse;
}
return $this->httpResponse;
}
/**
* Sets the number of Subscribers for which any updates are on behalf of.
* In other words, is this class serving one or more subscribers? How many?
* Defaults to 1 if left unchanged.
*
* @param string|int $count
* @return AbstractCallback
* @throws Exception\InvalidArgumentException
*/
public function setSubscriberCount($count)
{
$count = intval($count);
if ($count <= 0) {
throw new Exception\InvalidArgumentException('Subscriber count must be'
. ' greater than zero');
}
$this->subscriberCount = $count;
return $this;
}
/**
* Gets the number of Subscribers for which any updates are on behalf of.
* In other words, is this class serving one or more subscribers? How many?
*
* @return int
*/
public function getSubscriberCount()
{
return $this->subscriberCount;
}
/**
* Attempt to detect the callback URL (specifically the path forward)
* @return string
*/
protected function _detectCallbackUrl()
{
$callbackUrl = '';
if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) {
$callbackUrl = $_SERVER['HTTP_X_ORIGINAL_URL'];
} elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
$callbackUrl = $_SERVER['HTTP_X_REWRITE_URL'];
} elseif (isset($_SERVER['REQUEST_URI'])) {
$callbackUrl = $_SERVER['REQUEST_URI'];
$scheme = 'http';
if ($_SERVER['HTTPS'] == 'on') {
$scheme = 'https';
}
$schemeAndHttpHost = $scheme . '://' . $this->_getHttpHost();
if (strpos($callbackUrl, $schemeAndHttpHost) === 0) {
$callbackUrl = substr($callbackUrl, strlen($schemeAndHttpHost));
}
} elseif (isset($_SERVER['ORIG_PATH_INFO'])) {
$callbackUrl= $_SERVER['ORIG_PATH_INFO'];
if (!empty($_SERVER['QUERY_STRING'])) {
$callbackUrl .= '?' . $_SERVER['QUERY_STRING'];
}
}
return $callbackUrl;
}
/**
* Get the HTTP host
*
* @return string
*/
protected function _getHttpHost()
{
if (!empty($_SERVER['HTTP_HOST'])) {
return $_SERVER['HTTP_HOST'];
}
$scheme = 'http';
if ($_SERVER['HTTPS'] == 'on') {
$scheme = 'https';
}
$name = $_SERVER['SERVER_NAME'];
$port = $_SERVER['SERVER_PORT'];
if (($scheme == 'http' && $port == 80)
|| ($scheme == 'https' && $port == 443)
) {
return $name;
}
return $name . ':' . $port;
}
/**
* Retrieve a Header value from either $_SERVER or Apache
*
* @param string $header
* @return bool|string
*/
protected function _getHeader($header)
{
$temp = strtoupper(str_replace('-', '_', $header));
if (!empty($_SERVER[$temp])) {
return $_SERVER[$temp];
}
$temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
if (!empty($_SERVER[$temp])) {
return $_SERVER[$temp];
}
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
if (!empty($headers[$header])) {
return $headers[$header];
}
}
return false;
}
/**
* Return the raw body of the request
*
* @return string|false Raw body, or false if not present
*/
protected function _getRawBody()
{
$body = file_get_contents('php://input');
if (strlen(trim($body)) == 0 && isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
$body = $GLOBALS['HTTP_RAW_POST_DATA'];
}
if (strlen(trim($body)) > 0) {
return $body;
}
return false;
}
}

View file

@ -0,0 +1,51 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub;
interface CallbackInterface
{
/**
* Handle any callback from a Hub Server responding to a subscription or
* unsubscription request. This should be the Hub Server confirming the
* the request prior to taking action on it.
*
* @param array $httpData GET/POST data if available and not in $_GET/POST
* @param bool $sendResponseNow Whether to send response now or when asked
*/
public function handle(array $httpData = null, $sendResponseNow = false);
/**
* Send the response, including all headers.
* If you wish to handle this via Zend\Mvc\Controller, use the getter methods
* to retrieve any data needed to be set on your HTTP Response object, or
* simply give this object the HTTP Response instance to work with for you!
*
* @return void
*/
public function sendResponse();
/**
* An instance of a class handling Http Responses. This is implemented in
* Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with
* (i.e. not inherited from) Zend\Feed\Pubsubhubbub\AbstractCallback.
*
* @param HttpResponse|\Zend\Http\PhpEnvironment\Response $httpResponse
*/
public function setHttpResponse($httpResponse);
/**
* An instance of a class handling Http Responses. This is implemented in
* Zend\Feed\Pubsubhubbub\HttpResponse which shares an unenforced interface with
* (i.e. not inherited from) Zend\Feed\Pubsubhubbub\AbstractCallback.
*
* @return HttpResponse|\Zend\Http\PhpEnvironment\Response
*/
public function getHttpResponse();
}

View file

@ -0,0 +1,16 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub\Exception;
use Zend\Feed\Exception\ExceptionInterface as Exception;
interface ExceptionInterface extends Exception
{
}

View file

@ -0,0 +1,16 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub\Exception;
use Zend\Feed\Exception;
class InvalidArgumentException extends Exception\InvalidArgumentException implements ExceptionInterface
{
}

View file

@ -0,0 +1,16 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub\Exception;
use Zend\Feed\Exception;
class RuntimeException extends Exception\RuntimeException implements ExceptionInterface
{
}

View file

@ -0,0 +1,211 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub;
class HttpResponse
{
/**
* The body of any response to the current callback request
*
* @var string
*/
protected $content = '';
/**
* Array of headers. Each header is an array with keys 'name' and 'value'
*
* @var array
*/
protected $headers = [];
/**
* HTTP response code to use in headers
*
* @var int
*/
protected $statusCode = 200;
/**
* Send the response, including all headers
*
* @return void
*/
public function send()
{
$this->sendHeaders();
echo $this->getContent();
}
/**
* Send all headers
*
* Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code}
* has been specified, it is sent with the first header.
*
* @return void
*/
public function sendHeaders()
{
if (count($this->headers) || (200 != $this->statusCode)) {
$this->canSendHeaders(true);
} elseif (200 == $this->statusCode) {
return;
}
$httpCodeSent = false;
foreach ($this->headers as $header) {
if (!$httpCodeSent && $this->statusCode) {
header($header['name'] . ': ' . $header['value'], $header['replace'], $this->statusCode);
$httpCodeSent = true;
} else {
header($header['name'] . ': ' . $header['value'], $header['replace']);
}
}
if (!$httpCodeSent) {
header('HTTP/1.1 ' . $this->statusCode);
}
}
/**
* Set a header
*
* If $replace is true, replaces any headers already defined with that
* $name.
*
* @param string $name
* @param string $value
* @param bool $replace
* @return \Zend\Feed\PubSubHubbub\HttpResponse
*/
public function setHeader($name, $value, $replace = false)
{
$name = $this->_normalizeHeader($name);
$value = (string) $value;
if ($replace) {
foreach ($this->headers as $key => $header) {
if ($name == $header['name']) {
unset($this->headers[$key]);
}
}
}
$this->headers[] = [
'name' => $name,
'value' => $value,
'replace' => $replace,
];
return $this;
}
/**
* Check if a specific Header is set and return its value
*
* @param string $name
* @return string|null
*/
public function getHeader($name)
{
$name = $this->_normalizeHeader($name);
foreach ($this->headers as $header) {
if ($header['name'] == $name) {
return $header['value'];
}
}
}
/**
* Return array of headers; see {@link $headers} for format
*
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Can we send headers?
*
* @param bool $throw Whether or not to throw an exception if headers have been sent; defaults to false
* @return HttpResponse
* @throws Exception\RuntimeException
*/
public function canSendHeaders($throw = false)
{
$ok = headers_sent($file, $line);
if ($ok && $throw) {
throw new Exception\RuntimeException('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
}
return !$ok;
}
/**
* Set HTTP response code to use with headers
*
* @param int $code
* @return HttpResponse
* @throws Exception\InvalidArgumentException
*/
public function setStatusCode($code)
{
if (!is_int($code) || (100 > $code) || (599 < $code)) {
throw new Exception\InvalidArgumentException('Invalid HTTP response'
. ' code:' . $code);
}
$this->statusCode = $code;
return $this;
}
/**
* Retrieve HTTP response code
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* Set body content
*
* @param string $content
* @return \Zend\Feed\PubSubHubbub\HttpResponse
*/
public function setContent($content)
{
$this->content = (string) $content;
$this->setHeader('content-length', strlen($content));
return $this;
}
/**
* Return the body content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Normalizes a header name to X-Capitalized-Names
*
* @param string $name
* @return string
*/
protected function _normalizeHeader($name)
{
$filtered = str_replace(['-', '_'], ' ', (string) $name);
$filtered = ucwords(strtolower($filtered));
$filtered = str_replace(' ', '-', $filtered);
return $filtered;
}
}

View file

@ -0,0 +1,39 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\TableGateway\TableGatewayInterface;
class AbstractModel
{
/**
* Zend\Db\TableGateway\TableGatewayInterface instance to host database methods
*
* @var TableGatewayInterface
*/
protected $db = null;
/**
* Constructor
*
* @param null|TableGatewayInterface $tableGateway
*/
public function __construct(TableGatewayInterface $tableGateway = null)
{
if ($tableGateway === null) {
$parts = explode('\\', get_class($this));
$table = strtolower(array_pop($parts));
$this->db = new TableGateway($table, null);
} else {
$this->db = $tableGateway;
}
}
}

View file

@ -0,0 +1,142 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub\Model;
use DateInterval;
use DateTime;
use Zend\Feed\PubSubHubbub;
class Subscription extends AbstractModel implements SubscriptionPersistenceInterface
{
/**
* Common DateTime object to assist with unit testing
*
* @var DateTime
*/
protected $now;
/**
* Save subscription to RDMBS
*
* @param array $data
* @return bool
* @throws PubSubHubbub\Exception\InvalidArgumentException
*/
public function setSubscription(array $data)
{
if (!isset($data['id'])) {
throw new PubSubHubbub\Exception\InvalidArgumentException(
'ID must be set before attempting a save'
);
}
$result = $this->db->select(['id' => $data['id']]);
if ($result && (0 < count($result))) {
$data['created_time'] = $result->current()->created_time;
$now = $this->getNow();
if (array_key_exists('lease_seconds', $data)
&& $data['lease_seconds']
) {
$data['expiration_time'] = $now->add(new DateInterval('PT' . $data['lease_seconds'] . 'S'))
->format('Y-m-d H:i:s');
}
$this->db->update(
$data,
['id' => $data['id']]
);
return false;
}
$this->db->insert($data);
return true;
}
/**
* Get subscription by ID/key
*
* @param string $key
* @return array
* @throws PubSubHubbub\Exception\InvalidArgumentException
*/
public function getSubscription($key)
{
if (empty($key) || !is_string($key)) {
throw new PubSubHubbub\Exception\InvalidArgumentException('Invalid parameter "key"'
.' of "' . $key . '" must be a non-empty string');
}
$result = $this->db->select(['id' => $key]);
if (count($result)) {
return $result->current()->getArrayCopy();
}
return false;
}
/**
* Determine if a subscription matching the key exists
*
* @param string $key
* @return bool
* @throws PubSubHubbub\Exception\InvalidArgumentException
*/
public function hasSubscription($key)
{
if (empty($key) || !is_string($key)) {
throw new PubSubHubbub\Exception\InvalidArgumentException('Invalid parameter "key"'
.' of "' . $key . '" must be a non-empty string');
}
$result = $this->db->select(['id' => $key]);
if (count($result)) {
return true;
}
return false;
}
/**
* Delete a subscription
*
* @param string $key
* @return bool
*/
public function deleteSubscription($key)
{
$result = $this->db->select(['id' => $key]);
if (count($result)) {
$this->db->delete(
['id' => $key]
);
return true;
}
return false;
}
/**
* Get a new DateTime or the one injected for testing
*
* @return DateTime
*/
public function getNow()
{
if (null === $this->now) {
return new DateTime();
}
return $this->now;
}
/**
* Set a DateTime instance for assisting with unit testing
*
* @param DateTime $now
* @return Subscription
*/
public function setNow(DateTime $now)
{
$this->now = $now;
return $this;
}
}

View file

@ -0,0 +1,45 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub\Model;
interface SubscriptionPersistenceInterface
{
/**
* Save subscription to RDMBS
*
* @param array $data The key must be stored here as a $data['id'] entry
* @return bool
*/
public function setSubscription(array $data);
/**
* Get subscription by ID/key
*
* @param string $key
* @return array
*/
public function getSubscription($key);
/**
* Determine if a subscription matching the key exists
*
* @param string $key
* @return bool
*/
public function hasSubscription($key);
/**
* Delete a subscription
*
* @param string $key
* @return bool
*/
public function deleteSubscription($key);
}

View file

@ -0,0 +1,147 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub;
use Zend\Escaper\Escaper;
use Zend\Feed\Reader;
use Zend\Http;
class PubSubHubbub
{
/**
* Verification Modes
*/
const VERIFICATION_MODE_SYNC = 'sync';
const VERIFICATION_MODE_ASYNC = 'async';
/**
* Subscription States
*/
const SUBSCRIPTION_VERIFIED = 'verified';
const SUBSCRIPTION_NOTVERIFIED = 'not_verified';
const SUBSCRIPTION_TODELETE = 'to_delete';
/**
* @var Escaper
*/
protected static $escaper;
/**
* Singleton instance if required of the HTTP client
*
* @var Http\Client
*/
protected static $httpClient = null;
/**
* Simple utility function which imports any feed URL and
* determines the existence of Hub Server endpoints. This works
* best if directly given an instance of Zend\Feed\Reader\Atom|Rss
* to leverage off.
*
* @param \Zend\Feed\Reader\Feed\AbstractFeed|string $source
* @return array
* @throws Exception\InvalidArgumentException
*/
public static function detectHubs($source)
{
if (is_string($source)) {
$feed = Reader\Reader::import($source);
} elseif ($source instanceof Reader\Feed\AbstractFeed) {
$feed = $source;
} else {
throw new Exception\InvalidArgumentException('The source parameter was'
. ' invalid, i.e. not a URL string or an instance of type'
. ' Zend\Feed\Reader\Feed\AbstractFeed');
}
return $feed->getHubs();
}
/**
* Allows the external environment to make ZendOAuth use a specific
* Client instance.
*
* @param Http\Client $httpClient
* @return void
*/
public static function setHttpClient(Http\Client $httpClient)
{
static::$httpClient = $httpClient;
}
/**
* Return the singleton instance of the HTTP Client. Note that
* the instance is reset and cleared of previous parameters GET/POST.
* Headers are NOT reset but handled by this component if applicable.
*
* @return Http\Client
*/
public static function getHttpClient()
{
if (!isset(static::$httpClient)) {
static::$httpClient = new Http\Client;
} else {
static::$httpClient->resetParameters();
}
return static::$httpClient;
}
/**
* Simple mechanism to delete the entire singleton HTTP Client instance
* which forces a new instantiation for subsequent requests.
*
* @return void
*/
public static function clearHttpClient()
{
static::$httpClient = null;
}
/**
* Set the Escaper instance
*
* If null, resets the instance
*
* @param null|Escaper $escaper
*/
public static function setEscaper(Escaper $escaper = null)
{
static::$escaper = $escaper;
}
/**
* Get the Escaper instance
*
* If none registered, lazy-loads an instance.
*
* @return Escaper
*/
public static function getEscaper()
{
if (null === static::$escaper) {
static::setEscaper(new Escaper());
}
return static::$escaper;
}
/**
* RFC 3986 safe url encoding method
*
* @param string $string
* @return string
*/
public static function urlencode($string)
{
$escaper = static::getEscaper();
$rawencoded = $escaper->escapeUrl($string);
$rfcencoded = str_replace('%7E', '~', $rawencoded);
return $rfcencoded;
}
}

View file

@ -0,0 +1,397 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub;
use Traversable;
use Zend\Feed\Uri;
use Zend\Http\Request as HttpRequest;
use Zend\Stdlib\ArrayUtils;
class Publisher
{
/**
* An array of URLs for all Hub Servers used by the Publisher, and to
* which all topic update notifications will be sent.
*
* @var array
*/
protected $hubUrls = [];
/**
* An array of topic (Atom or RSS feed) URLs which have been updated and
* whose updated status will be notified to all Hub Servers.
*
* @var array
*/
protected $updatedTopicUrls = [];
/**
* An array of any errors including keys for 'response', 'hubUrl'.
* The response is the actual Zend\Http\Response object.
*
* @var array
*/
protected $errors = [];
/**
* An array of topic (Atom or RSS feed) URLs which have been updated and
* whose updated status will be notified to all Hub Servers.
*
* @var array
*/
protected $parameters = [];
/**
* Constructor; accepts an array or Zend\Config\Config instance to preset
* options for the Publisher without calling all supported setter
* methods in turn.
*
* @param array|Traversable $options
*/
public function __construct($options = null)
{
if ($options !== null) {
$this->setOptions($options);
}
}
/**
* Process any injected configuration options
*
* @param array|Traversable $options Options array or Traversable object
* @return Publisher
* @throws Exception\InvalidArgumentException
*/
public function setOptions($options)
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (!is_array($options)) {
throw new Exception\InvalidArgumentException('Array or Traversable object'
. 'expected, got ' . gettype($options));
}
if (array_key_exists('hubUrls', $options)) {
$this->addHubUrls($options['hubUrls']);
}
if (array_key_exists('updatedTopicUrls', $options)) {
$this->addUpdatedTopicUrls($options['updatedTopicUrls']);
}
if (array_key_exists('parameters', $options)) {
$this->setParameters($options['parameters']);
}
return $this;
}
/**
* Add a Hub Server URL supported by Publisher
*
* @param string $url
* @return Publisher
* @throws Exception\InvalidArgumentException
*/
public function addHubUrl($url)
{
if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) {
throw new Exception\InvalidArgumentException('Invalid parameter "url"'
. ' of "' . $url . '" must be a non-empty string and a valid'
. 'URL');
}
$this->hubUrls[] = $url;
return $this;
}
/**
* Add an array of Hub Server URLs supported by Publisher
*
* @param array $urls
* @return Publisher
*/
public function addHubUrls(array $urls)
{
foreach ($urls as $url) {
$this->addHubUrl($url);
}
return $this;
}
/**
* Remove a Hub Server URL
*
* @param string $url
* @return Publisher
*/
public function removeHubUrl($url)
{
if (!in_array($url, $this->getHubUrls())) {
return $this;
}
$key = array_search($url, $this->hubUrls);
unset($this->hubUrls[$key]);
return $this;
}
/**
* Return an array of unique Hub Server URLs currently available
*
* @return array
*/
public function getHubUrls()
{
$this->hubUrls = array_unique($this->hubUrls);
return $this->hubUrls;
}
/**
* Add a URL to a topic (Atom or RSS feed) which has been updated
*
* @param string $url
* @return Publisher
* @throws Exception\InvalidArgumentException
*/
public function addUpdatedTopicUrl($url)
{
if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) {
throw new Exception\InvalidArgumentException('Invalid parameter "url"'
. ' of "' . $url . '" must be a non-empty string and a valid'
. 'URL');
}
$this->updatedTopicUrls[] = $url;
return $this;
}
/**
* Add an array of Topic URLs which have been updated
*
* @param array $urls
* @return Publisher
*/
public function addUpdatedTopicUrls(array $urls)
{
foreach ($urls as $url) {
$this->addUpdatedTopicUrl($url);
}
return $this;
}
/**
* Remove an updated topic URL
*
* @param string $url
* @return Publisher
*/
public function removeUpdatedTopicUrl($url)
{
if (!in_array($url, $this->getUpdatedTopicUrls())) {
return $this;
}
$key = array_search($url, $this->updatedTopicUrls);
unset($this->updatedTopicUrls[$key]);
return $this;
}
/**
* Return an array of unique updated topic URLs currently available
*
* @return array
*/
public function getUpdatedTopicUrls()
{
$this->updatedTopicUrls = array_unique($this->updatedTopicUrls);
return $this->updatedTopicUrls;
}
/**
* Notifies a single Hub Server URL of changes
*
* @param string $url The Hub Server's URL
* @return void
* @throws Exception\InvalidArgumentException
* @throws Exception\RuntimeException
*/
public function notifyHub($url)
{
if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) {
throw new Exception\InvalidArgumentException('Invalid parameter "url"'
. ' of "' . $url . '" must be a non-empty string and a valid'
. 'URL');
}
$client = $this->_getHttpClient();
$client->setUri($url);
$response = $client->getResponse();
if ($response->getStatusCode() !== 204) {
throw new Exception\RuntimeException('Notification to Hub Server '
. 'at "' . $url . '" appears to have failed with a status code of "'
. $response->getStatusCode() . '" and message "'
. $response->getContent() . '"');
}
}
/**
* Notifies all Hub Server URLs of changes
*
* If a Hub notification fails, certain data will be retained in an
* an array retrieved using getErrors(), if a failure occurs for any Hubs
* the isSuccess() check will return FALSE. This method is designed not
* to needlessly fail with an Exception/Error unless from Zend\Http\Client.
*
* @return void
* @throws Exception\RuntimeException
*/
public function notifyAll()
{
$client = $this->_getHttpClient();
$hubs = $this->getHubUrls();
if (empty($hubs)) {
throw new Exception\RuntimeException('No Hub Server URLs'
. ' have been set so no notifications can be sent');
}
$this->errors = [];
foreach ($hubs as $url) {
$client->setUri($url);
$response = $client->getResponse();
if ($response->getStatusCode() !== 204) {
$this->errors[] = [
'response' => $response,
'hubUrl' => $url
];
}
}
}
/**
* Add an optional parameter to the update notification requests
*
* @param string $name
* @param string|null $value
* @return Publisher
* @throws Exception\InvalidArgumentException
*/
public function setParameter($name, $value = null)
{
if (is_array($name)) {
$this->setParameters($name);
return $this;
}
if (empty($name) || !is_string($name)) {
throw new Exception\InvalidArgumentException('Invalid parameter "name"'
. ' of "' . $name . '" must be a non-empty string');
}
if ($value === null) {
$this->removeParameter($name);
return $this;
}
if (empty($value) || (!is_string($value) && $value !== null)) {
throw new Exception\InvalidArgumentException('Invalid parameter "value"'
. ' of "' . $value . '" must be a non-empty string');
}
$this->parameters[$name] = $value;
return $this;
}
/**
* Add an optional parameter to the update notification requests
*
* @param array $parameters
* @return Publisher
*/
public function setParameters(array $parameters)
{
foreach ($parameters as $name => $value) {
$this->setParameter($name, $value);
}
return $this;
}
/**
* Remove an optional parameter for the notification requests
*
* @param string $name
* @return Publisher
* @throws Exception\InvalidArgumentException
*/
public function removeParameter($name)
{
if (empty($name) || !is_string($name)) {
throw new Exception\InvalidArgumentException('Invalid parameter "name"'
. ' of "' . $name . '" must be a non-empty string');
}
if (array_key_exists($name, $this->parameters)) {
unset($this->parameters[$name]);
}
return $this;
}
/**
* Return an array of optional parameters for notification requests
*
* @return array
*/
public function getParameters()
{
return $this->parameters;
}
/**
* Returns a boolean indicator of whether the notifications to Hub
* Servers were ALL successful. If even one failed, FALSE is returned.
*
* @return bool
*/
public function isSuccess()
{
return !(count($this->errors) != 0);
}
/**
* Return an array of errors met from any failures, including keys:
* 'response' => the Zend\Http\Response object from the failure
* 'hubUrl' => the URL of the Hub Server whose notification failed
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* Get a basic prepared HTTP client for use
*
* @return \Zend\Http\Client
* @throws Exception\RuntimeException
*/
protected function _getHttpClient()
{
$client = PubSubHubbub::getHttpClient();
$client->setMethod(HttpRequest::METHOD_POST);
$client->setOptions([
'useragent' => 'Zend_Feed_Pubsubhubbub_Publisher/' . Version::VERSION,
]);
$params = [];
$params[] = 'hub.mode=publish';
$topics = $this->getUpdatedTopicUrls();
if (empty($topics)) {
throw new Exception\RuntimeException('No updated topic URLs'
. ' have been set');
}
foreach ($topics as $topicUrl) {
$params[] = 'hub.url=' . urlencode($topicUrl);
}
$optParams = $this->getParameters();
foreach ($optParams as $name => $value) {
$params[] = urlencode($name) . '=' . urlencode($value);
}
$paramString = implode('&', $params);
$client->setRawBody($paramString);
return $client;
}
}

View file

@ -0,0 +1,837 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub;
use DateInterval;
use DateTime;
use Traversable;
use Zend\Feed\Uri;
use Zend\Http\Request as HttpRequest;
use Zend\Stdlib\ArrayUtils;
class Subscriber
{
/**
* An array of URLs for all Hub Servers to subscribe/unsubscribe.
*
* @var array
*/
protected $hubUrls = [];
/**
* An array of optional parameters to be included in any
* (un)subscribe requests.
*
* @var array
*/
protected $parameters = [];
/**
* The URL of the topic (Rss or Atom feed) which is the subject of
* our current intent to subscribe to/unsubscribe from updates from
* the currently configured Hub Servers.
*
* @var string
*/
protected $topicUrl = '';
/**
* The URL Hub Servers must use when communicating with this Subscriber
*
* @var string
*/
protected $callbackUrl = '';
/**
* The number of seconds for which the subscriber would like to have the
* subscription active. Defaults to null, i.e. not sent, to setup a
* permanent subscription if possible.
*
* @var int
*/
protected $leaseSeconds = null;
/**
* The preferred verification mode (sync or async). By default, this
* Subscriber prefers synchronous verification, but is considered
* desirable to support asynchronous verification if possible.
*
* Zend\Feed\Pubsubhubbub\Subscriber will always send both modes, whose
* order of occurrence in the parameter list determines this preference.
*
* @var string
*/
protected $preferredVerificationMode = PubSubHubbub::VERIFICATION_MODE_SYNC;
/**
* An array of any errors including keys for 'response', 'hubUrl'.
* The response is the actual Zend\Http\Response object.
*
* @var array
*/
protected $errors = [];
/**
* An array of Hub Server URLs for Hubs operating at this time in
* asynchronous verification mode.
*
* @var array
*/
protected $asyncHubs = [];
/**
* An instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used to background
* save any verification tokens associated with a subscription or other.
*
* @var \Zend\Feed\PubSubHubbub\Model\SubscriptionPersistenceInterface
*/
protected $storage = null;
/**
* An array of authentication credentials for HTTP Basic Authentication
* if required by specific Hubs. The array is indexed by Hub Endpoint URI
* and the value is a simple array of the username and password to apply.
*
* @var array
*/
protected $authentications = [];
/**
* Tells the Subscriber to append any subscription identifier to the path
* of the base Callback URL. E.g. an identifier "subkey1" would be added
* to the callback URL "http://www.example.com/callback" to create a subscription
* specific Callback URL of "http://www.example.com/callback/subkey1".
*
* This is required for all Hubs using the Pubsubhubbub 0.1 Specification.
* It should be manually intercepted and passed to the Callback class using
* Zend\Feed\Pubsubhubbub\Subscriber\Callback::setSubscriptionKey(). Will
* require a route in the form "callback/:subkey" to allow the parameter be
* retrieved from an action using the Zend\Controller\Action::\getParam()
* method.
*
* @var string
*/
protected $usePathParameter = false;
/**
* Constructor; accepts an array or Traversable instance to preset
* options for the Subscriber without calling all supported setter
* methods in turn.
*
* @param array|Traversable $options
*/
public function __construct($options = null)
{
if ($options !== null) {
$this->setOptions($options);
}
}
/**
* Process any injected configuration options
*
* @param array|Traversable $options
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function setOptions($options)
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (!is_array($options)) {
throw new Exception\InvalidArgumentException('Array or Traversable object'
. 'expected, got ' . gettype($options));
}
if (array_key_exists('hubUrls', $options)) {
$this->addHubUrls($options['hubUrls']);
}
if (array_key_exists('callbackUrl', $options)) {
$this->setCallbackUrl($options['callbackUrl']);
}
if (array_key_exists('topicUrl', $options)) {
$this->setTopicUrl($options['topicUrl']);
}
if (array_key_exists('storage', $options)) {
$this->setStorage($options['storage']);
}
if (array_key_exists('leaseSeconds', $options)) {
$this->setLeaseSeconds($options['leaseSeconds']);
}
if (array_key_exists('parameters', $options)) {
$this->setParameters($options['parameters']);
}
if (array_key_exists('authentications', $options)) {
$this->addAuthentications($options['authentications']);
}
if (array_key_exists('usePathParameter', $options)) {
$this->usePathParameter($options['usePathParameter']);
}
if (array_key_exists('preferredVerificationMode', $options)) {
$this->setPreferredVerificationMode(
$options['preferredVerificationMode']
);
}
return $this;
}
/**
* Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe
* event will relate
*
* @param string $url
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function setTopicUrl($url)
{
if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) {
throw new Exception\InvalidArgumentException('Invalid parameter "url"'
.' of "' . $url . '" must be a non-empty string and a valid'
.' URL');
}
$this->topicUrl = $url;
return $this;
}
/**
* Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe
* event will relate
*
* @return string
* @throws Exception\RuntimeException
*/
public function getTopicUrl()
{
if (empty($this->topicUrl)) {
throw new Exception\RuntimeException('A valid Topic (RSS or Atom'
. ' feed) URL MUST be set before attempting any operation');
}
return $this->topicUrl;
}
/**
* Set the number of seconds for which any subscription will remain valid
*
* @param int $seconds
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function setLeaseSeconds($seconds)
{
$seconds = intval($seconds);
if ($seconds <= 0) {
throw new Exception\InvalidArgumentException('Expected lease seconds'
. ' must be an integer greater than zero');
}
$this->leaseSeconds = $seconds;
return $this;
}
/**
* Get the number of lease seconds on subscriptions
*
* @return int
*/
public function getLeaseSeconds()
{
return $this->leaseSeconds;
}
/**
* Set the callback URL to be used by Hub Servers when communicating with
* this Subscriber
*
* @param string $url
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function setCallbackUrl($url)
{
if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) {
throw new Exception\InvalidArgumentException('Invalid parameter "url"'
. ' of "' . $url . '" must be a non-empty string and a valid'
. ' URL');
}
$this->callbackUrl = $url;
return $this;
}
/**
* Get the callback URL to be used by Hub Servers when communicating with
* this Subscriber
*
* @return string
* @throws Exception\RuntimeException
*/
public function getCallbackUrl()
{
if (empty($this->callbackUrl)) {
throw new Exception\RuntimeException('A valid Callback URL MUST be'
. ' set before attempting any operation');
}
return $this->callbackUrl;
}
/**
* Set preferred verification mode (sync or async). By default, this
* Subscriber prefers synchronous verification, but does support
* asynchronous if that's the Hub Server's utilised mode.
*
* Zend\Feed\Pubsubhubbub\Subscriber will always send both modes, whose
* order of occurrence in the parameter list determines this preference.
*
* @param string $mode Should be 'sync' or 'async'
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function setPreferredVerificationMode($mode)
{
if ($mode !== PubSubHubbub::VERIFICATION_MODE_SYNC
&& $mode !== PubSubHubbub::VERIFICATION_MODE_ASYNC
) {
throw new Exception\InvalidArgumentException('Invalid preferred'
. ' mode specified: "' . $mode . '" but should be one of'
. ' Zend\Feed\Pubsubhubbub::VERIFICATION_MODE_SYNC or'
. ' Zend\Feed\Pubsubhubbub::VERIFICATION_MODE_ASYNC');
}
$this->preferredVerificationMode = $mode;
return $this;
}
/**
* Get preferred verification mode (sync or async).
*
* @return string
*/
public function getPreferredVerificationMode()
{
return $this->preferredVerificationMode;
}
/**
* Add a Hub Server URL supported by Publisher
*
* @param string $url
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function addHubUrl($url)
{
if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) {
throw new Exception\InvalidArgumentException('Invalid parameter "url"'
. ' of "' . $url . '" must be a non-empty string and a valid'
. ' URL');
}
$this->hubUrls[] = $url;
return $this;
}
/**
* Add an array of Hub Server URLs supported by Publisher
*
* @param array $urls
* @return Subscriber
*/
public function addHubUrls(array $urls)
{
foreach ($urls as $url) {
$this->addHubUrl($url);
}
return $this;
}
/**
* Remove a Hub Server URL
*
* @param string $url
* @return Subscriber
*/
public function removeHubUrl($url)
{
if (!in_array($url, $this->getHubUrls())) {
return $this;
}
$key = array_search($url, $this->hubUrls);
unset($this->hubUrls[$key]);
return $this;
}
/**
* Return an array of unique Hub Server URLs currently available
*
* @return array
*/
public function getHubUrls()
{
$this->hubUrls = array_unique($this->hubUrls);
return $this->hubUrls;
}
/**
* Add authentication credentials for a given URL
*
* @param string $url
* @param array $authentication
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function addAuthentication($url, array $authentication)
{
if (empty($url) || !is_string($url) || !Uri::factory($url)->isValid()) {
throw new Exception\InvalidArgumentException('Invalid parameter "url"'
. ' of "' . $url . '" must be a non-empty string and a valid'
. ' URL');
}
$this->authentications[$url] = $authentication;
return $this;
}
/**
* Add authentication credentials for hub URLs
*
* @param array $authentications
* @return Subscriber
*/
public function addAuthentications(array $authentications)
{
foreach ($authentications as $url => $authentication) {
$this->addAuthentication($url, $authentication);
}
return $this;
}
/**
* Get all hub URL authentication credentials
*
* @return array
*/
public function getAuthentications()
{
return $this->authentications;
}
/**
* Set flag indicating whether or not to use a path parameter
*
* @param bool $bool
* @return Subscriber
*/
public function usePathParameter($bool = true)
{
$this->usePathParameter = $bool;
return $this;
}
/**
* Add an optional parameter to the (un)subscribe requests
*
* @param string $name
* @param string|null $value
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function setParameter($name, $value = null)
{
if (is_array($name)) {
$this->setParameters($name);
return $this;
}
if (empty($name) || !is_string($name)) {
throw new Exception\InvalidArgumentException('Invalid parameter "name"'
. ' of "' . $name . '" must be a non-empty string');
}
if ($value === null) {
$this->removeParameter($name);
return $this;
}
if (empty($value) || (!is_string($value) && $value !== null)) {
throw new Exception\InvalidArgumentException('Invalid parameter "value"'
. ' of "' . $value . '" must be a non-empty string');
}
$this->parameters[$name] = $value;
return $this;
}
/**
* Add an optional parameter to the (un)subscribe requests
*
* @param array $parameters
* @return Subscriber
*/
public function setParameters(array $parameters)
{
foreach ($parameters as $name => $value) {
$this->setParameter($name, $value);
}
return $this;
}
/**
* Remove an optional parameter for the (un)subscribe requests
*
* @param string $name
* @return Subscriber
* @throws Exception\InvalidArgumentException
*/
public function removeParameter($name)
{
if (empty($name) || !is_string($name)) {
throw new Exception\InvalidArgumentException('Invalid parameter "name"'
. ' of "' . $name . '" must be a non-empty string');
}
if (array_key_exists($name, $this->parameters)) {
unset($this->parameters[$name]);
}
return $this;
}
/**
* Return an array of optional parameters for (un)subscribe requests
*
* @return array
*/
public function getParameters()
{
return $this->parameters;
}
/**
* Sets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used to background
* save any verification tokens associated with a subscription or other.
*
* @param Model\SubscriptionPersistenceInterface $storage
* @return Subscriber
*/
public function setStorage(Model\SubscriptionPersistenceInterface $storage)
{
$this->storage = $storage;
return $this;
}
/**
* Gets an instance of Zend\Feed\Pubsubhubbub\Storage\StoragePersistence used
* to background save any verification tokens associated with a subscription
* or other.
*
* @return Model\SubscriptionPersistenceInterface
* @throws Exception\RuntimeException
*/
public function getStorage()
{
if ($this->storage === null) {
throw new Exception\RuntimeException('No storage vehicle '
. 'has been set.');
}
return $this->storage;
}
/**
* Subscribe to one or more Hub Servers using the stored Hub URLs
* for the given Topic URL (RSS or Atom feed)
*
* @return void
*/
public function subscribeAll()
{
$this->_doRequest('subscribe');
}
/**
* Unsubscribe from one or more Hub Servers using the stored Hub URLs
* for the given Topic URL (RSS or Atom feed)
*
* @return void
*/
public function unsubscribeAll()
{
$this->_doRequest('unsubscribe');
}
/**
* Returns a boolean indicator of whether the notifications to Hub
* Servers were ALL successful. If even one failed, FALSE is returned.
*
* @return bool
*/
public function isSuccess()
{
if (count($this->errors) > 0) {
return false;
}
return true;
}
/**
* Return an array of errors met from any failures, including keys:
* 'response' => the Zend\Http\Response object from the failure
* 'hubUrl' => the URL of the Hub Server whose notification failed
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* Return an array of Hub Server URLs who returned a response indicating
* operation in Asynchronous Verification Mode, i.e. they will not confirm
* any (un)subscription immediately but at a later time (Hubs may be
* doing this as a batch process when load balancing)
*
* @return array
*/
public function getAsyncHubs()
{
return $this->asyncHubs;
}
/**
* Executes an (un)subscribe request
*
* @param string $mode
* @return void
* @throws Exception\RuntimeException
*/
protected function _doRequest($mode)
{
$client = $this->_getHttpClient();
$hubs = $this->getHubUrls();
if (empty($hubs)) {
throw new Exception\RuntimeException('No Hub Server URLs'
. ' have been set so no subscriptions can be attempted');
}
$this->errors = [];
$this->asyncHubs = [];
foreach ($hubs as $url) {
if (array_key_exists($url, $this->authentications)) {
$auth = $this->authentications[$url];
$client->setAuth($auth[0], $auth[1]);
}
$client->setUri($url);
$client->setRawBody($params = $this->_getRequestParameters($url, $mode));
$response = $client->send();
if ($response->getStatusCode() !== 204
&& $response->getStatusCode() !== 202
) {
$this->errors[] = [
'response' => $response,
'hubUrl' => $url,
];
/**
* At first I thought it was needed, but the backend storage will
* allow tracking async without any user interference. It's left
* here in case the user is interested in knowing what Hubs
* are using async verification modes so they may update Models and
* move these to asynchronous processes.
*/
} elseif ($response->getStatusCode() == 202) {
$this->asyncHubs[] = [
'response' => $response,
'hubUrl' => $url,
];
}
}
}
/**
* Get a basic prepared HTTP client for use
*
* @return \Zend\Http\Client
*/
protected function _getHttpClient()
{
$client = PubSubHubbub::getHttpClient();
$client->setMethod(HttpRequest::METHOD_POST);
$client->setOptions(['useragent' => 'Zend_Feed_Pubsubhubbub_Subscriber/'
. Version::VERSION]);
return $client;
}
/**
* Return a list of standard protocol/optional parameters for addition to
* client's POST body that are specific to the current Hub Server URL
*
* @param string $hubUrl
* @param string $mode
* @return string
* @throws Exception\InvalidArgumentException
*/
protected function _getRequestParameters($hubUrl, $mode)
{
if (!in_array($mode, ['subscribe', 'unsubscribe'])) {
throw new Exception\InvalidArgumentException('Invalid mode specified: "'
. $mode . '" which should have been "subscribe" or "unsubscribe"');
}
$params = [
'hub.mode' => $mode,
'hub.topic' => $this->getTopicUrl(),
];
if ($this->getPreferredVerificationMode()
== PubSubHubbub::VERIFICATION_MODE_SYNC
) {
$vmodes = [
PubSubHubbub::VERIFICATION_MODE_SYNC,
PubSubHubbub::VERIFICATION_MODE_ASYNC,
];
} else {
$vmodes = [
PubSubHubbub::VERIFICATION_MODE_ASYNC,
PubSubHubbub::VERIFICATION_MODE_SYNC,
];
}
$params['hub.verify'] = [];
foreach ($vmodes as $vmode) {
$params['hub.verify'][] = $vmode;
}
/**
* Establish a persistent verify_token and attach key to callback
* URL's path/query_string
*/
$key = $this->_generateSubscriptionKey($params, $hubUrl);
$token = $this->_generateVerifyToken();
$params['hub.verify_token'] = $token;
// Note: query string only usable with PuSH 0.2 Hubs
if (!$this->usePathParameter) {
$params['hub.callback'] = $this->getCallbackUrl()
. '?xhub.subscription=' . PubSubHubbub::urlencode($key);
} else {
$params['hub.callback'] = rtrim($this->getCallbackUrl(), '/')
. '/' . PubSubHubbub::urlencode($key);
}
if ($mode == 'subscribe' && $this->getLeaseSeconds() !== null) {
$params['hub.lease_seconds'] = $this->getLeaseSeconds();
}
// hub.secret not currently supported
$optParams = $this->getParameters();
foreach ($optParams as $name => $value) {
$params[$name] = $value;
}
// store subscription to storage
$now = new DateTime();
$expires = null;
if (isset($params['hub.lease_seconds'])) {
$expires = $now->add(new DateInterval('PT' . $params['hub.lease_seconds'] . 'S'))
->format('Y-m-d H:i:s');
}
$data = [
'id' => $key,
'topic_url' => $params['hub.topic'],
'hub_url' => $hubUrl,
'created_time' => $now->format('Y-m-d H:i:s'),
'lease_seconds' => $params['hub.lease_seconds'],
'verify_token' => hash('sha256', $params['hub.verify_token']),
'secret' => null,
'expiration_time' => $expires,
'subscription_state' => ($mode == 'unsubscribe')? PubSubHubbub::SUBSCRIPTION_TODELETE : PubSubHubbub::SUBSCRIPTION_NOTVERIFIED,
];
$this->getStorage()->setSubscription($data);
return $this->_toByteValueOrderedString(
$this->_urlEncode($params)
);
}
/**
* Simple helper to generate a verification token used in (un)subscribe
* requests to a Hub Server. Follows no particular method, which means
* it might be improved/changed in future.
*
* @return string
*/
protected function _generateVerifyToken()
{
if (!empty($this->testStaticToken)) {
return $this->testStaticToken;
}
return uniqid(rand(), true) . time();
}
/**
* Simple helper to generate a verification token used in (un)subscribe
* requests to a Hub Server.
*
* @param array $params
* @param string $hubUrl The Hub Server URL for which this token will apply
* @return string
*/
protected function _generateSubscriptionKey(array $params, $hubUrl)
{
$keyBase = $params['hub.topic'] . $hubUrl;
$key = md5($keyBase);
return $key;
}
/**
* URL Encode an array of parameters
*
* @param array $params
* @return array
*/
protected function _urlEncode(array $params)
{
$encoded = [];
foreach ($params as $key => $value) {
if (is_array($value)) {
$ekey = PubSubHubbub::urlencode($key);
$encoded[$ekey] = [];
foreach ($value as $duplicateKey) {
$encoded[$ekey][]
= PubSubHubbub::urlencode($duplicateKey);
}
} else {
$encoded[PubSubHubbub::urlencode($key)]
= PubSubHubbub::urlencode($value);
}
}
return $encoded;
}
/**
* Order outgoing parameters
*
* @param array $params
* @return array
*/
protected function _toByteValueOrderedString(array $params)
{
$return = [];
uksort($params, 'strnatcmp');
foreach ($params as $key => $value) {
if (is_array($value)) {
foreach ($value as $keyduplicate) {
$return[] = $key . '=' . $keyduplicate;
}
} else {
$return[] = $key . '=' . $value;
}
}
return implode('&', $return);
}
/**
* This is STRICTLY for testing purposes only...
*/
protected $testStaticToken = null;
final public function setTestStaticToken($token)
{
$this->testStaticToken = (string) $token;
}
}

View file

@ -0,0 +1,316 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub\Subscriber;
use Zend\Feed\PubSubHubbub;
use Zend\Feed\PubSubHubbub\Exception;
use Zend\Feed\Uri;
class Callback extends PubSubHubbub\AbstractCallback
{
/**
* Contains the content of any feeds sent as updates to the Callback URL
*
* @var string
*/
protected $feedUpdate = null;
/**
* Holds a manually set subscription key (i.e. identifies a unique
* subscription) which is typical when it is not passed in the query string
* but is part of the Callback URL path, requiring manual retrieval e.g.
* using a route and the \Zend\Mvc\Router\RouteMatch::getParam() method.
*
* @var string
*/
protected $subscriptionKey = null;
/**
* After verification, this is set to the verified subscription's data.
*
* @var array
*/
protected $currentSubscriptionData = null;
/**
* Set a subscription key to use for the current callback request manually.
* Required if usePathParameter is enabled for the Subscriber.
*
* @param string $key
* @return \Zend\Feed\PubSubHubbub\Subscriber\Callback
*/
public function setSubscriptionKey($key)
{
$this->subscriptionKey = $key;
return $this;
}
/**
* Handle any callback from a Hub Server responding to a subscription or
* unsubscription request. This should be the Hub Server confirming the
* the request prior to taking action on it.
*
* @param array $httpGetData GET data if available and not in $_GET
* @param bool $sendResponseNow Whether to send response now or when asked
* @return void
*/
public function handle(array $httpGetData = null, $sendResponseNow = false)
{
if ($httpGetData === null) {
$httpGetData = $_GET;
}
/**
* Handle any feed updates (sorry for the mess :P)
*
* This DOES NOT attempt to process a feed update. Feed updates
* SHOULD be validated/processed by an asynchronous process so as
* to avoid holding up responses to the Hub.
*/
$contentType = $this->_getHeader('Content-Type');
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post'
&& $this->_hasValidVerifyToken(null, false)
&& (stripos($contentType, 'application/atom+xml') === 0
|| stripos($contentType, 'application/rss+xml') === 0
|| stripos($contentType, 'application/xml') === 0
|| stripos($contentType, 'text/xml') === 0
|| stripos($contentType, 'application/rdf+xml') === 0)
) {
$this->setFeedUpdate($this->_getRawBody());
$this->getHttpResponse()->setHeader('X-Hub-On-Behalf-Of', $this->getSubscriberCount());
/**
* Handle any (un)subscribe confirmation requests
*/
} elseif ($this->isValidHubVerification($httpGetData)) {
$this->getHttpResponse()->setContent($httpGetData['hub_challenge']);
switch (strtolower($httpGetData['hub_mode'])) {
case 'subscribe':
$data = $this->currentSubscriptionData;
$data['subscription_state'] = PubSubHubbub\PubSubHubbub::SUBSCRIPTION_VERIFIED;
if (isset($httpGetData['hub_lease_seconds'])) {
$data['lease_seconds'] = $httpGetData['hub_lease_seconds'];
}
$this->getStorage()->setSubscription($data);
break;
case 'unsubscribe':
$verifyTokenKey = $this->_detectVerifyTokenKey($httpGetData);
$this->getStorage()->deleteSubscription($verifyTokenKey);
break;
default:
throw new Exception\RuntimeException(sprintf(
'Invalid hub_mode ("%s") provided',
$httpGetData['hub_mode']
));
}
/**
* Hey, C'mon! We tried everything else!
*/
} else {
$this->getHttpResponse()->setStatusCode(404);
}
if ($sendResponseNow) {
$this->sendResponse();
}
}
/**
* Checks validity of the request simply by making a quick pass and
* confirming the presence of all REQUIRED parameters.
*
* @param array $httpGetData
* @return bool
*/
public function isValidHubVerification(array $httpGetData)
{
/**
* As per the specification, the hub.verify_token is OPTIONAL. This
* implementation of Pubsubhubbub considers it REQUIRED and will
* always send a hub.verify_token parameter to be echoed back
* by the Hub Server. Therefore, its absence is considered invalid.
*/
if (strtolower($_SERVER['REQUEST_METHOD']) !== 'get') {
return false;
}
$required = [
'hub_mode',
'hub_topic',
'hub_challenge',
'hub_verify_token',
];
foreach ($required as $key) {
if (!array_key_exists($key, $httpGetData)) {
return false;
}
}
if ($httpGetData['hub_mode'] !== 'subscribe'
&& $httpGetData['hub_mode'] !== 'unsubscribe'
) {
return false;
}
if ($httpGetData['hub_mode'] == 'subscribe'
&& !array_key_exists('hub_lease_seconds', $httpGetData)
) {
return false;
}
if (!Uri::factory($httpGetData['hub_topic'])->isValid()) {
return false;
}
/**
* Attempt to retrieve any Verification Token Key attached to Callback
* URL's path by our Subscriber implementation
*/
if (!$this->_hasValidVerifyToken($httpGetData)) {
return false;
}
return true;
}
/**
* Sets a newly received feed (Atom/RSS) sent by a Hub as an update to a
* Topic we've subscribed to.
*
* @param string $feed
* @return \Zend\Feed\PubSubHubbub\Subscriber\Callback
*/
public function setFeedUpdate($feed)
{
$this->feedUpdate = $feed;
return $this;
}
/**
* Check if any newly received feed (Atom/RSS) update was received
*
* @return bool
*/
public function hasFeedUpdate()
{
if ($this->feedUpdate === null) {
return false;
}
return true;
}
/**
* Gets a newly received feed (Atom/RSS) sent by a Hub as an update to a
* Topic we've subscribed to.
*
* @return string
*/
public function getFeedUpdate()
{
return $this->feedUpdate;
}
/**
* Check for a valid verify_token. By default attempts to compare values
* with that sent from Hub, otherwise merely ascertains its existence.
*
* @param array $httpGetData
* @param bool $checkValue
* @return bool
*/
protected function _hasValidVerifyToken(array $httpGetData = null, $checkValue = true)
{
$verifyTokenKey = $this->_detectVerifyTokenKey($httpGetData);
if (empty($verifyTokenKey)) {
return false;
}
$verifyTokenExists = $this->getStorage()->hasSubscription($verifyTokenKey);
if (!$verifyTokenExists) {
return false;
}
if ($checkValue) {
$data = $this->getStorage()->getSubscription($verifyTokenKey);
$verifyToken = $data['verify_token'];
if ($verifyToken !== hash('sha256', $httpGetData['hub_verify_token'])) {
return false;
}
$this->currentSubscriptionData = $data;
return true;
}
return true;
}
/**
* Attempt to detect the verification token key. This would be passed in
* the Callback URL (which we are handling with this class!) as a URI
* path part (the last part by convention).
*
* @param null|array $httpGetData
* @return false|string
*/
protected function _detectVerifyTokenKey(array $httpGetData = null)
{
/**
* Available when sub keys encoding in Callback URL path
*/
if (isset($this->subscriptionKey)) {
return $this->subscriptionKey;
}
/**
* Available only if allowed by PuSH 0.2 Hubs
*/
if (is_array($httpGetData)
&& isset($httpGetData['xhub_subscription'])
) {
return $httpGetData['xhub_subscription'];
}
/**
* Available (possibly) if corrupted in transit and not part of $_GET
*/
$params = $this->_parseQueryString();
if (isset($params['xhub.subscription'])) {
return rawurldecode($params['xhub.subscription']);
}
return false;
}
/**
* Build an array of Query String parameters.
* This bypasses $_GET which munges parameter names and cannot accept
* multiple parameters with the same key.
*
* @return array|void
*/
protected function _parseQueryString()
{
$params = [];
$queryString = '';
if (isset($_SERVER['QUERY_STRING'])) {
$queryString = $_SERVER['QUERY_STRING'];
}
if (empty($queryString)) {
return [];
}
$parts = explode('&', $queryString);
foreach ($parts as $kvpair) {
$pair = explode('=', $kvpair);
$key = rawurldecode($pair[0]);
$value = rawurldecode($pair[1]);
if (isset($params[$key])) {
if (is_array($params[$key])) {
$params[$key][] = $value;
} else {
$params[$key] = [$params[$key], $value];
}
} else {
$params[$key] = $value;
}
}
return $params;
}
}

View file

@ -0,0 +1,15 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\PubSubHubbub;
abstract class Version
{
const VERSION = '2';
}