Location: PHPKode > scripts > Access Pattern Counter > access-pattern-counter/class.counter.php
<?php

//
// Class: Counter
// Table: counter
// Database: counter
/*
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      |      | PRI | NULL    | auto_increment |
| counter   | int(11)      |      |     | 0       |                |
| host      | varchar(255) | YES  |     | NULL    |                |
| page      | longtext     | YES  |     | NULL    |                |
| timestamp | datetime     | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
*/
// Generated by buildClass.php, written by Dick Munroe (hide@address.com)
//
// Edit History:
//
//	Dick Munroe (hide@address.com) 03-Nov-2005
//		Semantics of select changed.  Errors now require testing with "hasErrors" in order to sort out
//		the case between that and no data.
//
//	Dick Munroe (hide@address.com) 12-Jun-2006
//		The format of timestamps changed from sql V3 to V4.
//

include_once("class.counterUser.php") ;
include_once("SDD/class.SDD.php") ;
include_once("SQLData/class.SQLData.php") ;

class Counter extends SQLData
{

    //
    // Private (or constant) varibles.
    //

    var $m__current = 60 ;                              // Number of minutes a user is considered to be "current"
    var $m__host ;					// name of the host (allows multiple sites per database).
    var $m__page ;					// page on the host.
    var $m__remoteAddr ;				// fqdn or ip address of the accessing host.
    var $m__tableName = 'counter' ;

    //
    // Constructor
    //
    //  Create and, if necessary, increment a counter for a page.
    //
    // Parameters:
    //
    // 	$_database	Name of the database containing the counter tables.
    //	$_host		Name of the host running the MySQL server.  (Default: localhost)
    //	$_login		SQL user name.  (Default: "")
    //  $_password	SQL user password.  (Default: "")
    //  $_page 		Name of the counter.  (Default: $_SERVER['SCRIPT_NAME'])
    //	$_current	Number of minues this accessor is considered current for
    //			access to the page.  (Default: 60)
    //

    function Counter($_dataBase,
                     $_host="localhost",
                     $_login="",
                     $_password="",
                     $_page = null,
                     $_current = null)
    {
        if ($_page == null)
        {
            $this->m__page = $_SERVER['SCRIPT_NAME'] ;
        }
        else
        {
            $this->m__page = $_page ;
        }

        if ($_current != null)
        {
            $this->m__current = $_current ;
        }

		$this->m__host = $_SERVER['HTTP_HOST'] ;

        $this->m__remoteAddr = (empty($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_ADDR'] : $_SERVER['REMOTE_HOST']) ;

        $this->SQLData($this->m__tableName, $_dataBase, $_host, $_login, $_password) ;

        //
        // Create a counter in the table if one hasn't been implemented.
        //

        if (!$this->select("where host = '" . $this->escape_string($this->m__host) .
			   			   "' and page = '" . $this->escape_string($this->m__page) . "'"))
        {
			if ($this->hasErrors())
			{
	            $this->showErrors() ;
	            die("Can't select counter") ;
			}
        }

        if ($this->eof())
        {
	    $this->setHost($this->m__host) ;
            $this->setPage($this->m__page) ;
            $this->setCounter(0) ;
            $this->setTimestamp(date("YmdHis")) ;
            if (!$this->insert())
            {
                $this->showErrors() ;
                die("Can't insert counter") ;
            }
            $this->initId($this->fetchLastInsertId()) ;
        }

        $u = new CounterUser($this->getId(), $this->m__remoteAddr, $_dataBase, $_host, $_login, $_password) ;

        $ts = $u->getTimestamp() ;

        //
        // Convert MySQL V4 timestamps into canonical form.
        //

        $ts = preg_replace('/[: -.]+/', '', $ts) ;

        if (preg_match("/^0+$/", $ts))
        {
            //
            // This is a brand new user of the page, so belt out the timestamp.
            //

            $this->setCounter($this->getCounter()+1) ;

            if (!$this->update("where id = '" . $this->getId() . "'"))
            {
                $this->showErrors() ;
                die("Can't update counter") ;
            }

            $u->setTimestamp(null) ;

            if (!$u->update("where id = '" . $u->escape_string($u->getId()) . "'"))
            {
                $u->showErrors() ;
                die("Can't update user") ;
            }
        }
        else
        {
            $localTs = array(substr($ts, 8, 2),
                             substr($ts, 10, 2),
                             substr($ts, 12, 2),
                             substr($ts, 4, 2),
                             substr($ts, 6, 2),
                             substr($ts, 0, 4)) ;

            //
            // Add the increment of current to get when the timestamp expires.
            //

            $localTs[1] += $this->m__current ;
            $localTs = mktime($localTs[0], $localTs[1], $localTs[2], $localTs[3], $localTs[4], $localTs[5]) ;

            if (time() > $localTs)
            {
                //
                // It's been long enough, so increment another counter.
                //

                $this->setCounter($this->getCounter()+1) ;

                if (!$this->update("where id = '" . $this->getId() . "'"))
                {
                    $this->showErrors() ;
                    die("Can't update counter") ;
                }
            }

            //
            // Since this user has made yet another hit on the page, move his
            // window for a "new" hit into the future by remarking his
            // timestamp.  This avoids repeated hits on the page from being
            // incorrectly counted.  Keep track of the repeats in case of some
            // form of abuse.
            //

            $u->setTimestamp(null) ;

            $u->setRepeat($u->getRepeat()+1) ;

            if (!$u->update("where id = '" . $u->escape_string($u->getId()) . "'"))
            {
                $u->showErrors() ;
                die("Can't update user") ;
            }
        }
    }

    //
    // Accessor Functions
    //

    function setId($theValue)
    {
        $this->set('id', $theValue) ;
    }

    function getId()
    {
        return $this->get('id') ;
    }

    function initId($theValue)
    {
        $this->init('id', $theValue) ;
    }

    function setCounter($theValue)
    {
        $this->set('counter', $theValue) ;
    }

    function getCounter()
    {
        return $this->get('counter') ;
    }

    function initCounter($theValue)
    {
        $this->init('counter', $theValue) ;
    }

    function setHost($theValue)
    {
        $this->set('host', $theValue) ;
    }

    function getHost()
    {
        return $this->get('host') ;
    }

    function initHost($theValue)
    {
        $this->init('host', $theValue) ;
    }

    function setPage($theValue)
    {
        $this->set('page', $theValue) ;
    }

    function getPage()
    {
        return $this->get('page') ;
    }

    function initPage($theValue)
    {
        $this->init('page', $theValue) ;
    }

    function setTimestamp($theValue)
    {
        $this->set('timestamp', $theValue) ;
    }

    function getTimestamp()
    {
        return $this->get('timestamp') ;
    }

    function initTimestamp($theValue)
    {
        $this->init('timestamp', $theValue) ;
    }

    //
    // Return counter as a table, one digit per cell.
    //

    function oneDigitTable($theTableAttr = "", $theTDAttr = "", $theLength=0)
    {
        $theTable = "" ;

        $theCounter = sprintf("%0{$theLength}d", $this->getCounter()) ;

        for ($i = 0; $i < strlen($theCounter) ; $i++)
        {
            $theTable .= sprintf("<td%s>%s</td>",
                                 ($theTDAttr == "" ? "" : " " . $theTDAttr),
                                 substr($theCounter, $i, 1)) ;
        }

        return sprintf("<table%s>%s</table>", ($theTableAttr == "" ? "" : " " . $theTableAttr), $theTable) ;
    }

    //
    // Debugging Functions
    //

    function print_r()
    {
        print("class " . get_class($this) . " ") ;
        parent::print_r() ;
    }
}

?>
Return current item: Access Pattern Counter