<?php
#BEGIN_LICENSE
#-------------------------------------------------------------------------
# Module: HitCounter (c) 2009-2014 by Robert Campbell
#         (calguy1000@cmsmadesimple.org)
#  An addon module for CMS Made Simple to allow management of frontend
#  users, and their login process within a CMS Made Simple powered
#  website.
#
#-------------------------------------------------------------------------
# CMS - CMS Made Simple is (c) 2009 by Ted Kulp (wishy@cmsmadesimple.org)
# This projects homepage is: http://www.cmsmadesimple.org
#
#-------------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# However, as a special exception to the GPL, this software is distributed
# as an addon module to CMS Made Simple.  You may not use this software
# in any Non GPL version of CMS Made simple, or in any version of CMS
# Made simple that does not indicate clearly and obviously in its admin
# section that the site was built with CMS Made simple.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
#END_LICENSE
if( !isset($gCms) ) exit;


/*---------------------------------------------------------
 _HandleHit($id, &$params, $returnid)
 ---------------------------------------------------------*/
if( !function_exists('hitcounter_HandleHit')) {
    function hitcounter_HandleHit(&$module, $id, &$params, $returnid)
    {
        $db = cmsms()->GetDb();
        $ip = getenv("REMOTE_ADDR");
        $agent = $_SERVER["HTTP_USER_AGENT"];

        $key1 = cge_utils::get_param($params,'key1');
        $key2 = cge_utils::get_param($params,'key2');
        $key3 = cge_utils::get_param($params,'key3');
        if( $key1 == '' ) {
            $key1 = 'Page';
            $key2 = $returnid;
        }

        if( $module->GetPreference('exclude_bots',1) ) {
            $browser = cge_utils::get_browser();
            if( $browser->IsRobot() ) {
                // yup, it's a bot.
                return TRUE;
            }
        }

        $config = cmsms()->GetConfig();
        if( !isset($config['hitcounter_debug']) ) {
            if( get_userid(FALSE) > 0 ) {
                // excluded logged in administrators.
                return TRUE;
            }

            // make sure we're not in the excluded ip range
            $subnet_exclusions = trim($module->GetPreference("subnet_exclusions"));
            if($subnet_exclusions != ""){
                $subnets = explode(",", $subnet_exclusions);
                $test = 0;
                foreach($subnets as $subnet) {
                    $test = $module->_testip( $subnet, $ip );
                    if( $test ) {
                        // don't allow any more processing
                        return TRUE;
                    }
                }
            }
        }

        // or an excluded user agent
        $agent_exclusions = trim($module->GetPreference("agent_exclusions"));
        if( isset( $_SERVER["HTTP_USER_AGENT"] ) && $agent_exclusions != "") {
            $agents = explode(",", $agent_exclusions);
            $test = 0;
            foreach($agents as $excl_agent) {
                if( preg_match( "/".$excl_agent."/", $agent ) )  {
                    // don't allow any more processing
                    return TRUE;
                }
            }
        }

        // todo: anonymize the user agent and ip address if so inclined.

        // then check to make sure we haven't set a hit from module person
        // within the last N minutes
        $timeout = $module->GetPreference("visit_timeout");
        $expr = sprintf("%d minutes ago",$timeout);
        $date1 = $db->DbTimeStamp(strtotime($expr, time()));
        $query = "SELECT id FROM ".cms_db_prefix()."module_hitcounter WHERE ip_address = ? AND date > $date1 AND key1 = ?";
        $qparms = array($ip,$key1);

        if( $key2 ) {
            $query .= ' AND key2 = ?';
            $qparms[] = $key2;

            if( $key3 )	{
                $query .= ' AND key3 = ?';
                $qparms[] = $key3;
            }
        }

        $tmp = $db->GetOne( $query, $qparms );
        if( $tmp ) {
            // there was a hit within the timeout period
            return TRUE;
        }

        // then add an entry into the database
        $now   = $db->DbTimeSTamp(time());
        $query = "INSERT INTO ".cms_db_prefix()."module_hitcounter (key1,key2,key3,returnid,ip_address,date,agent)
                  VALUES (?,?,?,?,?,$now,?)";
        $dbr = $db->Execute( $query, array( $key1, $key2, $key3, $returnid, $ip, $agent));
        return TRUE;
    }
} // function exists

////////////////////////////////////////////////////////////////////////////////
$key1 = cge_utils::get_param($params,'key1');
$key2 = cge_utils::get_param($params,'key2');
$key3 = cge_utils::get_param($params,'key3');
$mode = cge_utils::get_param($params,'opt','hits');
if( $key1 == '' ) {
    $key1 = 'Page';
    $key2 = $returnid;
}

if( !hitcounter_HandleHit( $this, $id, $params, $returnid ) ) return;

// now do something based on which option we're given
switch( $mode ) {
  case 'hits':
      // now echo the total number of hits for this page
      $count = 0;
      $query = "SELECT COUNT(id) as total FROM ".cms_db_prefix()."module_hitcounter WHERE key1 = ?";
      $qparms = array($key1);

      if( $key2 ) {
          $query .= ' AND key2 = ?';
          $qparms[] = $key2;

          if( $key3 ) {
              $query .= ' AND key3 = ?';
              $qparms[] = $key3;
          }
      }

      $count = $db->GetOne( $query, $qparms );
      echo $count;
      break;

  case 'hosts':
      $count = 0;
      $query = "SELECT count(DISTINCT ip_address) as total FROM ".cms_db_prefix()."module_hitcounter
                WHERE key1 = ?";
      $qparms = array($key1);

      if( $key2 ) {
          $query .= ' AND key2 = ?';
          $qparms[] = $key2;

          if( $key3 ) {
              $query .= ' AND key3 = ?';
              $qparms[] = $key3;
          }
      }

      $count = $db->GetOne($query,$qparms);
      echo $count;
      break;
}

#
# EOF
#