<?php

/**
 * Isgd
 *
 * For more information on this file and how to use the class please visit
 * http://www.hashbangcode.com/blog/php-class-to-interact-with-is-gd-api-1503.html
 *
 * @author       Philip Norton
 * @version   1.0
 * @copyright 2009 #! code
 *
 */

/**
 * This class provides an interface to the is.gd service.
 * For more information about the is.gd API have a look
 * at http://is.gd/api_info.php
 * Please read the is.gd terms of service at http://is.gd/terms.php before
 * using this class.
 *
 * @package Isgd
 */
class Isgd{

    
/**
     * The data returned from is.gd.
     *
     * @var array
     */
    
private $result;

    
/**
     * The any error messages returned from is.gd.
     *
     * @var mixed
     */
    
private $errors false;

    
/**
   * Constructor
   *
   */
    
public function Isgd()
    {
    }

    
/**
   * Get the latest errors.
   *
   * @return string A string containing the latest error.
   */
    
public function getErrors()
    {
        return 
$this->errors;
    }

    
/**
   * Get the latest results from the is.gd service.
   *
   * @return string A string containing the is.gd result.
   */
    
public function getResult()
    {
        return 
$this->result;
    }

    
/**
   * Shorten a URL using the is.gd service. Note that $preview and $keywords
   * cannot be used together. If both are supplied then $preview will take
   * precedence. This is a feature of is.gd.
   *
   * @param string  $url      The URL to shorten.
   * @param boolean $preview  If set to true a hyphen will be appended to the 
   *                          URL to access the preview functionality of the 
   *                          is.gd service.
   * @param string  $keywords An extra string can be added to the is.gd URL to
   *                          provide more information about the URL. This is 
   *                          ignored by the is.gd service.
   *
   * @return string A string containing the shortened URL.
   */
    
public function shorten($url$preview false$keywords '')
    {
        
$isgdargs 'api.php?longurl='.urlencode($url);
        if ( 
$this->getIsgdResult($isgdargs) !== false ) {
      if ( 
$preview == true ) {
        return 
$this->result.'-';
      }
      if ( 
strlen($keywords) > ) {
        return 
$this->result.'/'.$keywords;
      }
      return 
$this->result;
        }
        return 
false;
    }

  
/**
   * Expand a URL that has been shortened using the is.gd service.
   *
   * @param string $url  The URL to expand.
   *
   * @return string The long URL, as translated by the is.gd service.
   */
    
public function expand($shortUrl)
    {
    
// Extract the end of the string and remove any dashes
    // This prevents is.gd returning a page of HTML as the preview page, we only
    // want the header, which we will extract the URL from.
    
$shortUrl str_replace(array('http://is.gd''-'), ''$shortUrl);
        if ( 
$this->getIsgdResult($shortUrl) !== false ) {
            return 
$this->result;
        }
        return 
false;
    }

  
/**
   * Interact with the is.gd service.
   *
   * @param string $url The URL to interact with. The interaction is determined 
   *                    by the function that calls this function.
   *
   * @return boolean True if everything worked, otherwise false.
   */
    
private function getIsgdResult($isgdargs)
    {
    
$results '';
    
$this->errors '';
    
$fp fsockopen("is.gd"80$errno$errstr30);
    if ( !
$fp ) {
        
$this->errors 'Cannot open connection!';
        return 
false;
    } else {
        
$out "GET ".$isgdargs." HTTP/1.1\r\n";
        
$out .= "Host: is.gd\r\n";
        
$out .= "Connection: Close\r\n\r\n";
        
fwrite($fp$out);
        while ( !
feof($fp) ) {
            
$results .= (fgets($fp128));
        }
        
fclose($fp);
    }

    
$hc explode("\r\n\r\n",  $results);
    
    
// $hc[0] == headers
    
$headers explode("\r\n",  $hc[0]);
    
    
// $hc[1] == content
    
$content explode("\r\n",  $hc[1]);
    
    if ( 
strpos($hc[1],'404 Error') !== false ) {
      
// URL was not found.
      
$this->errors 'The URL was not found.';
      return 
false;
    }

    if ( 
$headers[0] == 'HTTP/1.1 200 OK' ) {
      
// everything worked
      
$this->result $content[1];
      return 
true;
    }

    if ( 
$headers[0] == 'HTTP/1.1 500 Internal Server Error' ) {
      
// borked!
      // record raw headers and output as results
      
$this->result $results;
      
// store errors from is.gd
      
$this->errors $content[1];
      return 
false;
    }

    if ( 
$headers[0] == 'HTTP/1.1 301 Moved Permanently' ) {
      
// record where the url is going to
      
$this->result trim(str_replace('Location:'''$headers[2]));
      return 
true;
    }
    
    return 
false;
    }

  
/**
   * Convert a string into a URL friendly string, removing anything that is not
   * a number or letter.
   *
   * @param string $string The string to convert.
   *
   * @return string The converted string.
   */
  
function fixForUri($string){
    
$slug trim($string); // trim the string
    
$slugpreg_replace('/[^a-zA-Z0-9 -]/','',$slug ); // only take alphanumerical characters, but keep the spaces and dashes too...
    
$slugstr_replace(' ','-'$slug); // replace spaces by dashes
    
$slugstrtolower($slug);  // make it lowercase
    
return $slug;
  }
}