installed plugin W3 Total Cache version 2.3.2

This commit is contained in:
2023-06-05 11:23:16 +00:00
committed by Gitium
parent d9b3c97e40
commit 51ea2ff21c
2730 changed files with 334913 additions and 0 deletions

View File

@ -0,0 +1,136 @@
# AWS SDK for PHP
The AWS SDK for PHP enables developers to build solutions for Amazon Simple Storage Service (Amazon S3),
Amazon Elastic Compute Cloud (Amazon EC2), Amazon SimpleDB, and more. With the AWS SDK for PHP, developers
can get started in minutes with a single, downloadable package.
The SDK features:
* **AWS PHP Libraries:** Build PHP applications on top of APIs that take the complexity out of coding directly
against a web service interface. The toolkit provides APIs that hide much of the lower-level implementation.
* **Code Samples:** Practical examples for how to use the toolkit to build applications.
* **Documentation:** Complete SDK reference documentation with samples demonstrating how to use the SDK.
* **PEAR package:** The ability to install the AWS SDK for PHP as a PEAR package.
* **SDK Compatibility Test:** Includes both an HTML-based and a CLI-based SDK Compatibility Test that you can
run on your server to determine whether or not your PHP environment meets the minimum requirements.
For more information about the AWS SDK for PHP, including a complete list of supported services, see
[aws.amazon.com/sdkforphp](http://aws.amazon.com/sdkforphp).
## Signing up for Amazon Web Services
Before you can begin, you must sign up for each service you want to use.
To sign up for a service:
* Go to the home page for the service. You can find a list of services on
[aws.amazon.com/products](http://aws.amazon.com/products).
* Click the Sign Up button on the top right corner of the page. If you don't already have an AWS account, you
are prompted to create one as part of the sign up process.
* Follow the on-screen instructions.
* AWS sends you a confirmation e-mail after the sign-up process is complete. At any time, you can view your
current account activity and manage your account by going to [aws.amazon.com](http://aws.amazon.com) and
clicking "Your Account".
## Source
The source tree for includes the following files and directories:
* `_compatibility_test` -- Includes both an HTML-based and a CLI-based SDK Compatibility Test that you can
run on your server to determine whether or not your PHP environment meets the minimum requirements.
* `_docs` -- Informational documents, the contents of which should be fairly self-explanatory.
* `_samples` -- Code samples that you can run out of the box.
* `extensions` -- Extra code that can be used to enhance usage of the SDK, but isn't a service class or a
third-party library.
* `lib` -- Contains any third-party libraries that the SDK depends on. The licenses for these projects will
always be Apache 2.0-compatible.
* `services` -- Contains the service-specific classes that communicate with AWS. These classes are always
prefixed with `Amazon`.
* `utilities` -- Contains any utility-type methods that the SDK uses. Includes extensions to built-in PHP
classes, as well as new functionality that is entirely custom. These classes are always prefixed with `CF`.
* `README` -- The document you're reading right now.
* `config-sample.inc.php` -- A sample configuration file that should be filled out and renamed to `config.inc.php`.
* `sdk.class.php` -- The SDK loader that you would include in your projects. Contains the base functionality
that the rest of the SDK depends on.
## Minimum Requirements in a nutshell
* You are at least an intermediate-level PHP developer and have a basic understanding of object-oriented PHP.
* You have a valid AWS account, and you've already signed up for the services you want to use.
* The PHP interpreter, version 5.2 or newer. PHP 5.2.17 or 5.3.x is highly recommended for use with the AWS SDK for PHP.
* The cURL PHP extension (compiled with the [OpenSSL](http://openssl.org) libraries for HTTPS support).
* The ability to read from and write to the file system via [file_get_contents()](http://php.net/file_get_contents) and [file_put_contents()](http://php.net/file_put_contents).
If you're not sure whether your PHP environment meets these requirements, run the
[SDK Compatibility Test](http://github.com/amazonwebservices/aws-sdk-for-php/tree/master/_compatibility_test/) script
included in the SDK download.
## Installation
### Via GitHub
[Git](http://git-scm.com) is an extremely fast, efficient, distributed version control system ideal for the
collaborative development of software. [GitHub](http://github.com/amazonwebservices) is the best way to
collaborate with others. Fork, send pull requests and manage all your public and private git repositories.
We believe that GitHub is the ideal service for working collaboratively with the open source PHP community.
Git is primarily a command-line tool. GitHub provides instructions for installing Git on
[Mac OS X](http://help.github.com/mac-git-installation/), [Windows](http://help.github.com/win-git-installation/),
and [Linux](http://help.github.com/linux-git-installation/). If you're unfamiliar with Git, there are a variety
of resources on the net that will help you learn more:
* [Git Immersion](http://gitimmersion.com) is a guided tour that walks through the fundamentals of Git, inspired
by the premise that to know a thing is to do it.
* The [PeepCode screencast on Git](https://peepcode.com/products/git) ($12) will teach you how to install and
use Git. You'll learn how to create a repository, use branches, and work with remote repositories.
* [Git Reference](http://gitref.org) is meant to be a quick reference for learning and remembering the most
important and commonly used Git commands.
* [Git Ready](http://gitready.com) provides a collection of Git tips and tricks.
* If you want to dig even further, I've [bookmarked other Git references](http://pinboard.in/u:skyzyx/t:git).
If you're comfortable working with Git and/or GitHub, you can pull down the source code as follows:
git clone git://github.com/amazonwebservices/aws-sdk-for-php.git AWSSDKforPHP
cd ./AWSSDKforPHP
### Via PEAR
[PEAR](http://pear.php.net) stands for the _PHP Extension and Application Repository_ and is a framework and
distribution system for reusable PHP components. It is the PHP equivalent to package management software such as
[MacPorts](http://macports.org) and [Homebrew](https://github.com/mxcl/homebrew) for Mac OS X,
[Yum](http://fedoraproject.org/wiki/Tools/yum) and [Apt](http://wiki.debian.org/Apt) for GNU/Linux,
[RubyGems](http://rubygems.org) for Ruby, [Easy Install](http://packages.python.org/distribute/easy_install.html)
for Python, [Maven](http://maven.apache.org) for Java, and [NPM](http://npm.mape.me) for Node.js.
PEAR packages are very easy to install, and are available in your PHP environment path so that they are accessible
to any PHP project. PEAR packages are not specific to your project, but rather to the machine that they're
installed on.
From the command-line, you can install the SDK with PEAR as follows:
pear channel-discover pear.amazonwebservices.com
pear install aws/sdk
You may need to use `sudo` for the above commands. Once the SDK has been installed via PEAR, you can load it into
your project with:
require_once 'AWSSDKforPHP/sdk.class.php';
### Configuration
1. Copy the contents of [config-sample.inc.php](https://github.com/amazonwebservices/aws-sdk-for-php/raw/master/config-sample.inc.php)
and add your credentials as instructed in the file.
2. Move your file to `~/.aws/sdk/config.inc.php`.
3. Make sure that `getenv('HOME')` points to your user directory. If not you'll need to set
`putenv('HOME=<your-user-directory>')`.
## Additional Information
* AWS SDK for PHP: <http://aws.amazon.com/sdkforphp>
* Documentation: <http://docs.amazonwebservices.com/AWSSDKforPHP/latest/>
* License: <http://aws.amazon.com/apache2.0/>
* Discuss: <http://aws.amazon.com/forums>

View File

@ -0,0 +1,25 @@
Copyright (c) 2006-2010 Ryan Parman, Foleeo Inc., and contributors. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
* Neither the name of Ryan Parman, Foleeo Inc. nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS
AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,15 @@
# RequestCore
RequestCore is a lightweight cURL-based HTTP request/response class that leverages MultiCurl for parallel requests.
### PEAR HTTP_Request?
RequestCore was written as a replacement for [PEAR HTTP_Request](http://pear.php.net/http_request/). While PEAR HTTP_Request is full-featured and heavy, RequestCore features only the essentials and is very lightweight. It also leverages the batch request support in cURL's `curl_multi_exec()` to enable multi-threaded requests that fire in parallel.
### Reference and Download
You can find the class reference at <http://skyzyx.github.com/requestcore/>. You can get the code from <http://github.com/skyzyx/requestcore>.
### License and Copyright
This code is Copyright (c) 2008-2010, Ryan Parman. However, I'm licensing this code for others to use under the [Simplified BSD license](http://www.opensource.org/licenses/bsd-license.php).

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,140 @@
<?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
class Message
{
protected static $requiredKeys = array(
'__default' => array(
'Message',
'MessageId',
'Timestamp',
'TopicArn',
'Type',
'Signature',
'SigningCertURL',
),
'SubscriptionConfirmation' => array(
'SubscribeURL',
'Token'
),
'UnsubscribeConfirmation' => array(
'SubscribeURL',
'Token'
),
);
protected static $signableKeys = array(
'Message',
'MessageId',
'Subject',
'SubscribeURL',
'Timestamp',
'Token',
'TopicArn',
'Type',
);
/**
* @var array The message data
*/
protected $data;
/**
* Creates a Message object from an array of raw message data
*
* @param array $data The message data
*
* @return Message
* @throws InvalidArgumentException If a valid type is not provided or there are other required keys missing
*/
public static function fromArray($data) {
// Make sure the type key is set
if (!isset($data['Type'])) {
throw new InvalidArgumentException('The "Type" key must be provided to instantiate a Message object.');
}
// Determine required keys and create a collection from the message data
$requiredKeys = array_merge(
self::$requiredKeys['__default'],
isset(self::$requiredKeys[$data['Type']]) ? self::$requiredKeys[$data['Type']] : array()
);
$data = array_merge($requiredKeys, $data);
return new self($data);
}
/**
* Creates a message object from the raw POST data
*
* @return Message
* @throws UnexpectedValueException If the POST data is absent, or not a valid JSON document
*/
public static function fromRawPostData() {
$data = json_decode(file_get_contents('php://input'), true);
if (!is_array($data)) {
throw new UnexpectedValueException('POST data absent, or not a valid JSON document', json_last_error());
}
return self::fromArray($data);
}
/**
* @param array $data A Collection of message data with all required keys
*/
public function __construct($data) {
$this->data = $data;
}
/**
* Get the entire message data as a Collection
*
* @return array
*/
public function getData() {
return $this->data;
}
/**
* Gets a single key from the message data
*
* @param string $key
* @return string
*/
public function get($key) {
return $this->data[$key];
}
/**
* Builds a newline delimited string to sign according to the specs
*
* @return string
* @link http://docs.aws.amazon.com/sns/latest/gsg/SendMessageToHttp.verify.signature.html
*/
public function getStringToSign() {
$stringToSign = '';
$data = $this->data;
ksort($data);
$has = array();
foreach ($data as $key => $value) {
if (in_array($key, self::$signableKeys) && !in_array($key, $has)) {
$stringToSign .= "{$key}\n{$value}\n";
$has[] = $key;
}
}
return $stringToSign;
}
}

View File

@ -0,0 +1,111 @@
<?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
require_once(W3TC_LIB_DIR . '/SNS/services/MessageValidator/sns-exceptions.php');
/**
* This class uses openssl to verify SNS messages to ensure that they were sent by AWS.
*/
class MessageValidator {
private $hostPattern
= '/^sns\.[a-zA-Z0-9\-]{3,}\.amazonaws\.com(\.cn)?$/';
/**
* Constructs the Message Validator object and ensures that openssl is installed
*
* @throws Exception If openssl is not installed
*/
public function __construct()
{
if (!extension_loaded('openssl')) {
throw new Exception('The openssl extension is required to use the SNS Message '
. 'Validator. Please install this extension in order to use this feature.');
}
}
/**
* Validates a message from SNS to ensure that it was delivered by AWS
*
* @param Message $message The message to validate
*
* @throws CannotGetPublicKeyFromCertificateException If the certificate cannot be retrieved
* @throws CertificateFromUnrecognizedSourceException If the certificate's source cannot be verified
* @throws InvalidMessageSignatureException If the message's signature is invalid
*/
public function validate($message) {
// Get the cert's URL and ensure it is from AWS
$certUrl = $message->get('SigningCertURL');
$this->validateUrl($certUrl);
// Get the cert itself and extract the public key
$response = wp_remote_get($certUrl);
if (is_wp_error($response))
throw new CannotGetPublicKeyFromCertificateException('Could not retrieve certificate from ' . $certUrl);
$certificate = wp_remote_retrieve_body($response);
$publicKey = openssl_get_publickey($certificate);
if (!$publicKey) {
throw new CannotGetPublicKeyFromCertificateException('Could not extract public key from ' . $certUrl);
}
// Verify the signature of the message
$stringToSign = $message->getStringToSign();
$incomingSignature = base64_decode($message->get('Signature'));
if (0 !== openssl_verify($stringToSign, $incomingSignature, $publicKey, OPENSSL_ALGO_SHA1)) {
throw new InvalidMessageSignatureException('The message did not match the signature ' . "\n" . $stringToSign);
}
}
/**
* Ensures that the URL of the certificate is one belonging to AWS, and not
* just something from the amazonaws domain, which could include S3 buckets.
*
* @param string $url Certificate URL
*
* @throws InvalidSnsMessageException if the cert url is invalid.
*/
private function validateUrl($url)
{
$parsed = parse_url($url);
if (empty($parsed['scheme'])
|| empty($parsed['host'])
|| $parsed['scheme'] !== 'https'
|| substr($url, -4) !== '.pem'
|| !preg_match($this->hostPattern, $parsed['host'])
) {
throw new InvalidSnsMessageException(
'The certificate is located on an invalid domain.'
);
}
}
/**
* Determines if a message is valid and that is was delivered by AWS. This method does not throw exceptions and
* returns a simple boolean value.
*
* @param Message $message The message to validate
* @return bool
*/
public function isValid($message)
{
try {
$this->validate($message);
return true;
} catch (SnsMessageValidatorException $e) {
$error = $e->getMessage();
return false;
}
}
}

View File

@ -0,0 +1,37 @@
<?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
* Generic exception thrown by the SNS Message Validator.
*/
class SnsMessageValidatorException extends RuntimeException {}
/**
* Indicates that certificate was from an unrecognized source.
*/
class CertificateFromUnrecognizedSourceException extends SnsMessageValidatorException {}
/**
* Indicates that the public key can't be extracted from the the certificate.
*/
class CannotGetPublicKeyFromCertificateException extends SnsMessageValidatorException {}
/**
* Indicates that the signature for SNS message was invalid.
*/
class InvalidMessageSignatureException extends SnsMessageValidatorException {}

View File

@ -0,0 +1,440 @@
<?php
/*
* Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
*
* @version Thu Sep 01 21:23:56 PDT 2011
* @license See the included NOTICE.md file for complete information.
* @copyright See the included NOTICE.md file for complete information.
* @link http://aws.amazon.com/sns/Amazon Simple Notification Service
* @link http://aws.amazon.com/documentation/sns/Amazon Simple Notification Service documentation
*/
class AmazonSNS extends CFRuntime
{
/*%******************************************************************************************%*/
// CLASS CONSTANTS
/**
* Specify the default queue URL.
*/
const DEFAULT_URL = 'sns.us-east-1.amazonaws.com';
/**
* Specify the queue URL for the US-East (Northern Virginia) Region.
*/
const REGION_US_E1 = self::DEFAULT_URL;
/**
* Specify the queue URL for the US-West (Northern California) Region.
*/
const REGION_US_W1 = 'sns.us-west-1.amazonaws.com';
/**
* Specify the queue URL for the EU (Ireland) Region.
*/
const REGION_EU_W1 = 'sns.eu-west-1.amazonaws.com';
/**
* Specify the queue URL for the Asia Pacific (Singapore) Region.
*/
const REGION_APAC_SE1 = 'sns.ap-southeast-1.amazonaws.com';
/**
* Specify the queue URL for the Asia Pacific (Japan) Region.
*/
const REGION_APAC_NE1 = 'sns.ap-northeast-1.amazonaws.com';
/*%******************************************************************************************%*/
// SETTERS
/**
* This allows you to explicitly sets the region for the service to use.
*
* @param string $region (Required) The region to use for subsequent Amazon S3 operations. [Allowed values: `AmazonSNS::REGION_US_E1 `, `AmazonSNS::REGION_US_W1`, `AmazonSNS::REGION_EU_W1`, `AmazonSNS::REGION_APAC_SE1`]
* @return $this A reference to the current instance.
*/
public function set_region($region)
{
$this->set_hostname($region);
return $this;
}
/*%******************************************************************************************%*/
// CONVENIENCE METHODS
/**
* Gets a simple list of Topic ARNs.
*
* @param string $pcre (Optional) A Perl-Compatible Regular Expression (PCRE) to filter the names against.
* @return array A list of Topic ARNs.
* @link http://php.net/pcre Perl-Compatible Regular Expression (PCRE) Docs
*/
public function get_topic_list($pcre = null)
{
if ($this->use_batch_flow)
{
throw new SNS_Exception(__FUNCTION__ . '() cannot be batch requested');
}
// Get a list of topics.
$list = $this->list_topics();
if ($list = $list->body->TopicArn())
{
$list = $list->map_string($pcre);
return $list;
}
return array();
}
/*%******************************************************************************************%*/
// CONSTRUCTOR
/**
* Constructs a new instance of <AmazonSNS>. If the <code>AWS_DEFAULT_CACHE_CONFIG</code> configuration
* option is set, requests will be authenticated using a session token. Otherwise, requests will use
* the older authentication method.
*
* @param string $key (Optional) Your AWS key, or a session key. If blank, it will look for the <code>AWS_KEY</code> constant.
* @param string $secret_key (Optional) Your AWS secret key, or a session secret key. If blank, it will look for the <code>AWS_SECRET_KEY</code> constant.
* @param string $token (optional) An AWS session token. If blank, a request will be made to the AWS Secure Token Service to fetch a set of session credentials.
* @return boolean A value of <code>false</code> if no valid values are set, otherwise <code>true</code>.
*/
public function __construct($key = null, $secret_key = null, $token = null)
{
$this->api_version = '2010-03-31';
$this->hostname = self::DEFAULT_URL;
if (!$key && !defined('AWS_KEY'))
{
// @codeCoverageIgnoreStart
throw new SNS_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.');
// @codeCoverageIgnoreEnd
}
if (!$secret_key && !defined('AWS_SECRET_KEY'))
{
// @codeCoverageIgnoreStart
throw new SNS_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.');
// @codeCoverageIgnoreEnd
}
if (defined('AWS_DEFAULT_CACHE_CONFIG') && AWS_DEFAULT_CACHE_CONFIG)
{
return parent::session_based_auth($key, $secret_key, $token);
}
return parent::__construct($key, $secret_key);
}
/*%******************************************************************************************%*/
// SERVICE METHODS
/**
*
* The ConfirmSubscription action verifies an endpoint owner's intent to receive messages by validating the token sent to the endpoint by an
* earlier Subscribe action. If the token is valid, the action creates a new subscription and returns its Amazon Resource Name (ARN). This call
* requires an AWS signature only when the AuthenticateOnUnsubscribe flag is set to "true".
*
* @param string $topic_arn (Required) The ARN of the topic for which you wish to confirm a subscription.
* @param string $token (Required) Short-lived token sent to an endpoint during the Subscribe action.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>AuthenticateOnUnsubscribe</code> - <code>string</code> - Optional - Indicates that you want to disable unauthenticated unsubsciption of the subscription. If parameter is present in the request, the request has an AWS signature, and the value of this parameter is true, only the topic owner and the subscription owner will be permitted to unsubscribe the endopint, and the Unsubscribe action will require AWS authentication. </li>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function confirm_subscription($topic_arn, $token, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
$opt['Token'] = $token;
return $this->authenticate('ConfirmSubscription', $opt, $this->hostname);
}
/**
*
* The GetTopicAttribtues action returns all of the properties of a topic customers have created. Topic properties returned might differ based
* on the authorization of the user.
*
* @param string $topic_arn (Required) The ARN of the topic whose properties you want to get.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function get_topic_attributes($topic_arn, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
return $this->authenticate('GetTopicAttributes', $opt, $this->hostname);
}
/**
*
* The Subscribe action prepares to subscribe an endpoint by sending the endpoint a confirmation message. To actually create a subscription,
* the endpoint owner must call the ConfirmSubscription action with the token from the confirmation message. Confirmation tokens are valid for
* twenty-four hours.
*
* @param string $topic_arn (Required) The ARN of topic you want to subscribe to.
* @param string $protocol (Required) The protocol you want to use. Supported protocols include: <ul> <li>http -- delivery of JSON-encoded message via HTTP POST</li><li>https -- delivery of JSON-encoded message via HTTPS POST</li><li>email -- delivery of message via SMTP</li><li>email-json -- delivery of JSON-encoded message via SMTP</li><li>sqs -- delivery of JSON-encoded message to an Amazon SQS queue</li> </ul>
* @param string $endpoint (Required) The endpoint that you want to receive notifications. Endpoints vary by protocol: <ul> <li>For the http protocol, the endpoint is an URL beginning with "http://"</li><li>For the https protocol, the endpoint is a URL beginning with "https://"</li><li>For the email protocol, the endpoint is an e-mail address</li><li>For the email-json protocol, the endpoint is an e-mail address</li><li>For the sqs protocol, the endpoint is the ARN of an Amazon SQS queue</li> </ul>
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function subscribe($topic_arn, $protocol, $endpoint, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
$opt['Protocol'] = $protocol;
$opt['Endpoint'] = $endpoint;
return $this->authenticate('Subscribe', $opt, $this->hostname);
}
/**
*
* The SetTopicAttributes action allows a topic owner to set an attribute of the topic to a new value.
*
* @param string $topic_arn (Required) The ARN of the topic to modify.
* @param string $attribute_name (Required) The name of the attribute you want to set. Only a subset of the topic's attributes are mutable.
* @param string $attribute_value (Required) The new value for the attribute.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function set_topic_attributes($topic_arn, $attribute_name, $attribute_value, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
$opt['AttributeName'] = $attribute_name;
$opt['AttributeValue'] = $attribute_value;
return $this->authenticate('SetTopicAttributes', $opt, $this->hostname);
}
/**
*
* The DeleteTopic action deletes a topic and all its subscriptions. Deleting a topic might prevent some messages previously sent to the topic
* from being delivered to subscribers. This action is idempotent, so deleting a topic that does not exist will not result in an error.
*
* @param string $topic_arn (Required) The ARN of the topic you want to delete.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function delete_topic($topic_arn, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
return $this->authenticate('DeleteTopic', $opt, $this->hostname);
}
/**
*
* The RemovePermission action removes a statement from a topic's access control policy.
*
* @param string $topic_arn (Required) The ARN of the topic whose access control policy you wish to modify.
* @param string $label (Required) The unique label of the statement you want to remove.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function remove_permission($topic_arn, $label, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
$opt['Label'] = $label;
return $this->authenticate('RemovePermission', $opt, $this->hostname);
}
/**
*
* The ListSubscriptions action returns a list of the requester's subscriptions. Each call returns a limited list of subscriptions. If there
* are more subscriptions, a NextToken is also returned. Use the NextToken parameter in a new ListSubscriptions call to get further results.
*
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>NextToken</code> - <code>string</code> - Optional - Token returned by the previous ListSubscriptions request. </li>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function list_subscriptions($opt = null)
{
if (!$opt) $opt = array();
return $this->authenticate('ListSubscriptions', $opt, $this->hostname);
}
/**
*
* The AddPermission action adds a statement to a topic's access control policy, granting access for the specified AWS accounts to the
* specified actions.
*
* @param string $topic_arn (Required) The ARN of the topic whose access control policy you wish to modify.
* @param string $label (Required) A unique identifier for the new policy statement.
* @param string|array $account_id (Required) The AWS account IDs of the users (principals) who will be given access to the specified actions. The users must have AWS accounts, but do not need to be signed up for this service. Pass a string for a single value, or an indexed array for multiple values.
* @param string|array $action_name (Required) The action you want to allow for the specified principal(s). Pass a string for a single value, or an indexed array for multiple values.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function add_permission($topic_arn, $label, $account_id, $action_name, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
$opt['Label'] = $label;
// Required parameter
$opt = array_merge($opt, CFComplexType::map(array(
'AWSAccountId' => (is_array($account_id) ? $account_id : array($account_id))
), 'member'));
// Required parameter
$opt = array_merge($opt, CFComplexType::map(array(
'ActionName' => (is_array($action_name) ? $action_name : array($action_name))
), 'member'));
return $this->authenticate('AddPermission', $opt, $this->hostname);
}
/**
*
* The CreateTopic action creates a topic to which notifications can be published. Users can create at most 25 topics. This action is
* idempotent, so if the requester already owns a topic with the specified name, that topic's ARN will be returned without creating a new
* topic.
*
* @param string $name (Required) The name of the topic you want to create. Constraints: Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, and hyphens, and must be between 1 and 256 characters long.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function create_topic($name, $opt = null)
{
if (!$opt) $opt = array();
$opt['Name'] = $name;
return $this->authenticate('CreateTopic', $opt, $this->hostname);
}
/**
*
* The ListTopics action returns a list of the requester's topics. Each call returns a limited list of topics. If there are more topics, a
* NextToken is also returned. Use the NextToken parameter in a new ListTopics call to get further results.
*
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>NextToken</code> - <code>string</code> - Optional - Token returned by the previous ListTopics request. </li>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function list_topics($opt = null)
{
if (!$opt) $opt = array();
return $this->authenticate('ListTopics', $opt, $this->hostname);
}
/**
*
* The Unsubscribe action deletes a subscription. If the subscription requires authentication for deletion, only the owner of the subscription
* or the its topic's owner can unsubscribe, and an AWS signature is required. If the Unsubscribe call does not require authentication and the
* requester is not the subscription owner, a final cancellation message is delivered to the endpoint, so that the endpoint owner can easily
* resubscribe to the topic if the Unsubscribe request was unintended.
*
* @param string $subscription_arn (Required) The ARN of the subscription to be deleted.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function unsubscribe($subscription_arn, $opt = null)
{
if (!$opt) $opt = array();
$opt['SubscriptionArn'] = $subscription_arn;
return $this->authenticate('Unsubscribe', $opt, $this->hostname);
}
/**
*
* The ListSubscriptionsByTopic action returns a list of the subscriptions to a specific topic. Each call returns a limited list of
* subscriptions. If there are more subscriptions, a NextToken is also returned. Use the NextToken parameter in a new ListSubscriptionsByTopic
* call to get further results.
*
* @param string $topic_arn (Required) The ARN of the topic for which you wish to find subscriptions.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>NextToken</code> - <code>string</code> - Optional - Token returned by the previous ListSubscriptionsByTopic request. </li>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function list_subscriptions_by_topic($topic_arn, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
return $this->authenticate('ListSubscriptionsByTopic', $opt, $this->hostname);
}
/**
*
* The Publish action sends a message to all of a topic's subscribed endpoints. When a messageId is returned, the message has been saved and
* Amazon SNS will attempt to deliver it to the topic's subscribers shortly. The format of the outgoing message to each subscribed endpoint
* depends on the notification protocol selected.
*
* @param string $topic_arn (Required) The topic you want to publish to.
* @param string $message (Required) The message you want to send to the topic. Constraints: Messages must be UTF-8 encoded strings at most 8 KB in size (8192 bytes, not 8192 characters).
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>Subject</code> - <code>string</code> - Optional - Optional parameter to be used as the "Subject" line of when the message is delivered to e-mail endpoints. This field will also be included, if present, in the standard JSON messages delivered to other endpoints. Constraints: Subjects must be ASCII text that begins with a letter, number or punctuation mark; must not include line breaks or control characters; and must be less than 100 characters long. </li>
* <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li>
* <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul>
* @return CFResponse A <CFResponse> object containing a parsed HTTP response.
*/
public function publish($topic_arn, $message, $opt = null)
{
if (!$opt) $opt = array();
$opt['TopicArn'] = $topic_arn;
$opt['Message'] = $message;
return $this->authenticate('Publish', $opt, $this->hostname);
}
}
/*%******************************************************************************************%*/
// EXCEPTIONS
/**
* Default SNS Exception.
*/
class SNS_Exception extends Exception {}

View File

@ -0,0 +1,64 @@
<?php
/*
* Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*%******************************************************************************************%*/
// CLASS
/**
* Wraps the underlying `RequestCore` class with some AWS-specific customizations.
*
* @version 2011.06.02
* @license See the included NOTICE.md file for more information.
* @copyright See the included NOTICE.md file for more information.
* @link http://aws.amazon.com/php/ PHP Developer Center
*/
class CFRequest extends RequestCore
{
/**
* The default class to use for HTTP Requests (defaults to <CFRequest>).
*/
public $request_class = 'CFRequest';
/**
* The default class to use for HTTP Responses (defaults to <CFResponse>).
*/
public $response_class = 'CFResponse';
/*%******************************************************************************************%*/
// CONSTRUCTOR
/**
* Constructs a new instance of this class.
*
* @param string $url (Optional) The URL to request or service endpoint to query.
* @param string $proxy (Optional) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port`
* @param array $helpers (Optional) An associative array of classnames to use for request, and response functionality. Gets passed in automatically by the calling class.
* @return $this A reference to the current instance.
*/
public function __construct($url = null, $proxy = null, $helpers = null)
{
parent::__construct($url, $proxy, $helpers);
// Standard settings for all requests
$this->add_header('Expect', '100-continue');
$this->set_useragent(CFRUNTIME_USERAGENT);
$this->cacert_location = (defined('AWS_CERTIFICATE_AUTHORITY') ? AWS_CERTIFICATE_AUTHORITY : false);
return $this;
}
}

View File

@ -0,0 +1,29 @@
<?php
/*
* Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*%******************************************************************************************%*/
// CLASS
/**
* Wraps the underlying `ResponseCore` class with some AWS-specific customizations.
*
* @version 2010.10.11
* @license See the included NOTICE.md file for more information.
* @copyright See the included NOTICE.md file for more information.
* @link http://aws.amazon.com/php/ PHP Developer Center
*/
class CFResponse extends ResponseCore {}

View File

@ -0,0 +1,215 @@
<?php
/*
* Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*%******************************************************************************************%*/
// CLASS
/**
* Wraps the underlying `SimpleXMLIterator` class with enhancements for rapidly traversing the DOM tree,
* converting types, and comparisons.
*
* @version 2011.04.25
* @license See the included NOTICE.md file for more information.
* @copyright See the included NOTICE.md file for more information.
* @link http://aws.amazon.com/php/ PHP Developer Center
* @link http://php.net/SimpleXML SimpleXML
*/
class CFSimpleXML extends SimpleXMLIterator
{
/**
* Stores the namespace name to use in XPath queries.
*/
public $xml_ns;
/**
* Stores the namespace URI to use in XPath queries.
*/
public $xml_ns_url;
/**
* Catches requests made to methods that don't exist. Specifically, looks for child nodes via XPath.
*
* @param string $name (Required) The name of the method.
* @param array $arguments (Required) The arguments passed to the method.
* @return mixed Either an array of matches, or a single <CFSimpleXML> element.
*/
public function __call($name, $arguments)
{
// Remap $this
$self = $this;
// Re-base the XML
$self = new CFSimpleXML($self->asXML());
// Determine XPath query
$self->xpath_expression = 'descendant-or-self::' . $name;
// Get the results and augment with CFArray
$results = $self->xpath($self->xpath_expression);
if (!count($results)) return false;
$results = new CFArray($results);
// If an integer was passed, return only that result
if (isset($arguments[0]) && is_int($arguments[0]))
{
if (isset($results[$arguments[0]]))
{
return $results[$arguments[0]];
}
return false;
}
return $results;
}
/**
* Alternate approach to constructing a new instance. Supports chaining.
*
* @param string $data (Required) A well-formed XML string or the path or URL to an XML document if $data_is_url is <code>true</code>.
* @param integer $options (Optional) Used to specify additional LibXML parameters. The default value is <code>0</code>.
* @param boolean $data_is_url (Optional) Specify a value of <code>true</code> to specify that data is a path or URL to an XML document instead of string data. The default value is <code>false</code>.
* @param string $ns (Optional) The XML namespace to return values for.
* @param boolean $is_prefix (Optional) (No description provided by PHP.net.)
* @return CFSimpleXML Creates a new <CFSimpleXML> element.
*/
public static function init($data, $options = 0, $data_is_url, $ns, $is_prefix = false)
{
if (version_compare(PHP_VERSION, '5.3.0', '<'))
{
throw new Exception('PHP 5.3 or newer is required to instantiate a new class with CLASS::init().');
}
$self = get_called_class();
return new $self($data, $options, $data_is_url, $ns, $is_prefix);
}
/*%******************************************************************************************%*/
// TRAVERSAL
/**
* Wraps the results of an XPath query in a <CFArray> object.
*
* @param string $expr (Required) The XPath expression to use to query the XML response.
* @return CFArray A <CFArray> object containing the results of the XPath query.
*/
public function query($expr)
{
return new CFArray($this->xpath($expr));
}
/**
* Gets the parent or a preferred ancestor of the current element.
*
* @param string $node (Optional) Name of the ancestor element to match and return.
* @return CFSimpleXML A <CFSimpleXML> object containing the requested node.
*/
public function parent($node = null)
{
if ($node)
{
$parents = $this->xpath('ancestor-or-self::' . $node);
}
else
{
$parents = $this->xpath('parent::*');
}
return $parents[0];
}
/*%******************************************************************************************%*/
// ALTERNATE FORMATS
/**
* Gets the current XML node as a true string.
*
* @return string The current XML node as a true string.
*/
public function to_string()
{
return (string) $this;
}
/**
* Gets the current XML node as <CFArray>, a child class of PHP's <php:ArrayObject> class.
*
* @return CFArray The current XML node as a <CFArray> object.
*/
public function to_array()
{
return new CFArray(json_decode(json_encode($this), true));
}
/**
* Gets the current XML node as a stdClass object.
*
* @return array The current XML node as a stdClass object.
*/
public function to_stdClass()
{
return json_decode(json_encode($this));
}
/**
* Gets the current XML node as a JSON string.
*
* @return string The current XML node as a JSON string.
*/
public function to_json()
{
return json_encode($this);
}
/**
* Gets the current XML node as a YAML string.
*
* @return string The current XML node as a YAML string.
*/
public function to_yaml()
{
return sfYaml::dump(json_decode(json_encode($this), true), 5);
}
/*%******************************************************************************************%*/
// COMPARISONS
/**
* Whether or not the current node exactly matches the compared value.
*
* @param string $value (Required) The value to compare the current node to.
* @return boolean Whether or not the current node exactly matches the compared value.
*/
public function is($value)
{
return ((string) $this === $value);
}
/**
* Whether or not the current node contains the compared value.
*
* @param string $value (Required) The value to use to determine whether it is contained within the node.
* @return boolean Whether or not the current node contains the compared value.
*/
public function contains($value)
{
return (stripos((string) $this, $value) !== false);
}
}

View File

@ -0,0 +1,394 @@
<?php
/*
* Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*%******************************************************************************************%*/
// CLASS
/**
* Contains a set of utility methods for connecting to, and working with, AWS.
*
* @version 2010.09.30
* @license See the included NOTICE.md file for more information.
* @copyright See the included NOTICE.md file for more information.
* @link http://aws.amazon.com/php/ PHP Developer Center
*/
class CFUtilities
{
/*%******************************************************************************************%*/
// CONSTANTS
/**
* Define the RFC 2616-compliant date format.
*/
const DATE_FORMAT_RFC2616 = 'D, d M Y H:i:s \G\M\T';
/**
* Define the ISO-8601-compliant date format.
*/
const DATE_FORMAT_ISO8601 = 'Y-m-d\TH:i:s\Z';
/**
* Define the MySQL-compliant date format.
*/
const DATE_FORMAT_MYSQL = 'Y-m-d H:i:s';
/*%******************************************************************************************%*/
// METHODS
/**
* Constructs a new instance of this class.
*
* @return $this A reference to the current instance.
*/
public function __construct()
{
return $this;
}
/**
* Retrieves the value of a class constant, while avoiding the `T_PAAMAYIM_NEKUDOTAYIM` error. Misspelled because `const` is a reserved word.
*
* @param object $class (Required) An instance of the class containing the constant.
* @param string $const (Required) The name of the constant to retrieve.
* @return mixed The value of the class constant.
*/
public function konst($class, $const)
{
if (is_string($class))
{
$ref = new ReflectionClass($class);
}
else
{
$ref = new ReflectionObject($class);
}
return $ref->getConstant($const);
}
/**
* Convert a HEX value to Base64.
*
* @param string $str (Required) Value to convert.
* @return string Base64-encoded string.
*/
public function hex_to_base64($str)
{
$raw = '';
for ($i = 0; $i < strlen($str); $i += 2)
{
$raw .= chr(hexdec(substr($str, $i, 2)));
}
return base64_encode($raw);
}
/**
* Convert an associative array into a query string.
*
* @param array $array (Required) Array to convert.
* @return string URL-friendly query string.
*/
public function to_query_string($array)
{
$temp = array();
foreach ($array as $key => $value)
{
if (is_string($key) && !is_array($value))
{
$temp[] = rawurlencode($key) . '=' . rawurlencode($value);
}
}
return implode('&', $temp);
}
/**
* Convert an associative array into a sign-able string.
*
* @param array $array (Required) Array to convert.
* @return string URL-friendly sign-able string.
*/
public function to_signable_string($array)
{
$t = array();
foreach ($array as $k => $v)
{
$t[] = $this->encode_signature2($k) . '=' . $this->encode_signature2($v);
}
return implode('&', $t);
}
/**
* Encode the value according to RFC 3986.
*
* @param string $string (Required) String to convert.
* @return string URL-friendly sign-able string.
*/
public function encode_signature2($string)
{
$string = rawurlencode($string);
return str_replace('%7E', '~', $string);
}
/**
* Convert a query string into an associative array. Multiple, identical keys will become an indexed array.
*
* @param string $qs (Required) Query string to convert.
* @return array Associative array of keys and values.
*/
public function query_to_array($qs)
{
$query = explode('&', $qs);
$data = array();
foreach ($query as $q)
{
$q = explode('=', $q);
if (isset($data[$q[0]]) && is_array($data[$q[0]]))
{
$data[$q[0]][] = urldecode($q[1]);
}
else if (isset($data[$q[0]]) && !is_array($data[$q[0]]))
{
$data[$q[0]] = array($data[$q[0]]);
$data[$q[0]][] = urldecode($q[1]);
}
else
{
$data[urldecode($q[0])] = urldecode($q[1]);
}
}
return $data;
}
/**
* Return human readable file sizes.
*
* @author Aidan Lister <aidan@php.net>
* @author Ryan Parman <ryan@getcloudfusion.com>
* @license http://www.php.net/license/3_01.txt PHP License
* @param integer $size (Required) Filesize in bytes.
* @param string $unit (Optional) The maximum unit to use. Defaults to the largest appropriate unit.
* @param string $default (Optional) The format for the return string. Defaults to `%01.2f %s`.
* @return string The human-readable file size.
* @link http://aidanlister.com/repos/v/function.size_readable.php Original Function
*/
public function size_readable($size, $unit = null, $default = null)
{
// Units
$sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB');
$mod = 1024;
$ii = count($sizes) - 1;
// Max unit
$unit = array_search((string) $unit, $sizes);
if ($unit === null || $unit === false)
{
$unit = $ii;
}
// Return string
if ($default === null)
{
$default = '%01.2f %s';
}
// Loop
$i = 0;
while ($unit != $i && $size >= 1024 && $i < $ii)
{
$size /= $mod;
$i++;
}
return sprintf($default, $size, $sizes[$i]);
}
/**
* Convert a number of seconds into Hours:Minutes:Seconds.
*
* @param integer $seconds (Required) The number of seconds to convert.
* @return string The formatted time.
*/
public function time_hms($seconds)
{
$time = '';
// First pass
$hours = (int) ($seconds / 3600);
$seconds = $seconds % 3600;
$minutes = (int) ($seconds / 60);
$seconds = $seconds % 60;
// Cleanup
$time .= ($hours) ? $hours . ':' : '';
$time .= ($minutes < 10 && $hours > 0) ? '0' . $minutes : $minutes;
$time .= ':';
$time .= ($seconds < 10) ? '0' . $seconds : $seconds;
return $time;
}
/**
* Returns the first value that is set. Based on [Try.these()](http://api.prototypejs.org/language/Try/these/) from [Prototype](http://prototypejs.org).
*
* @param array $attrs (Required) The attributes to test, as strings. Intended for testing properties of the $base object, but also works with variables if you place an @ symbol at the beginning of the command.
* @param object $base (Optional) The base object to use, if any.
* @param mixed $default (Optional) What to return if there are no matches. Defaults to `null`.
* @return mixed Either a matching property of a given object, boolean `false`, or any other data type you might choose.
*/
public function try_these($attrs, $base = null, $default = null)
{
if ($base)
{
foreach ($attrs as $attr)
{
if (isset($base->$attr))
{
return $base->$attr;
}
}
}
else
{
foreach ($attrs as $attr)
{
if (isset($attr))
{
return $attr;
}
}
}
return $default;
}
/**
* Can be removed once all calls are updated.
*
* @deprecated Use <php:json_encode()> instead.
* @param mixed $obj (Required) The PHP object to convert into a JSON string.
* @return string A JSON string.
*/
public function json_encode($obj)
{
return json_encode($obj);
}
/**
* Converts a SimpleXML response to an array structure.
*
* @param ResponseCore $response (Required) A response value.
* @return array The response value as a standard, multi-dimensional array.
*/
public function convert_response_to_array(ResponseCore $response)
{
return json_decode(json_encode($response), true);
}
/**
* Checks to see if a date stamp is ISO-8601 formatted, and if not, makes it so.
*
* @param string $datestamp (Required) A date stamp, or a string that can be parsed into a date stamp.
* @return string An ISO-8601 formatted date stamp.
*/
public function convert_date_to_iso8601($datestamp)
{
if (!preg_match('/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}((\+|-)\d{2}:\d{2}|Z)/m', $datestamp))
{
return gmdate(self::DATE_FORMAT_ISO8601, strtotime($datestamp));
}
return $datestamp;
}
/**
* Determines whether the data is Base64 encoded or not.
*
* @license http://us.php.net/manual/en/function.base64-decode.php#81425 PHP License
* @param string $s (Required) The string to test.
* @return boolean Whether the string is Base64 encoded or not.
*/
public function is_base64($s)
{
return (bool) preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s);
}
/**
* Determines whether the data is a JSON string or not.
*
* @param string $s (Required) The string to test.
* @return boolean Whether the string is a valid JSON object or not.
*/
public function is_json($s)
{
return !!(json_decode($s) instanceof stdClass);
}
/**
* Decodes `\uXXXX` entities into their real unicode character equivalents.
*
* @param string $s (Required) The string to decode.
* @return string The decoded string.
*/
public function decode_uhex($s)
{
preg_match_all('/\\\u([0-9a-f]{4})/i', $s, $matches);
$matches = $matches[count($matches) - 1];
$map = array();
foreach ($matches as $match)
{
if (!isset($map[$match]))
{
$map['\u' . $match] = html_entity_decode('&#' . hexdec($match) . ';', ENT_NOQUOTES, 'UTF-8');
}
}
return str_replace(array_keys($map), $map, $s);
}
/**
* Generates a random GUID.
*
* @author Alix Axel <http://www.php.net/manual/en/function.com-create-guid.php#99425>
* @license http://www.php.net/license/3_01.txt PHP License
* @return string A random GUID.
*/
public function generate_guid()
{
return sprintf(
'%04X%04X-%04X-%04X-%04X-%04X%04X%04X',
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(16384, 20479),
mt_rand(32768, 49151),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535)
);
}
}