<?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

final class HitCounter extends CGExtensions
{
    public function GetName() { return 'HitCounter'; }
    public function GetAdminDescription() { return $this->Lang('moddescription');  }
    public function GetAdminSection() { return 'siteadmin'; }
    public function GetAuthor() { return 'calguy1000'; }
    public function GetAuthorEmail() { return 'calguy1000@cmsmadesimple.org'; }
    public function GetChangeLog() { return @file_get_contents(__DIR__.'/doc/changelog.inc'); }
    public function GetFriendlyName() { return $this->Lang('friendlyname'); }
    public function GetVersion() { return '2.1.2'; }
    public function GetDependencies() { return array('CGExtensions'=>'1.54'); }
    public function HasAdmin() { return true;  }
    public function MinimumCMSVersion () { return '2.1.6'; }
    public function IsPluginModule() { return TRUE; }
    public function UninstallPostMessage() { return $this->Lang('postuninstall'); }
    public function AllowAutoInstall() { return FALSE; }
    public function AllowAutoUpgrade() { return FALSE; }
    public function LazyLoadFrontend() { return TRUE; }
    public function LazyLoadAdmin() { return TRUE; }

    public function VisibleToAdminUser() {
        return $this->CheckPermission('Modify Site Preferences');
    }

    public function InitializeFrontend()
    {
        $this->RegisterModulePlugin();
        $this->RestrictUnknownParams();
        $this->SetParameterType('key1',CLEAN_STRING);
        $this->SetParameterType('key2',CLEAN_STRING);
        $this->SetParameterType('key3',CLEAN_STRING);
        $this->SetParameterType('opt',CLEAN_STRING);
        $this->SetParameterType('limit',CLEAN_INT);
        $this->SetParameterType('popular_template',CLEAN_STRING);
    }

    public function InitializeAdmin()
    {
        $this->CreateParameter('action','default',$this->Lang('help_param_action'));
        $this->CreateParameter('key1','<page id>',$this->Lang('help_param_key1'));
        $this->CreateParameter('key2','',$this->Lang('help_param_key2'));
        $this->CreateParameter('key3','',$this->Lang('help_param_key3'));
        $this->CreateParameter('opt','hits',$this->Lang('help_param_opt'));
        $this->CreateParameter('limit',10,$this->Lang('help_param_limit'));
    }

    private function _DisplayErrorPage($id, &$params, $returnid, $message='')
    {
        $smarty = cmsms()->GetSmarty();
        $smarty->assign ('title_error', $this->Lang ('error'));
        if ($message != '')	$smarty->assign ('message', $message);

        // Display the populated template
        echo $this->ProcessTemplate ('error.tpl');
    }


    /*---------------------------------------------------------
      _testip($range,$ip)
      NOT PART OF THE MODULE API

      This is a function to match an IP address against an
      address range specification.
      ---------------------------------------------------------*/
    public function _testip($range,$ip)
    {
        $result = 1;

        # IP Pattern Matcher
        # J.Adams <jna@retina.net>
        #
        # Matches:
        #
        # xxx.xxx.xxx.xxx        (exact)
        # xxx.xxx.xxx.[yyy-zzz]  (range)
        # xxx.xxx.xxx.xxx/nn    (nn = # bits, cisco style -- i.e. /24 = class C)
        #
        # Does not match:
        # xxx.xxx.xxx.xx[yyy-zzz]  (range, partial octets not supported)

        if (preg_match("/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\/([0-9]+)/",$range,$regs)) {

            # perform a mask match
            $ipl = ip2long($ip);
            $rangel = ip2long($regs[1] . "." . $regs[2] . "." . $regs[3] . "." . $regs[4]);

            $maskl = 0;

            for ($i = 0; $i< 31; $i++) {
                if ($i < $regs[5]-1) $maskl = $maskl + pow(2,(30-$i));
            }

            if (($maskl & $rangel) == ($maskl & $ipl)) {
                return 1;
            }
            else {
                return 0;
            }
        }
        else {
            # range based
            $maskocts = split("\.",$range);
            $ipocts = split("\.",$ip);

            # perform a range match
            for ($i=0; $i<4; $i++) {
                if (preg_match("/\[([0-9]+)\-([0-9]+)\]/",$maskocts[$i],$regs)) {
                    if ( ($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) $result = 0;
                }
                else {
                    if ($maskocts[$i] <> $ipocts[$i]) $result = 0;
                }
            }
        }
        return $result;
    }

    public static function page_type_lang_callback($str)
    {
        $mod = cms_utils::get_module('HitCounter');
        if( is_object($mod) ) return $mod->Lang('type_'.$str);
    }

    public static function reset_page_type_defaults(CmsLayoutTemplateType $type)
    {
        $mod = cms_utils::get_module('HitCounter');
        if( $type->get_originator() != $mod->GetName() ) throw new CmsLogicException('Cannot reset contents for this template type');

        $fn = null;
        switch( $type->get_name() ) {
        case 'popular':
            $fn = 'orig_popular.tpl';
            break;
        }

        $fn = __DIR__.'/templates/'.$fn;
        if( file_exists($fn) ) return @file_get_contents($fn);
    }

} // class
