<?php
/*

 $LastChangedDate: 2012-05-28 15:14:57 +0300 (Mon, 28 May 2012) $
 $Rev: 1164 $
 $Author: maborak $
 $Id: geostats.php 1164 2012-05-28 12:14:57Z maborak $
 $HeadURL: svn://source.maborak.com/release/interspire/email.marketer/addons/geostats/geostats.php $
 
 +--------------------------------------------------------------------------------
 |   GeoLocation Stadistics
 |   Copyright (C) 2012 Maborak Technologies <maborak@maborak.com>
 +--------------------------------------------------------------------------------
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
*/
if (! class_exists('Interspire_Addons', false))
{
    require_once (dirname(dirname(__FILE__)) . '/interspire_addons.php');
}
require_once (dirname(__FILE__) . '/language/language.php');
class Addons_geostats extends Interspire_Addons
{
    private $addon_name = "geostats";
    public function Install ()
    {
        $tables = $sequences = array();
        if (! $this->isEnabled("installer"))
        {
            throw new Interspire_Addons_Exception(
            "The Addon (Advanced Addons Installer) is required", 
            Interspire_Addons_Exception::AddonDoesntExist);
        } else
        {
            $this->Process("installer", "GetApi", "installer")->install(
            $this->addon_name);
        }
        $this->db->StartTransaction();
        require dirname(__FILE__) . '/schema.' . SENDSTUDIO_DATABASE_TYPE .
         '.php';
        foreach ($queries as $query)
        {
            $qry = str_replace('%%TABLEPREFIX%%', $this->db->TablePrefix, 
            $query);
            $result = $this->db->Query($qry);
            if (! $result)
            {
                $this->db->RollbackTransaction();
                throw new Interspire_Addons_Exception(
                "There was a problem running query " . $qry . ": " .
                 $this->db->GetErrorMsg(), 
                Interspire_Addons_Exception::DatabaseError);
            }
        }
        /*
         * Install the Geo data
         * LOAD DATA LOCAL INFILE '/var/lib/phpmyadmin/tmp/phprJfCKU' INTO TABLE `geo` FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n'
         */
        $result = $this->db->Query(
        "SELECT COUNT(*) as total FROM " . SENDSTUDIO_TABLEPREFIX . "geostats");
        $row = $this->db->Fetch($result);
        if ((int) $row['total'] < 1548448)
        {
            //$lquery="LOAD DATA LOCAL INFILE '".$this->addon_base_directory . $this->addon_id . '/api/'."ip.csv' INTO TABLE `{$this->db->TablePrefix}geostats` FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\' LINES TERMINATED BY '\r\n'";
            $lquery = "LOAD DATA LOCAL INFILE '" . $this->addon_base_directory . $this->addon_id . '/api/' . "ip.csv' INTO TABLE `{$this->db->TablePrefix}geostats` FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\r\\n'"; 
            $result = $this->db->Query($lquery);

            if (! $result)
            {
                $this->db->RollbackTransaction();
                throw new Interspire_Addons_Exception(
                "There was a problem running query " . $lquery . ": " .
                 $this->db->GetErrorMsg(), 
                Interspire_Addons_Exception::DatabaseError);
            }
        }
        $result = $this->db->Query ( "SELECT country_code FROM " . SENDSTUDIO_TABLEPREFIX . "stats_emailopens LIMIT 1" );
		if (!$result)
		{
			$result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_emailopens` ADD `country_code` VARCHAR( 255 ) NOT NULL DEFAULT '-'" );
		}
        $result = $this->db->Query ( "SELECT country_name FROM " . SENDSTUDIO_TABLEPREFIX . "stats_emailopens LIMIT 1" );
		if (!$result)
		{
			$result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_emailopens` ADD `country_name` VARCHAR( 255 ) NOT NULL DEFAULT '-'" );
		}
        $result = $this->db->Query ( "SELECT region FROM " . SENDSTUDIO_TABLEPREFIX . "stats_emailopens LIMIT 1" );
		if (!$result)
		{
			$result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_emailopens` ADD `region` VARCHAR( 255 ) NOT NULL DEFAULT '-'" );
		}
        $result = $this->db->Query ( "SELECT city FROM " . SENDSTUDIO_TABLEPREFIX . "stats_emailopens LIMIT 1" );
		if (!$result)
		{
			$result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_emailopens` ADD `city` VARCHAR( 255 ) NOT NULL DEFAULT '-'" );
		}
		// link clicks
        $result = $this->db->Query ( "SELECT country_code FROM " . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks LIMIT 1" );
		if (!$result)
		{
			$result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks` ADD `country_code` VARCHAR( 255 ) NOT NULL DEFAULT '-'" );
		}
        $result = $this->db->Query ( "SELECT country_name FROM " . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks LIMIT 1" );
		if (!$result)
		{
			$result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks` ADD `country_name` VARCHAR( 255 ) NOT NULL DEFAULT '-'" );
		}
        $result = $this->db->Query ( "SELECT region FROM " . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks LIMIT 1" );
		if (!$result)
		{
			$result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks` ADD `region` VARCHAR( 255 ) NOT NULL DEFAULT '-'" );
		}
        $result = $this->db->Query ( "SELECT city FROM " . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks LIMIT 1" );
		if (!$result)
		{
			$result = $this->db->Query ( "ALTER TABLE `" . SENDSTUDIO_TABLEPREFIX . "stats_linkclicks` ADD `city` VARCHAR( 255 ) NOT NULL DEFAULT '-'" );
		}
        $this->enabled = true;
        $this->configured = true;
        try
        {
            $status = parent::Install();
        } catch (Interspire_Addons_Exception $e)
        {
            $this->db->RollbackTransaction();
            throw new Exception(
            "Unable to install addon {$this->GetId()} " . $e->getMessage());
        }
        $this->db->CommitTransaction();
        return true;
    }
    public function UnInstall ()
    {
        $tables = $sequences = array();
        if (! $this->isEnabled("installer"))
        {
            throw new Interspire_Addons_Exception(
            "The Addon (Advanced Addons Installer) is required", 
            Interspire_Addons_Exception::AddonDoesntExist);
        } else
        {
            $this->Process("installer", "GetApi", "installer")->uninstall(
            $this->addon_name);
        }
        $this->db->StartTransaction();
        try
        {
            $this->Disable();
        } catch (Interspire_Addons_Exception $e)
        {
            $this->db->RollbackTransaction();
            throw new Interspire_Addons_Exception($e->getMessage(), 
            $e->getCode());
        }
        require dirname(__FILE__) . '/schema.' . SENDSTUDIO_DATABASE_TYPE .
         '.php';
        try
        {
            $status = parent::UnInstall();
        } catch (Interspire_Addons_Exception $e)
        {
            $this->db->RollbackTransaction();
            throw new Interspire_Addons_Exception($e->getMessage(), 
            $e->getCode());
        }
        $this->db->CommitTransaction();
        return true;
    }
    public function Enable ()
    {
        //$this->db->Query("INSERT INTO [|PREFIX|]settings_cron_schedule(jobtype, lastrun) VALUES ('" . $this->db->Quote($this->addon_id) . "', 0)");

        try
        {
            $status = parent::Enable();
        } catch (Interspire_Addons_Exception $e)
        {
            throw new Interspire_Addons_Exception($e->getMessage(), 
            $e->getCode());
        }
        return true;
    }
    public function Disable ()
    {
        //$job_check = "SELECT COUNT(jobid) AS jobcount FROM [|PREFIX|]jobs WHERE jobtype='splittest' AND jobstatus NOT IN ('c')";

        try
        {
            $status = parent::Disable();
        } catch (Interspire_Addons_Exception $e)
        {
            throw new Interspire_Addons_Exception($e->getMessage(), 
            $e->getCode());
        }
        return true;
    }
    public function Admin_Action_Default ()
    {return;
    	$api=$this->GetApi();
    	$countries=$api->get_countries();
    	//print_r($countries);
    	foreach ($countries as $k=>$v)
    	{
    		$flag = "http://www.ip2location.com/images/flags/".strtolower($v['country_code']).".png";
    		echo $flag."<br>";
    		$f=dirname(__FILE__)."/templates/flags/".strtoupper($v['country_code']).".png";
    		echo $f."<br>";
    		$data=file_get_contents($flag);
    		file_put_contents($f,$data);
    	}
        return;
        $ip = "24.232.163.204";
        //$ip=$_SERVER['REMOTE_ADDR'];
        $api=$this->GetApi();
        //$ro=$api->process_emailopens(1000);
        //$rc=$api->process_emailclicks(5000);
        /*FlashMessage(sprintf(GetLang("Addon_geostats_emailopens"),$ro[0],$ro[1]),SS_FLASH_MSG_SUCCESS);
        FlashMessage(sprintf(GetLang("Addon_geostats_emailclicks"),$rc[0],$rc[1]),SS_FLASH_MSG_SUCCESS);
        $this->template_system->assign('result',GetFlashMessages());*/
		//$this->template_system->ParseTemplate('manage');
    }
    public function Admin_Action_Gc()
    {
    	$api=$this->GetApi();
    	$statid=(isset($_GET['statid']))?(int)$_GET['statid']:0;
    	$t=(isset($_GET['t']))?$_GET['t']:'o';
    	$country=(isset($_GET['c']))?$_GET['c']:false;
    	$data=($t=="o")?$api->get_openners($statid,3000,false,$country):$api->get_clickers($statid,3000,false,$country);
    	$data_rc=array();
    	$data_r=array();
        //ini_set('memory_limit', '564M');
    	foreach ($data as $k=>$v)
    	{
    	    if (trim($v['region'])=="DISTRITO FEDERAL")
    	    {
    	        $v['region']=$v['city'];
    	    }
    	    $_r=$v['region'];
    	    $_t=(int)$v['total'];
    	    if (array_key_exists($_r,$data_rc))
    	    {
    	        $data_rc[$_r]=$data_rc[$_r]+$_t;
    	    }
    	    else
    	    {
    	        $data_rc[$_r]=$_t;
    	    }
    	}
    	foreach ($data_rc as $k=>$v)
    	{
    	    if (trim(strtolower($k))=="mexico")
    	    {
    	        $k=utf8_encode("Mˇxico");
    	    }
    	    $_region=addslashes($k);
    	    $data_r[]=array("region"=>$_region,"total"=>$v);
    	}
    	unset($data_rc);
    	$region=str_replace("UK","GB",$country);
    	$this->template_system->assign('t',$t);
    	$this->template_system->assign('dtype',($t=="o")?"Opens":"Clicks");
    	$this->template_system->assign('data_mode',"regions");
    	$this->template_system->assign('region',$region);
    	$this->template_system->assign('country',$country);
    	$this->template_system->assign('statid',$statid);
    	$this->template_system->assign('data_r',$data_r);
    	$this->template_system->assign('data_rhtml',$api->format($data_r));
    	$this->template_system->assign('data_count',count($data_r));
        $this->template_system->assign('data_raw',$data);
    	$this->template_system->assign('data',$api->format($data));
    	$this->template_system->ParseTemplate('show_city');
    }
    public function Admin_Action_Export()
    {
    	$api=$this->GetApi();
    	$statid=(isset($_GET['statid']))?(int)$_GET['statid']:0;
    	$t=(isset($_GET['t']))?$_GET['t']:'o';
    	$country=(isset($_GET['c']))?$_GET['c']:false;
    	$region=(isset($_GET['region']))?$_GET['region']:false;
    	$city=(isset($_GET['city']))?$_GET['city']:false;
    	header("Content-type: text/csv");
		header("Cache-Control: no-store, no-cache");
		header('Content-Disposition: attachment; filename="geostats_'.$country.'.csv"');
		echo "'Email','IP',Country Code','Country Name','Region','City'".PHP_EOL;
    	$data=($t=="o")?$api->export_openners($statid,$country,$region,$city):$api->export_clickers($statid,$country,$region,$city);
    }
    function GetEventListeners ()
    {
        $my_file = "{%IEM_ADDONS_PATH%}/{$this->addon_name}/{$this->addon_name}.php";
        $listeners = array();
        //$listeners[] = array('eventname' => 'IEM_SENDSTUDIOFUNCTIONS_GENERATETEXTMENULINKS' , 'trigger_details' => array('Addons_geostats' , 'SetMenuItems') , 'trigger_file' => $my_file);
        $listeners[] = array(
        	'eventname' => 'IEM_USERAPI_GETPERMISSIONTYPES', 
        	'trigger_details' => array('Interspire_Addons', 'GetAddonPermissions'), 'trigger_file' => $my_file
        );
        return $listeners;
    }
	public function Configure()
	{
		foreach ($this->settings as $k => $v) {
			$this->template_system->Assign($k, $v);
		}
		return $this->settings_url;
		//return $this->template_system->ParseTemplate('settings', true);
	}
    static function SetMenuItems (EventData_IEM_SENDSTUDIOFUNCTIONS_GENERATETEXTMENULINKS $data)
    {
        $user = &GetUser();
        $self = new self();
        $menuItems = $data->data;
        //$menuItems['tools'][] = array('text' => 'Process Geo Location cache' , 'link' => 'index.php?Page=Addons&Addon=geostats' , 'show' => $user->isAdmin() , 'description' => '' , 'image' => 'templates_view.gif');
        $data->data = $menuItems;
    }
	static function RegisterAddonPermissions()
	{
		$description = self::LoadDescription('geostats');
		$perms = array (
			'geostats' => array (
				'addon_description' => "MT: Geolocation Statistics - Addon",
				'gc' => array('name' => "View Region/City"),
				'export' => array('name' => "Export Country/Region/City")
			)
		);
		self::RegisterAddonPermission($perms);
	}
    protected function GetApi ($api = 'Geostats')
    {
        $api = (is_array($api)) ? $api[0] : $api;
        $path = $this->addon_base_directory . $this->addon_id . '/api/' .
         strtolower($api) . '.php';
        if (! is_file($path))
        {
            return false;
        }
        require_once $path;
        $class = $api . '_API';
        $api = new $class();
        $api->template_system = $this->template_system;
        $api->addon_base_directory=$this->addon_base_directory;
        $api->addon_id=$this->addon_id;
        return $api;
    }
}

