Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Google Apps Short Links API Class
- *
- * PHP version 5
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- * @package ShortLink
- * @author Adrien Gibrat <adrien.gibrat@gmail.com>
- * @copyright 2011 Adrien Gibrat
- * @license http://www.opensource.org/licenses/mit-license.php The MIT License
- * @version 1.0.0
- * @see https://www.google.com/enterprise/marketplace/viewListing?productListingId=5143210+6352879591152674960
- * @see http://www.google.com/support/a/bin/answer.py?answer=114245
- * @usage
- $s = new ShortLink( 'my.domain.com', 'MyHmacSecretKey','user@any-domain.com' );
- echo 'create public short url : ', $r = clone $s->pub( 'http://www.google.com' ), '<br/>', // clone result to keep it for later
- 'get status : ', $r->status, '<br/>',
- 'request status : ', $s->info( $r->short )->status, '<br/>', // non sense, only for demo purpose
- 'remaining API call : ', $s->remain, '<br/>',
- 'Info request : ', $s->request, '<br/>',
- 'Creation request : ', $r->request;
- *
- * If 'status' property is 'no response', check your domain.
- * If 'status' property is 'error 403', check your Hmac secret key or your server time setting!
- */
- /**
- * Google Apps Short Links Class
- *
- * Easy usage of Google Apps Short Links API (by Google Labs)
- * 3 main methods : short, hash & info
- * + 2 convenience methods : pub & priv
- *
- * @package ShortLink
- * @author Adrien Gibrat <adrien.gibrat@gmail.com>
- * @copyright 2011 Adrien Gibrat
- * @license http://www.opensource.org/licenses/mit-license.php The MIT License
- * @version 1.0.0
- *
- * Access magic properties
- *
- * @property string $status Status of last request
- * @property string $long Long link
- * @property string $short Short link
- * @property boolean $public Is link public
- * @property boolean $hash Is link hashed
- * @property string $owner Owner email
- * @property integer $usage Usage link counter
- * @property integer $count Usage link counter
- * @property integer $remain Remaining API call
- * @property string $request Requested url
- * @property stdObject $response Raw decoded response
- *
- */
- class ShortLink {
- /**
- * Alias for easy access to response propeties
- * @var array
- * @access public
- * @static
- */
- static public $alias = array(
- 'usage' => 'usage_count',
- 'count' => 'usage_count',
- 'short' => 'shortcut',
- 'long' => 'url',
- 'public' => 'is_public',
- 'hash' => 'is_hash'
- );
- /**
- * Remaining API call stored by domain
- * @var array
- * @access protected
- * @static
- */
- static protected $remain = array();
- /**
- * Max number of retry in case of creation / update failure
- * @var integer
- * @access public
- */
- public $maxRetry = 2;
- /**
- * Actual number of retry for last request
- * @var integer
- * @access protected
- */
- protected $retry;
- /**
- * Domain name
- * @var string
- * @access protected
- */
- protected $domain;
- /**
- * Hmac secret key
- * @var string
- * @access protected
- */
- protected $key;
- /**
- * User email
- * @var string
- * @access protected
- */
- protected $user;
- /**
- * Last request url
- * @var string
- * @access protected
- */
- protected $request;
- /**
- * Last request response
- * @var object|false
- * @access protected
- */
- protected $response;
- /**
- * Constructor
- *
- * Set mandatory informations
- *
- * @param string $domain Domain name
- * @param string $key Hmac secret key
- * @param string $user Owner / user email
- */
- public function __construct ( $domain, $key, $user ) {
- $this->user = $user;
- $this->key = $key;
- $this->domain = $domain;
- }
- /**
- * Magic getter
- *
- * Get last request, response and number of retry (read only)
- * Easy access to last response properties (with alias)
- *
- * @param string $property Property name
- * @return mixed Last response property value or last request / response
- */
- public function __get ( $property ) {
- switch ( $property ) {
- case 'remain' :
- return isset( self::$remain[$this->domain] ) ? self::$remain[$this->domain] : true;
- case 'response' :
- return $this->response;
- case 'request' :
- return $this->request;
- case 'retry' :
- return $this->retry;
- }
- if ( ! $this->response ) {
- return;
- }
- $alias = isset( self::$alias[$property] ) ? self::$alias[$property] : false;
- if ( $alias && isset( $this->response->{$alias} ) ) {
- return $this->response->{$alias};
- }
- if ( isset( $this->response->{$property} ) ) {
- return $this->response->{$property};
- }
- }
- /**
- * Magic toString
- *
- * Get last response short url
- *
- * @return string Last request short url or empty string on failure
- */
- public function __toString () {
- return $this->_success () && isset( $this->response->shortcut ) ?
- 'http://' . $this->domain . '/' . $this->response->shortcut :
- '';
- }
- /**
- * Create private short link (for convenience)
- *
- * Create / update private shortcut or hashed link
- * If hashed link exists, visibility is set to private, no new hashed link is created
- * If shortcut exists, url is updated and visibility set to private
- *
- * @param string $url Long url to shorten
- * @param string $shortcut Optional shortcut, if ommited create or update hashed link
- * @return ShortLink Chainable object to allow easy access to response
- */
- public function priv ( $url, $shortcut = null ) {
- return $shortcut ?
- $this->short( $shortcut, $url, false ) :
- $this->hash( $url, false );
- }
- /**
- * Create public short link (for convenience)
- *
- * Create / update public shortcut or hashed link
- * If hashed link exists, visibility is set to public, no new hashed link is created
- * If shortcut exists, url is updated and visibility set to public
- *
- * @param string $url Long url to shorten
- * @param string $shortcut Optional shortcut, if ommited create or update hashed link
- * @return ShortLink Chainable object to allow easy access to response
- */
- public function pub ( $url, $shortcut = null ) {
- return $shortcut ?
- $this->short( $shortcut, $url, true ) :
- $this->hash( $url, true );
- }
- /**
- * Create shortcut link
- *
- * Create / update shortcut link
- * If shortcut exists, url and visibility are updated
- *
- * @param string $shortcut Shortcut
- * @param string $url Long url to shorten
- * @param boolean $public Short link visiblity: true = public, false = private (default)
- * @return ShortLink Chainable object to allow easy access to response
- */
- public function short ( $shortcut, $url, $public = false ) {
- $this->_valid( $shortcut ) && $this->_request( 'get_or_create_shortlink', array(
- 'is_public' => $public ? 'true' : 'false',
- 'shortcut' => $shortcut,
- 'url' => $url,
- 'user' => $this->user
- ), $this->maxRetry );
- return $this;
- }
- /**
- * Create hashed link
- *
- * Create / update hashed link
- * If hashed link exists, visibility is updated, no new hashed link is created
- *
- * @param string $url Long url to shorten
- * @param boolean $public Short link visiblity: true = public, false = private (default)
- * @return ShortLink Chainable object to allow easy access to response
- */
- public function hash ( $url, $public = false ) {
- $this->_request( 'get_or_create_hash', array(
- 'is_public' => $public ? 'true' : 'false',
- 'url' => $url,
- 'user' => $this->user
- ), $this->maxRetry );
- return $this;
- }
- /**
- * Get details about short link
- *
- * Retrieve basic informations about short link
- *
- * @param string $shortcut Shortcut
- * @return ShortLink Chainable object to allow easy access to response
- */
- public function info ( $shortcut ) {
- $this->_valid( $shortcut ) && $this->_request( 'get_details', array( 'shortcut' => $shortcut ) );
- return $this;
- }
- /**
- * Send signed request to API
- *
- * Build signed GET request and get response
- * Automatically retry on failure, you can set the number of retry with public "retry" property
- *
- * @param string $method Method to call
- * @param array $params Request parameters
- * @param integer $maxRetry Maximum retry
- * @return stdObject|boolean Response object on success or false on failure
- */
- protected function _request ( $method, array $params, $maxRetry = 0 ) {
- $params = array(
- 'oauth_signature_method' => 'HMAC-SHA1',
- 'timestamp' => time(),
- 'user' => $this->user
- ) + $params;
- ksort($params);
- $params = http_build_query( $params );
- $url = 'http://' . $this->domain . '/js/' . $method;
- $signature = 'GET&' . $this->_encode( $url ) . '&' . $this->_encode( $params );
- $oauth = $this->_encode( base64_encode( hash_hmac( 'sha1', $signature, $this->key, true ) ) );
- $handle = curl_init( $this->request = $url . '?' . $params . '&oauth_signature=' . $oauth ) ;
- curl_setopt( $handle, CURLOPT_RETURNTRANSFER, 1 );
- $this->retry = 0;
- while ( ( $this->retry <= $maxRetry ) && $this->_response( $handle ) ) {
- if ( ! isset( $this->response->shortcut ) ) {
- $this->retry++;
- continue;
- }
- break;
- }
- curl_close( $handle );
- return $this->response;
- }
- /**
- * Check and set response
- *
- * Set response property on success and set appropriate status on error
- *
- * @param ressource $curl Curl handle ressource.
- * @return boolean True on success or false on failure
- */
- protected function _response ( $curl ) {
- $this->response = json_decode( curl_exec( $curl ) );
- if ( $this->response && isset( $this->response->status ) ) {
- if ( isset( $this->response->estimated_api_calls_remaining ) ) {
- self::$remain[$this->domain] = $this->response->estimated_api_calls_remaining;
- }
- return true;
- }
- $code = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
- $this->response = (object) array( 'status' => $code ? 'error ' . $code : 'no response' );
- return false;
- }
- /**
- * Proper url encode
- *
- * Replace space characters encoded as "+" by "%20"
- *
- * @param string $value String to encode
- * @return string Url-encoded string
- */
- protected function _encode ( $value ) {
- return str_replace( '+', '%20', urlencode( $value ) );
- }
- /**
- * Check shortcut
- *
- * Check if shortcut is valid, as some url specific characters are not allowed
- * Reset request and response properties if invalid shortcut (consistency purpose)
- *
- * @param string $shortcut Shortcut
- * @return boolean True if shortcut is valid or false if it's not
- */
- protected function _valid ( $shortcut ) {
- if ( preg_match( '~\/|\?|=|#~', $shortcut ) ) {
- $this->retry = 0;
- $this->request = null;
- return $this->response = false;
- }
- return true;
- }
- /**
- * Check response
- *
- * Check if last response status is ok
- *
- * @return boolean True if last response status is ok or false if it's not
- */
- protected function _success () {
- return $this->response && $this->response->status === 'ok';
- }
- }
- /* Bonus functions */
- function utm ( $url, $campaign, $medium, $source, $content = null, $term = null ) {
- $params = array_filter( array(
- 'utm_campaign' => $campaign,
- 'utm_medium' => $medium,
- 'utm_source' => $source,
- 'utm_content' => $content,
- 'utm_term' => $term
- ) );
- if ( $query = parse_url( $url, PHP_URL_QUERY ) ) {
- parse_str( $query, $oldParams );
- $params = array_merge( $oldParams, $params );
- }
- $newQuery = http_build_query( $params );
- return $query ?
- str_replace( $query, $newQuery, $url ) :
- $url . '?' . $newQuery;
- }
- function qr ( $url, $size = 150 ) {
- return 'http://chart.apis.google.com/chart?cht=qr&chs=' . $size . 'x' . $size . '&choe=UTF-8&chld=H&chl=' . urlencode( $url );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement