Your IP : 216.73.216.240


Current Path : /home/juvelize/www/plugins/system/cwtrafficonline/
Upload File :
Current File : /home/juvelize/www/plugins/system/cwtrafficonline/cwtrafficonline.php

<?php

/**
 * @package     Joomla
 * @subpackage  CoalaWeb Traffic
 * @author      Steven Palmer <support@coalaweb.com>
 * @link        https://coalaweb.com/
 * @license     GNU/GPL V3 or later; https://www.gnu.org/licenses/gpl-3.0.html
 * @copyright   Copyright (c) 2021 Steven Palmer All rights reserved.
 *
 * CoalaWeb Traffic 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 3 of the License, or
 * (at your option) any later version.
 * 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.
 */

defined('_JEXEC') or die('Restricted access');

JLoader::import('joomla.plugin.plugin');
JLoader::import('joomla.application.plugin');
JLoader::import('joomla.log.log');
JLoader::import('joomla.filesystem.path');
JLoader::import('joomla.filesystem.file');
JLoader::import('joomla.html.parameter');
JLoader::import('joomla.application.component.helper');

//Helpers
$helpPath  = '/components/com_coalawebtraffic/helpers/';
JLoader::register('CoalawebtrafficHelperIptools', JPATH_ADMINISTRATOR . $helpPath  . 'iptools.php');
JLoader::register('CoalawebtrafficHelperLocation', JPATH_ADMINISTRATOR . $helpPath  . 'location.php');
JLoader::register('CoalawebtrafficHelperDetect', JPATH_ADMINISTRATOR . $helpPath  . 'detect.php');
JLoader::register('CoalawebtrafficHelperTools', JPATH_ADMINISTRATOR . $helpPath  . 'tools.php');

class plgSystemCwtrafficOnline extends JPlugin
{
    private $checkOk;
    private $debug;
    private $comParams;

    /**
     * Constructor
     *
     * @param   object $subject The object to observe
     * @param   array $config An array that holds the plugin configuration
     */
    public function __construct(&$subject, $config)
    {
        parent::__construct($subject, $config);

        // Load the language files
        $jlang = JFactory::getLanguage();

        // Plugin
        $jlang->load('plg_system_cwtrafficonline', JPATH_ADMINISTRATOR, 'en-GB', true);
        $jlang->load('plg_system_cwtrafficonline', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
        $jlang->load('plg_system_cwtrafficonline', JPATH_ADMINISTRATOR, null, true);

        // Component
        $jlang->load('com_coalawebtraffic', JPATH_ADMINISTRATOR, 'en-GB', true);
        $jlang->load('com_coalawebtraffic', JPATH_ADMINISTRATOR, $jlang->getDefault(), true);
        $jlang->load('com_coalawebtraffic', JPATH_ADMINISTRATOR, null, true);

        // Classes that are needed
        $assets = [
            'mobile' => false,
            'count' => false,
            'tools' => true,
            'latest' => false
        ];

        $extensions = array(
            'components' => array(
                'com_coalawebtraffic'
            ),
            'modules' => array(
            ),
            'plugins' => array(
            )
        );

        // Lets get our helper functions
        $comHelp = new CoalawebtrafficHelperTools();

        $this->checkOk = $comHelp::checkDependencies('PLG_CWTRAFFICONLINE', $assets, $extensions);
        $this->comParams = JComponentHelper::getParams('com_coalawebtraffic');
        $this->debug = null !== $this->params->get('debug') ? $this->params->get('debug') : $this->comParams->get('debug', '0');
    }

    public function onAfterRoute()
    {
        $app = JFactory::getApplication();
        $client = JFactory::getApplication()->client;

        if ($client->robot || $app->getName() !== 'site') {
            return;
        }

        // Dependency checks
        if ($this->checkOk['ok'] === false) {
            if ($this->debug === '1') {
                $app->enqueueMessage($this->checkOk['msg'], $this->checkOk['type']);
            }
            return;
        }

        $comParams = JComponentHelper::getParams('com_coalawebtraffic');

        $db = JFactory::getDbo();

        if ($comParams->get('log_sql')) {
            //Start our log file code
            JLog::addLogger(array('text_file' => 'com_coalawebtraffic_sql.log.php'), JLog::ERROR, 'com_coalawebtraffic_sql');
        }

        // Should we store a cookie? If not remove old cookie, clear DB and then return
        if (!$comParams->get('set_cookie', 1)){
            if (isset($_COOKIE['cwGeoData'])) {
                unset($_COOKIE['cwGeoData']);
                setcookie('cwGeoData', '', time() - 3600, '/'); // empty value and old timestamp
            }

            try {
                $db->setQuery('TRUNCATE TABLE ' . $db->qn('#__cwtraffic_whoisonline'));
                $db->execute();
            } catch (JDatabaseExceptionExecuting $e) {
                if ($comParams->get('log_sql')) {
                    //Log error
                    $msg = JText::sprintf('COM_CWTRAFFIC_DATABASE_ERROR', $e->getMessage());
                    JLog::add($msg, JLog::ERROR, 'com_coalawebtraffic_sql');
                }
            }
            return;
        }

        //Lets check if our classes exist and if not display a nice graceful message
        if (
            !class_exists('CoalawebtrafficHelperIptools') ||
            !class_exists('CoalawebtrafficHelperLocation') ||
            !class_exists('CoalawebtrafficHelperDetect')
        ) {
            if ($this->debug === '1') {
                $app->enqueueMessage(JText::_('COM_CWTRAFFIC_MSG_MISSING'), 'error');
            }
            return;
        }

        if ($comParams->get('log_sql')) {
            //Start our log file code
            JLog::addLogger(array('text_file' => 'com_coalawebtraffic_sql.log.php'), JLog::ERROR, 'com_coalawebtraffic_sql');
        }

        // Load version.php
        $version_php = JPATH_ADMINISTRATOR . '/components/com_coalawebtraffic/version.php';
        if (!defined('COM_CWTRAFFIC_VERSION') && JFile::exists($version_php)) {
            include_once $version_php;
        }

        //Get the users IP
        $stringIp = CoalawebtrafficHelperIptools::getUserIp();
        $intIp = ip2long($stringIp);

        //Check the Who is Online table for IPs
        $query = $db->getQuery(true);
        $query->select('count(*)');
        $query->from($db->qn('#__cwtraffic_whoisonline'));
        $query->where('iphash = UNHEX(SHA1(' . $db->q($intIp) . ')) OR ip = ' . $db->q($intIp));

        try {
            $db->setQuery($query);
            $inDB = $db->loadResult();
        } catch (JDatabaseExceptionExecuting $e) {
            $inDB = '';
            if ($comParams->get('log_sql')) {
                //Log error
                $msg = JText::sprintf('COM_CWTRAFFIC_DATABASE_ERROR', $e->getMessage());
                JLog::add($msg, JLog::ERROR, 'com_coalawebtraffic_sql');
            }
        }

        if (!$inDB) {
            if (isset($_COOKIE['cwGeoData'])) {
                $cookie = $_COOKIE['cwGeoData'];
            }

            if (!empty($cookie)) {
                // A "geoData" cookie has been previously set by the script, so we will use it
                // Always escape any user input, including cookies:
                list($city, $countryName, $countryCode) = explode('|', strip_tags($cookie));
            } else {

                //Lets get some info on our IP
                if (CoalawebtrafficHelperLocation::geodatExist()) {
                    $details = CoalawebtrafficHelperLocation::geoInfo($stringIp);
                }

                $city = !empty($details['city']) ? $details['city'] : "unknown city";
                $countryName = !empty($details['country_name']) ? $details['country_name'] : "unknown country";
                $countryCode = !empty($details['country_code']) ? $details['country_code'] : "xx";

                // Setting a cookie with the data, which is set to expire in a month:
                setcookie('cwGeoData', $city . '|' . $countryName . '|' . $countryCode, time() + 60 * 60 * 24 * 30, '/');
            }

            $query = $db->getQuery(true);
            $query->insert($db->qn('#__cwtraffic_whoisonline'));

            $query->columns('ip, country_name, country_code, city,  dt');
            $query->values($db->q($intIp) . ', ' . $db->q($countryName) . ',' . $db->q($countryCode) . ',' . $db->q($city) . ',NOW()');


            try {
                $db->setQuery($query);
                $db->execute();
            } catch (JDatabaseExceptionExecuting $e) {
                if ($comParams->get('log_sql')) {
                    //Log error
                    $msg = JText::sprintf('COM_CWTRAFFIC_DATABASE_ERROR', $e->getMessage());
                    JLog::add($msg, JLog::ERROR, 'com_coalawebtraffic_sql');
                }
            }
        } else {
            // If the visitor is already online, just update the dt value of the row:
            $query = $db->getQuery(true);
            $query->update($db->qn('#__cwtraffic_whoisonline'));
            $query->set('dt = NOW()');
            $query->where('iphash = UNHEX(SHA1(' . $db->q($intIp) . ')) OR ip = ' . $db->q($intIp));

            try {
                $db->setQuery($query);
                $db->execute();
            } catch (JDatabaseExceptionExecuting $e) {
                if ($comParams->get('log_sql')) {
                    //Log error
                    $msg = JText::sprintf('COM_CWTRAFFIC_DATABASE_ERROR', $e->getMessage());
                    JLog::add($msg, JLog::ERROR, 'com_coalawebtraffic_sql');
                }
            }
        }
        $query = $db->getQuery(true);
        $query->delete($db->qn('#__cwtraffic_whoisonline'));
        $query->where("dt < SUBTIME(NOW(),'0 0:10:0')");

        try {
            $db->setQuery($query);
            $db->execute();
        } catch (JDatabaseExceptionExecuting $e) {
            if ($comParams->get('log_sql')) {
                //Log error
                $msg = JText::sprintf('COM_CWTRAFFIC_DATABASE_ERROR', $e->getMessage());
                JLog::add($msg, JLog::ERROR, 'com_coalawebtraffic_sql');
            }
        }
    }
}