Call Nucleus Development [Nd] now, 347 688 6441 or contact us


content loading...

Code Repository

The code libraries listed to the right -> are available for public use. You may copy, distribute, and eat this code as you wish. However, the license remains in effect for the life of the software.
Pretense for download and use "[Nd] Libraries":
  • You may not use this code in a commercial setting without prior consent from [Nd].
  • You may not misrepresent yourself as the author of this code.
  • You may make changes to this code, but must make the changes available under this license.
  • These libraries are governed by their respective licenses.



<?php
 
class SHORTEN
{
 
 
    // vars
    private $id = null;
    private $url_long = null;
    private $url_short = null;
    private $base = null;
    private $limit_ip = null; // set to world
    private $tracking = true;
    public $check_url = null;
    private $caching = false;
    private $cache_dir = null;
    
    private $allowed_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
     
    // contructor 
    public function __construct( $mode = 'create', $url = null, $check_url = false ) {
        global $DIR_ROOT, $CONF;        
        /**
          * uncomment this and reload site
          * to clear db.
          **/
        //$this->clearDb();    
 
        $this->base = 'http://'. $CONF['IndexURL'] .'/'; // . $_SERVER['HTTP_HOST'] . '/';
        $this->limit_ip = $_SERVER['REMOTE_ADDR'];
        $this->cache_dir = $DIR_ROOT . 'cache/';
        $this->check_url = $check_url;
        
        if($mode == 'redirect')
            return $this->load($url);
        
                
        // short circuit to create    
        return $this->store($url);    
    }
    
    
    public function getShortUrl() {
        global $CONF;
        
        if( !empty( $this->url_short ) )
            return 'http://'. $CONF['ShortURL'] . '/' . $this->url_short;
        
        return false;
    }
    
    
    public function redirect() {
        global $CONF;
            
        if( empty($this->url_long) ) {
            header('Location: ' . $CONF['IndexURL']);
            exit;
        }    
        
        // $CONF['IndexURL'] .  $this->url_long;
        //die();
    
        header('Location: '  .  $this->url_long);
        exit;
    
    }
    
    
    private function load($url) {
        
        if(!preg_match('|^[0-9a-zA-Z]{1,6}$|', $url))
            return false;
        
        $this->id = $this->getIdFromSurl($url);
        if($this->caching)
            $this->cache();
        
        
        $this->url_long = quickQuery( 'SELECT surl_long as result FROM ' . sql_table('shorturls') . ' WHERE sid = "' . $this->id . '"');
        
        if($this->tracking)
            $this->track();
        
        return true;
    }
    
    
    private function store($url_long) {
        global $CONF;
    
        // if class var limit_ip is limiting short linking
        if($_SERVER['REMOTE_ADDR'] != $this->limit_ip)
            return false;
                
        // if url is empty
        if( empty( $url_long ) )
            //return false; 
            $url_long = $CONF['IndexURL'];
            
        //if( !preg_match( '|^https?://|', $url_long ) ) return false;
        
        /** 
          * if the url contains the shortener's 
          * url don't allow recursive linking
          */
        if( strstr( $url_long, $CONF['ShortURL'] ) )
            return false;
        
        // don't allow just http:// to be a link
        if($url_long == 'http://')
            return false;
            
         $this->url_long = $url_long;
     
         // check if record exists and if so offer it
         if(true == ( $r = $this->recordExists() ) )
             return $this->url_short = $this->getSurlFromId($r);
    
        
         // if we are checking url for validity 
         if(true != ( $r = $this->checkUrl() ) )
             return false;
         
         //echo 'this is long url ' . $this->url_long;
        
                                   
         // if not create it
         $this->url_short =  $this->createRecord();
    
        return true;
        
    }
    
    
    private function getSurlFromId( $integer, $base = null ) {
        
        if( empty($base) )
            $base = $this->allowed_chars;
        
        $length = strlen($base);
        
        $out = null;
        while($integer > $length - 1) {
            $out = $base[fmod($integer, $length)] . $out;
            $integer = floor( $integer / $length );
        }
        
        return $base[$integer] . $out;
    }
    
    
    function getIdFromSurl($string, $base = null ) {
    
        if( empty($base) )
            $base = $this->allowed_chars;
 
        $length = strlen($base);
        $size = strlen($string) - 1;
        $string = str_split($string);
        $out = strpos($base, array_pop($string));
 
        foreach($string as $i => $char) {
            $out += strpos($base, $char) * pow($length, $size - $i);
        }
        
        return $out;
    }
    
    
    private function track() {
        $r = sql_query('UPDATE ' . sql_table('shorturls') . ' SET sreferrals=sreferrals+1 WHERE sid="' . addslashes($this->id) . '"');
        return $r;
    }
    
    
    // everything else if private
    private function checkUrl() {
        
        if(!$this->check_url)
            return true;
        
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $this->url_long );
        curl_setopt( $ch,  CURLOPT_RETURNTRANSFER, true );
        
        $r = curl_exec($ch);
        
        
        $flag = true;
        if( !curl_getinfo( $ch, CURLINFO_HTTP_CODE ) == '404' )
            $flag = false;
                
        curl_close($ch);
        
        return $flag;
        
    }
    
    
    
    private function recordExists() {
    
        /*if( !table_exists('shorturls') ) {    
            sql_query( "CREATE TABLE `nuke_shorturls` (
                 `sid` int(10) unsigned NOT NULL auto_increment,
                `surl_long` varchar(255) NOT NULL,
                 `screated` int(10) unsigned NOT NULL,
                  `screator` char(15) NOT NULL,
                  `sreferrals` int(10) unsigned NOT NULL default '0',
                  PRIMARY KEY  (`sid`),
                  UNIQUE KEY `long` (`surl_long`),
                  KEY `referrals` (`sreferrals`)
                ) ENGINE=MyISAM DEFAULT CHARSET=utf8;" 
            );  
        }*/
        
        $r = quickQuery( 'SELECT sid as result FROM ' . sql_table('shorturls') . ' WHERE surl_long ="' . $this->url_long.'"');        
        
        if( $r )
            return $r;
        
        return false;        
    }
    
    
    private function createRecord() {
    
        // URL not in database, insert
        sql_query('LOCK TABLES ' . sql_table('shorturls')  . ' WRITE;');
        sql_query('INSERT INTO ' . sql_table('shorturls') . ' (surl_long, screated, screator) VALUES ("' . addslashes($this->url_long) . '", "' . time() . '", "' . addslashes($_SERVER['REMOTE_ADDR']) . '")');
        $this->url_short = $this->getSurlFromID(mysql_insert_id());
        sql_query('UNLOCK TABLES');
 
        return $this->url_short;
    }
    
        
    private function cache() {
        
        if(is_file($this->cache_dir . $this->id))
            $url_long = file_get_contents($this->cache_dir . $this->id);
                
        if( empty( $url_long ) || !preg_match( '|^https?://|', $url_long ) ) {
            $r = quickQuery( 'SELECT surl_long as result FROM ' . sql_table('shorturls') . ' WHERE sid = "' . $this->id . '"');
            //@mkdir(CACHE_DIR, 0777);
            $handle = fopen($this->cache_dir . $this->id, 'w+');
            fwrite($handle, $r);
            fclose($handle);
        }
        
        return true;
        
    }
    
    
    private function clearDb() {
        global $CONF;
        
        $query = 'TRUNCATE TABLE '. sql_table('shorturls');
        
        if(!sql_query($query))
            echo 'Error emptying database<br />';
    
        $this->url_long = $CONF['IndexURL'];
         
         // check if record exists and if so offer it
         if(true == ( $r = $this->recordExists() ) )
             return $this->url_short = $this->getSurlFromId($r);
         
         // if not create it
         $this->url_short =  $this->createRecord();
 
        return true;
        
    }
    
 
}
 
?>
 

URL Buffer

The following is a change log of URL updates:

©2012. All rights reserved.