<?php
class Affiliate_Scripts_Bl_BannerViewerOptimized
{
    var $db = null;
    var $logLevel = 0;
    var $BannerID = '';
    var $sourceURL = '';
    var $destURL = '';
    var $description = '';
    var $commissionType = '';
    var $UserID = '';
    var $AccountID = DEFAULT_ACCOUNT;
    var $bannerType = '';
    var $ccampaignID = '';
    var $CampaignID = '';
    var $CPMcomission = '';
    var $extraData1 = '';
    var $debugImps = '';
    var $User_refid = '';
    var $User_username = '';
    var $User_name = '';
    var $User_surname = '';
    var $AllowedCountry = true;
    var $uniqueImp = true;
    var $rotatorOutput = '';
    var $rotatorID = '';

    //--------------------------------------------------------------------------

    function setDb(&$db) {
        $this->db =& $db;
    }

    //--------------------------------------------------------------------------

    function process()
    {
        if(AFF_PROGRAM_TYPE == PROG_TYPE_PRO || AFF_PROGRAM_TYPE == PROG_TYPE_ECOMMAGNET) {
            $this->AccountID = DEFAULT_ACCOUNT;
        } else {
            $this->AccountID = $this->getAccountForDomain();

            if($this->AccountID == false) {
                $this->writeHistory(WLOG_ERROR, "Click registration: Cannot recognize account from domain '".getHostName()."'", __FILE__, __LINE__);
                return;
            }
        }

        $this->loadSettings();

        $this->writeHistory(WLOG_DEBUG, "BannerViewer: Start registering impression, params: ".PARAM_A_AID." ".$_GET[PARAM_A_AID]." ".PARAM_A_BID." ".$_GET[PARAM_A_BID], __FILE__, __LINE__);

        if(!isset($_GET[PARAM_A_BID]) || $_GET[PARAM_A_BID] == '' || !isset($_GET[PARAM_A_AID]) || $_GET[PARAM_A_AID] == '')
        {
            if(AFF_PROGRAM_TYPE == PROG_TYPE_PRO) {
                $this->writeHistory(WLOG_ERROR, "Show banner: Wrong parameters", __FILE__, __LINE__);
            }
            return false;
        }

        $bannerID = preg_replace('/[\'\"]/', '', $_GET[PARAM_A_BID]);
        $userID = preg_replace('/[\'\"]/', '', $_GET[PARAM_A_AID]);
        $data1 = preg_replace('/[\'\"]/', '', $_REQUEST[PARAM_DATA1]);

        $this->extraData1 = $data1;

        if(!$this->checkUserExists($userID)) {
            return false;
        }

        if(AFF_PROGRAM_TYPE != PROG_TYPE_PRO)
        {
            if($value = $this->getSetting('Aff_log_level')) {
                $this->logLevel = $value;
            }

            if($value = $this->getSetting('Aff_debug_impressions')) {
                $this->debugImps = $value;
            }
        }

        if($this->getSetting('Aff_force_aff_domains_approval') == '1')
        {
            if(!$this->checkInDomain())
            {
                $this->writeHistory(WLOG_DEBUG, "Show banner: Referal url not in affiliate allowed domains. Banner with ID '$bannerID'.", __FILE__, __LINE__);
                return;
            }
        }

        if(!$this->checkBannerExists($bannerID)) {
            return false;
        }

        $this->saveImpression($bannerID);

        if($this->commissionType & TRANSTYPE_CPM)
        {
            $this->updateCPMCommission();
        }

        $this->redirect();
        return true;
    }

    //--------------------------------------------------------------------------

    function loadSettings() {
        if($value = $this->getSetting('Aff_log_level')) {
            $this->logLevel = $value;
        }

        if($value = $this->getSetting('Aff_debug_impressions')) {
            $this->debugImps = $value;
        }
    }

    //--------------------------------------------------------------------------

    function getSetting($code) {
        $sql =  "select value from wd_g_settings ".
                "where rtype='".addslashes(SETTINGTYPE_ACCOUNT)."'".
                " and accountid='".addslashes($this->AccountID)."'".
                " and code='$code'";

        $rs =& $this->db->query($sql);
        if($rs && ($row = $rs->FetchRow())) {
            return $row['value'];
        }

        $this->writeHistory(WLOG_DEBUG, "Show banner: Setting with code:".$code." is missing or empty", __FILE__, __LINE__);

        return false;
    }

    //--------------------------------------------------------------------------

    function checkUserExists($userID)
    {
        $sql = "select userid, refid, accountid, username, name, surname from wd_g_users ".
            "where deleted=0 ".
            " and (userid='".addslashes($userID)."' or refid='".addslashes($userID)."')";
        $rs =& $this->db->query($sql);
        if(!$rs || !($row = $rs->FetchRow()))
        {
            if(AFF_PROGRAM_TYPE == PROG_TYPE_PRO) {
                $this->writeHistory(WLOG_ERROR, "Show banner: Affiliate with ID '".$userID."' doesn't exist", __FILE__, __LINE__);
            }
            return false;
        }

        $this->UserID = $row['userid'];
        $this->AccountID = $row['accountid'];
        $this->User_refid = $row['refid'];
        $this->User_username = $row['username'];
        $this->User_name = $row['name'];
        $this->User_surname = $row['surname'];

        return true;
    }

    //--------------------------------------------------------------------------

    function checkBannerExists($bannerID)
    {
        $sql = 'select b.sourceurl, b.description, b.destinationurl, b.bannertype, b.campaignid, c.commtype '.
                'from wd_pa_banners b, wd_pa_campaigns c '.
               "where b.campaignid=c.campaignid and b.bannerid='".addslashes($bannerID)."'".
               ' and b.deleted=0 and c.deleted=0';
        $rs =& $this->db->query($sql);
        if (!$rs || !($row = $rs->FetchRow())) {
            $this->writeHistory(WLOG_ERROR, "Show banner: Banner with ID '$bannerID' doesn't exist", __FILE__, __LINE__);
            return false;
        }

        $this->BannerID = $bannerID;
        $this->sourceURL = $row['sourceurl'];
        $this->description = $row['description'];
        $this->bannerType = $row['bannertype'];
        $this->commissionType = $row['commtype'];
        $this->CampaignID = $row['campaignid'];
        $this->destURL = $row['destinationurl'];

        return true;
    }

    //--------------------------------------------------------------------------

    function updateDescriptionArg($bannerID, $description, $clearDestinationUrl=false)
    {
        $sql = "update wd_pa_banners set description='".addslashes($description)."'";
        if ($clearDestinationUrl) {
            $sql .= ", destinationurl=''";
        }
        $sql .= " where bannerid='".addslashes($bannerID)."'";
        $rs =& $this->db->query($sql);
        if (!$rs) {
            $this->writeHistory(WLOG_ERROR, "Can't update rotator banner description with ID '$bannerID'", __FILE__, __LINE__);
            return false;
        }

        return true;
    }

    //--------------------------------------------------------------------------

    function clearDestinationUrls()
    {
        $sql = "update wd_pa_banners set destinationurl=''".
               " where bannertype='".addslashes(BANNERTYPE_ROTATOR)."'";
        $rs =& $this->db->query($sql);
        if (!$rs) {
            $this->writeHistory(WLOG_ERROR, "Can't clear destination urls", __FILE__, __LINE__);
            return false;
        }

        return true;
    }

    //--------------------------------------------------------------------------

    function updateDescription()
    {
        return $this->updateDescriptionArg($this->BannerID, $this->description);
    }

    //--------------------------------------------------------------------------

    function getBannerData($bannerID)
    {
        $sql = 'select * from wd_pa_banners '.
               "where bannerid='".addslashes($bannerID)."'".
               ' and deleted=0';
        $rs =& $this->db->query($sql);
        if (!$rs || !($row = $rs->FetchRow())) {
            $this->writeHistory(WLOG_ERROR, "Show banner: Banner with ID '$bannerID' doesn't exist", __FILE__, __LINE__);
            return false;
        }
        return $row;
    }

    //--------------------------------------------------------------------------

    function saveImpression($bannerID)
    {
        if($this->getSetting('Aff_blockimps') == '1') {
            if(isset($_COOKIE[COOKIE_NAME.'blockimps'])) {
                return false;
            } else {
                if(($blockTime = $this->getSetting('Aff_blockimps_time')) && ($blockTimeUnit = $this->getSetting('Aff_blockimps_timeunit'))) {
                    switch($blockTimeUnit) {
                        case 1:
                            $expireTime = time() + $blockTime * 3600;
                            break;
                        case 2:
                            $expireTime = time() + $blockTime * 60;
                            break;
                        case 3:
                        default:
                            $expireTime = time() + $blockTime;
                            break;
                    }
                    setcookie(COOKIE_NAME.'blockimps', time(), $expireTime, '/');
                }
            }
        }

        // geo-targetting check
        $country['__'] = array("countrycode" => '__', "countryname" => 'Unknown');

        if($this->getSetting('Glob_acct_geo_allowed') == '1') {
        	$ip = $_SERVER['REMOTE_ADDR'];
            $country = $this->getCountryForIp($ip);
            $this->AllowedCountry = true;
            if(!$this->isAllowedCountry($country) && ($this->getSetting('Glob_acct_geo_dont_register_imp') == '1')) {
                $this->AllowedCountry = false;
                $this->writeHistory(WLOG_DEBUG, "Impression registration: Country from IP '$ip' is not in list of allowed countries", __FILE__, __LINE__);
                return false;
            }
        }

        $rotator = ($this->bannerType == BANNERTYPE_ROTATOR);
        if ($rotator) {
            $this->processRotatorBanner();
        }

        $hourDate = date('Y-m-d H:00:00');

        // get impression record for this hour
        $sql = "select impressionid, all_imps_count, unique_imps_count from wd_pa_impressions ".
            "where bannerid='".addslashes($this->BannerID)."' and affiliateid='".addslashes($this->UserID)."'".
            "  and dateimpression='".addslashes($hourDate)."'".
            "  and country='".addslashes($country['countrycode'])."'".
            "  and accountid='".addslashes($this->AccountID)."'".
            "  and commissiongiven=0".
            "  and data1='".addslashes($this->extraData1)."'";
        if ($rotator) {
            $sql .= "  and rotatorid="._q($this->rotatorID);
        }
        $rs =& $this->db->query($sql);
        if(!$rs)
        {
            $this->writeHistory(WLOG_ERROR,"Show banner: Error getting last impression", __FILE__, __LINE__);
            return false;
        }
        $this->uniqueImp = true;
        if(!($row = $rs->FetchRow()))
        {
            // insert record
            $impressionID = $this->db->createUniqueId();
            //$impressionID = QCore_Sql_DBUnit::createUniqueID('wd_pa_impressions', 'impressionid');
            $sql = "insert into wd_pa_impressions(impressionid,dateimpression,".
                "accountid,bannerid,rotatorid,affiliateid,all_imps_count,unique_imps_count, commissiongiven, data1, country)".
                "values('".addslashes($impressionID)."','".addslashes($hourDate).
                "','".addslashes($this->AccountID)."','".addslashes($this->BannerID)."','".addslashes($this->rotatorID).
                "','".addslashes($this->UserID)."',1,1,0,'".addslashes($this->extraData1).
                "','".addslashes($country['countrycode'])."')";

            $ret =& $this->db->query($sql);
            if (!$ret)
            {
                $this->writeHistory(WLOG_ERROR,"Show banner: Error saving impression", __FILE__, __LINE__);
                return false;
            }
        }
        else
        {
            $allImps = $row['all_imps_count'] + 1;
            $uniqueImps = $row['unique_imps_count'];
            $ipmId = $row['impressionid'];

            if($_COOKIE[COOKIE_NAME.'imp'] == '') {
                $uniqueImps++;
            } else {
                $this->uniqueImp = false;
            }

            // update record
            $sql = "update wd_pa_impressions ".
                " set all_imps_count='".addslashes($allImps)."'".
                ", unique_imps_count='".addslashes($uniqueImps)."'".
                " where impressionid='".addslashes($ipmId)."'";

            $ret =& $this->db->query($sql);
            if (!$ret)
            {
                $this->writeHistory(WLOG_ERROR, "Show banner: Error saving impression", __FILE__, __LINE__);
                return false;
            }
        }

        setcookie(COOKIE_NAME.'imp', time(), time() + 3650*86400, '/');

        return true;
    }

    //--------------------------------------------------------------------------

    function redirect()
    {
        // for text banners only register impression

        if($this->bannerType == BANNERTYPE_LIGHTBOX) {
            echo '//banner type lightbox, see more visit marketools.cn';
            return;
        }

        if ($this->rotatorOutput != '') {
            echo $this->rotatorOutput;
            return;
        }
        if($this->bannerType == BANNERTYPE_IMAGE)
        {
            if($this->sourceURL == '' || $this->sourceURL == false) {
                $this->writeHistory(WLOG_DEBUG, "Banner viewer: banner source URL is empty", __FILE__, __LINE__);
            }

            Header('Location: '.$this->sourceURL);
            return;

            header("Content-type: image/gif");
            if(!@readfile($this->sourceURL))
            {
                $this->writeHistory(WLOG_DEBUG, "Banner viewer: readfile returned false, file '".$this->sourceURL."'", __FILE__, __LINE__);

                // banner showing failed
                // try different way of displaying the banner
                Header('Location: '.$this->sourceURL);
            }

            //Header('Location: '.$this->sourceURL);
        }

        //-----------------for tearpage---------------------//
        $destUrl = $this->destURL;
        if(strpos($destUrl, '?') === false)
            $char = '?';
        else
            $char = '&';
                $this->UserID = $row['userid'];

        $aid = empty($this->User_refid)?$this->UserID:$this->User_refid;
        $clickUrl = $destUrl.$char.PARAM_A_AID.'='.$aid.'&'.PARAM_A_BID.'='.$this->BannerID;
        $scriptsurl = $this->getSetting('Aff_scripts_url');

        if($this->bannerType == BANNERTYPE_TEARPAGE) {
            $url = $scriptsurl.'tearpage.php?surl='.$this->description.'&burl='.$this->sourceURL.'&desturl='.urlencode($clickUrl).'&scriptsurl='.urlencode($scriptsurl);
            Header('Location: '.$url);
        }
    }

    //--------------------------------------------------------------------------

    function updateCPMCommission()
    {
        // get impression records that don't have commissions yet
        $sql = "select sum(i.all_imps_count) as all_imps_count, sum(i.unique_imps_count) as unique_imps_count, b.campaignid".
               " from wd_pa_impressions i, wd_pa_banners b ".
               " where i.affiliateid='".addslashes($this->UserID)."'".
               " and accountid='".addslashes($this->AccountID)."' and commissiongiven=0".
               " and i.bannerid=b.bannerid and b.campaignid='".addslashes($this->CampaignID)."'".
               " group by b.campaignid";

        $rs =& $this->db->query($sql);
        if(!$rs || !($row = $rs->FetchRow()))
        {
            $this->writeHistory(WLOG_ERROR, "Show banner: Error update CPM Commission", __FILE__, __LINE__);
            return false;
        }

        if($row['all_imps_count'] >= 1000)
        {
            return $this->saveCPMCommission();
        }

        return false;
    }

    //--------------------------------------------------------------------------

    function saveCPMCommission()
    {
        // first save commission
        if(($commission = $this->getCommission()) === false) return false;


        $remoteAddr = $_SERVER['HTTP_REFERER'];
        $ip = $_SERVER['REMOTE_ADDR'];
        $status = AFFSTATUS_APPROVED;

        $TransID = $this->db->createUniqueId();
        $sql = "insert into wd_pa_transactions ".
            "(transid, accountid, affiliateid, campcategoryid, bannerid,".
            " dateinserted, transtype, transkind, refererurl,".
            " ip, rstatus, commission)".
            "values('".addslashes($TransID)."','".addslashes($this->AccountID).
            "','".addslashes($this->UserID)."','".addslashes($this->CampaignCategoryID).
            "','".addslashes($this->BannerID)."','".$this->db->getDateString().
            "',".TRANSTYPE_CPM.",".TRANSKIND_NORMAL.",'".addslashes($remoteAddr).
            "','".addslashes($ip)."','".addslashes($status)."','".addslashes($commission)."')";

        $ret =& $this->db->query($sql);
        if (!$ret)
        {
            $this->writeHistory(WLOG_ERROR, "Show banner: Error saving CPM commission", __FILE__, __LINE__);
            return false;
        }

        $this->writeHistory(WLOG_DEBUG, "Banner Viewer: Created CPM commission with ID '$TransID'", __FILE__, __LINE__);

        //------------------------------------------------
        // now change impression status to commissiongiven=1
        $sql = "select bannerid from wd_pa_banners where campaignid='".addslashes($this->CampaignID)."'";
        $rs =& $this->db->query($sql);
        if(!$rs)
        {
            $this->writeHistory(WLOG_ERROR, "Show banner: Error getting banner ID by campaign", __FILE__, __LINE__);
            return false;
        }

        $bannerIDs = array();
        while($row = $rs->FetchRow())
        {
            $bannerIDs[] = $row['bannerid'];
        }

        $chunkedBannerIDs = sb_array_chunk($bannerIDs, WD_MAX_PROCESSED_IDS);

        foreach($chunkedBannerIDs as $bannerIDsArray)
        {
            $bannerIDSql = "('".implode("','", $bannerIDsArray)."')";

            $sql = 'update wd_pa_impressions set commissiongiven=1'.
                   ' where bannerid in '.$bannerIDSql.
                   "   and accountid='".addslashes($this->AccountID)."'".
                   "   and affiliateid='".addslashes($this->UserID)."'";

            $rs =& $this->db->query($sql);
            if (!$rs)
            {
                $this->writeHistory(WLOG_ERROR, "Show banner: Error changing impression status to commissiongiven=1", __FILE__, __LINE__);
                return false;
            }
        }

        return true;
    }

    //--------------------------------------------------------------------------

    function getCommission()
    {
        if(!$this->checkUserInCampaign())
            return false;

        return ($this->CPMCommission != '' ? $this->CPMCommission : 0);
    }

    //--------------------------------------------------------------------------

    function checkInDomain()
    {
        $sql = 'select url from wd_g_domains '.
               'where userid=\''.addslashes($this->UserID).'\''.
               '  and accountid=\''.addslashes($this->AccountID).'\''.
               '  and rtype=\''.addslashes(DOMAIN_USERS).'\''.
               '  and rstatus=\''.addslashes(AFFSTATUS_APPROVED).'\''.
               '  and url like \'%'.$GLOBALS['HTTP_REFERER'].'%\'';

        $rs =& $this->db->query($sql);
        if(!$rs || !($row = $rs->FetchRow()))
            return false;

        return true;
    }

    //--------------------------------------------------------------------------

    function checkUserInCampaign()
    {
        $sql = 'select cc.* from wd_pa_affiliatescampaigns ac, wd_pa_campaigncategories cc '.
               "where cc.campaignid='".addslashes($this->CampaignID)."'".
               '  and cc.campcategoryid=ac.campcategoryid'.
               "  and ac.rstatus='".addslashes(AFFSTATUS_APPROVED)."'".
               "  and ac.affiliateid='".addslashes($this->UserID)."'";
        $rs =& $this->db->query($sql);
        if(!$rs) {
            $this->writeHistory(WLOG_ERROR, "Show banner: Error getting campaign properties", __FILE__, __LINE__);
            return false;
        }

        if(!($row = $rs->FetchRow()))
        {
            // get basic commission category for this campaign
            $sql = 'select * from wd_pa_campaigncategories '.
                   "where deleted=0 and campaignid='".($this->CampaignID)."'".
                   " and name='".addslashes(UNASSIGNED_USERS)."'";
            $rs =& $this->db->query($sql);
            if (!($row = $rs->FetchRow())) {
                $this->writeHistory(WLOG_ERROR, "Show banner: Error getting campaign basic properties", __FILE__, __LINE__);
                return false;
            }
        }

        $this->CampaignCategoryID = $row['campcategoryid'];
        $this->CPMCommission = $row['cpmcommission'];
        $this->ClickCommission = $row['clickcommission'];
        $this->SaleCommission = $row['salecommission'];

        if($value = $this->getSetting('Aff_maxcommissionlevels')) {
            $this->maxCommissionLevels = $value;
        } else {
            $this->maxCommissionLevels = 1;
        }

        $this->STClickCommission = array();
        $this->STSaleCommission = array();
        $this->STRecurringCommission = array();

        for($i=2; $i<=$this->maxCommissionLevels; $i++)
        {
            $this->STClickCommission[$i] = $row['st'.$i.'clickcommission'];
            $this->STSaleCommission[$i] = $row['st'.$i.'salecommission'];
            $this->STRecurringCommission[$i] = $row['st'.$i.'recurringcommission'];
        }

        $this->PerSaleCommType = $row['salecommtype'];
        $this->STPerSaleCommType = $row['stsalecommtype'];

        $this->RecurringCommission = $row['recurringcommission'];
        $this->RecurringCommType = $row['recurringcommtype'];
        $this->RecurringCommDate = $row['recurringcommdate'];
        $this->RecurringDateType = $row['recurringdatetype'];
        $this->STRecurringCommType = $row['strecurringcommtype'];

        return true;
    }

   //--------------------------------------------------------------------------

    function writeHistory($type, $text, $file, $line)
    {
        if(!((int)$type &(int)$this->logLevel)) {
           return false;
        }

        if($type == WLOG_DEBUG && $this->debugImps != 1) {
            return false;
        }

        $historyid = $this->db->createUniqueId();
        $sql = "insert into wd_g_history set ".
                "historyid = '".addslashes($historyid)."',".
                "rtype = '".addslashes($type)."',".
                "accountid = '".$this->AccountID."',".
                "value = '".addslashes($text)."',".
                "dateinserted = '".$this->db->getDateString()."',".
                "hfile = '".addslashes($file)."',".
                "line = '".addslashes($line)."',".
                "ip = '".addslashes($_SERVER['REMOTE_ADDR'])."'";
        $ret =& $this->db->query($sql);
    }

   //--------------------------------------------------------------------------

    function getAccountForDomain() {
        $sql =  "select accountid from wd_g_domains".
                " where url = '".$_SERVER['SERVER_NAME']."'".
                " and rtype=1";
        $rs =& $this->db->query($sql);

        if ($row = $rs->FetchRow()) {
            return $row['accountid'];
        }
        return false;
    }

    //--------------------------------------------------------------------------

    function dot2LongIP($IPaddr)
	{
    	if ($IPaddr == "") {
        	return 0;
    	} else {
        	$ips = split ("\.", "$IPaddr");
        	return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
    	}
	}

	//--------------------------------------------------------------------------

    function getCountryForIp($ip)
    {
    	$sql = 'select countrySHORT, countryLONG from wd_g_ipcountry where '.
			   $this->dot2LongIP($ip).' between ipFROM AND ipTO';
		$rs =& $this->db->query($sql);
        if(!$rs) {
            $this->writeHistory(WLOG_ERROR, "DB Error", __FILE__, __LINE__);
            return array();
        }
        if(!($row = $rs->FetchRow())) {
        	return array('countrycode' => '__',
        			 	 'countryname' => 'Unknown');
        }

        return array('countrycode' => $row['countrySHORT'],
        			 'countryname' => $row['countryLONG']);
    }

    //--------------------------------------------------------------------------

	function isAllowedCountry($country)
	{
		if($this->getSetting('Glob_acct_geo_allow_ban_trafic') == 1) {
			if(strpos($this->getSetting('Glob_acct_geo_selectedcountries'), $country['countrycode']) === false)
				return false;
		} else {
			if(strpos($this->getSetting('Glob_acct_geo_selectedcountries'), $country['countrycode']) !== false)
				return false;
		}

		return true;
	}

	//------------------------------------------------------------------------

    function parseRotatorBannerDescription($desc)
    {
        if($desc == '') {
            return array();
        }

        $descArray = explode(',', $desc);
        $parsed = array();

        foreach($descArray as $descItem) {
            $banner = explode(';', $descItem);
            $parsed[$banner[0]] = array('all_imps'  => $banner[1],
                                        'uniq_imps' => $banner[2],
                                        'clicks'    => $banner[3],
                                        'rank'      => $banner[4]);
        }
        return $parsed;
    }

    //------------------------------------------------------------------------

    function encodeRotatorBannerDescription($banners)
    {
        if (count($banners) == 0) {
            return '';
        }

        $desc = '';
        foreach ($banners as $bannerID => $bannerData) {
            $desc .= ($desc == '' ? '' : ',').$bannerID.';'.implode(';', $bannerData);
        }

        return $desc;
    }

	//--------------------------------------------------------------------------

	function processRotatorBanner() {
	    $banners = $this->parseRotatorBannerDescription($this->description);
	    if(count($banners) == 0) {
	        return;
	    }
	    $id = $this->getBannerToShow($banners);

        if(($bannerData = $this->getBannerData($id)) === false) {
            return false;
        }

        $specialDestUrl = $_REQUEST[PARAM_DESTURL];
        $params = array();
        $params['Affiliate_id'] = urlencode($this->UserID);
        $params['Affiliate_refid'] = urlencode($this->User_refid);
        $params['Affiliate_name'] = urlencode($this->User_name.' '.$this->User_surname);
        $params['Affiliate_username'] = urlencode($this->User_username);

        $clickUrlOnly = $this->getClickUrl($bannerData['destinationurl'], $params);
        $code = $this->getBannerCode($clickUrlOnly, $bannerData['bannertype'], $bannerData['bannerid'], $bannerData['sourceurl'], $bannerData['description'], $params, $specialDestUrl);
        if ($bannerData['bannertype'] == BANNERTYPE_POPUNDER || $bannerData['bannertype'] == BANNERTYPE_POPUP) {
            $this->rotatorOutput = $code;
        } else {
            $code = str_replace("\n", " ", $code);
            $code = str_replace("\r", " ", $code);
	        $this->rotatorOutput = "document.write('".str_replace("'", "\\'", $code)."');";
        }

	    $banners = $this->updateStatistics($banners, $id);
	    if ($this->sourceURL != SELFOPTIMIZATION_NONE) {
	       $banners = $this->optimizeRotatorBanner($banners);
        }

        $this->description = $this->encodeRotatorBannerDescription($banners);
        $this->updateDescription();

        $this->rotatorID = $this->BannerID;
        $this->checkBannerExists($id);
	}

	//--------------------------------------------------------------------------

    function getClickUrl($destinationUrl, $params)
    {
        if($this->getSetting('Aff_link_style') == LINK_STYLE_NEW)
        {
            $destUrl = $destinationUrl;
            if(strpos($destUrl, '?') === false)
                $char = '?';
            else
                $char = '&';

            $destUrl = str_replace('$Affiliate_id', $params['Affiliate_id'], $destUrl);
            $destUrl = str_replace('$Affiliate_refid', $params['Affiliate_refid'], $destUrl);
            $destUrl = str_replace('$Affiliate_name', $params['Affiliate_name'], $destUrl);
            $destUrl = str_replace('$Affiliate_username', $params['Affiliate_username'], $destUrl);

            if (GLOBAL_DB_ENABLED == 1) {
                $clickUrlOnly = $destUrl.$char."lid=".$_SESSION[LID_PREFFIX.'lite_accountid']."&".PARAM_A_AID."=".$params['Affiliate_refid'];
            } else {
                $clickUrlOnly = $destUrl.$char.PARAM_A_AID."=".$params['Affiliate_refid'];
            }
        }
        else
        {
            if (GLOBAL_DB_ENABLED == 1) {
                $clickUrlOnly = $this->getSetting('Aff_scripts_url')."t.php?lid=".$_SESSION[LID_PREFFIX.'lite_accountid']."&".PARAM_A_AID."=".$params['Affiliate_refid'];
            } else {
                $clickUrlOnly = $this->getSetting('Aff_scripts_url')."t.php?".PARAM_A_AID."=".$params['Affiliate_refid'];
            }
        }

        return $clickUrlOnly;
    }

	//--------------------------------------------------------------------------

	function getBannerToShow($banners) {
	    if ($GLOBALS['selected_subbanner_id'] != '') {
	        return $GLOBALS['selected_subbanner_id'];
	    }
	    $sum = 0;
        list($usec, $sec) = explode(' ', microtime());
        srand((float) $sec + ((float) $usec * 100000));
	    $rnd = rand(0, MAX_RANK);
	    $id = '';
	    foreach ($banners as $bannerID => $bannerData) {
	        $sum += $bannerData['rank'];
	        if ($rnd <= $sum) {
	            return $bannerID;
	        }
	        $id = $bannerID;
	    }
	    return $id;
	}

	//--------------------------------------------------------------------------

	function updateStatistics($banners, $id) {
	    if ($this->AllowedCountry === false) {
	        return $banners;
	    }
	    $banners[$id]['all_imps']++;
	    if($this->uniqueImp) {
	        $banners[$id]['uniq_imps']++;
	    }
	    return $banners;
	}

	//--------------------------------------------------------------------------

	function optimizeRotatorBanner($banners) {
	    // prepare optimization data
	    $data = array();
	    $datasum = 0;
	    switch ($this->sourceURL) {
	        case SELFOPTIMIZATION_CLICKS:
	            foreach ($banners as $bannerID => $bannerData) {
	               $datasum += $data[$bannerID] = $bannerData['clicks'];
	            }
	            break;
	        case SELFOPTIMIZATION_CTR:
	            foreach ($banners as $bannerID => $bannerData) {
	                $datasum += $data[$bannerID] = ($bannerData['all_imps'] == 0) ? 0 : $bannerData['clicks']/$bannerData['all_imps']*100;
	            }
	            break;
	        default:
	           return $banners;
	    }
	    // optimize ranks
	    if ($datasum == 0)
	       return $banners;
	    $multiply_factor = MAX_RANK / $datasum;
	    foreach ($data as $bannerID => $newValue) {
	        $banners[$bannerID]['rank'] = round($banners[$bannerID]['rank'] + (($newValue*$multiply_factor) - $banners[$bannerID]['rank']) / SELFOPTIMIZATION_SPEED, RANK_PRECISION);
	    }
	    return $banners;
	}

	//--------------------------------------------------------------------------

	function getBannerCode($clickUrlOnly, $bannerType, $bannerID, $sourceUrl, $description, $params, $specialDestUrl = '') {
	    if($bannerType == BANNERTYPE_TEXT)
        {
            $title = $sourceUrl;
            $title = str_replace('$Affiliate_id', $params['Affiliate_id'], $title);
            $title = str_replace('$Affiliate_refid', $params['Affiliate_refid'], $title);
            $title = str_replace('$Affiliate_name', $params['Affiliate_name'], $title);
            $title = str_replace('$Affiliate_username', $params['Affiliate_username'], $title);

            $description = str_replace('$Affiliate_id', $params['Affiliate_id'], $description);
            $description = str_replace('$Affiliate_refid', $params['Affiliate_refid'], $description);
            $description = str_replace('$Affiliate_name', $params['Affiliate_name'], $description);
            $description = str_replace('$Affiliate_username', $params['Affiliate_username'], $description);

            if(isset($this->getSetting['Aff_bannerformat_textformat']) && trim($this->getSetting['Aff_bannerformat_textformat']) != '')
            {
                $code = $this->getSetting['Aff_bannerformat_textformat'];
                $code = str_replace('$TITLE', $title, $code);
                $code = str_replace('$DESCRIPTION', $description, $code);
                $code = str_replace('$DESTINATION', "'".$clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&desturl='.urlencode($specialDestUrl) : '')."'", $code);
                $code = str_replace('$IMPRESSION_TRACK', "", $code);

                $banner['titleDescription'] = $code;

            }
            else
            {
                $banner['titleDescription'] = "<b>".$title."</b><br>".$description;

                $code = "<A HREF=\"".$clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&'.PARAM_DESTURL.'='.urlencode($specialDestUrl) : '')."\">";
                $code .= "<center><b>".$title."</b><br>".$description."</center>";
                $code .= "</A>";
            }

            return $code;
        }
        else if($bannerType == BANNERTYPE_HTML)
        {
            $description = str_replace('$Affiliate_id', $params['Affiliate_id'], $description);
            $description = str_replace('$Affiliate_name', $params['Affiliate_name'], $description);
            $description = str_replace('$Affiliate_username', $params['Affiliate_username'], $description);

            $code = str_replace('$CLICKURL', $clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&'.PARAM_DESTURL.'='.$specialDestUrl : ''), $description);

            return $code;
        }
        else if($bannerType == BANNERTYPE_IMAGE)
        {
/*            $banner['titleDescription'] = "<img src='".$sourceUrl."' border=0 alt='".$description."'><br>";

            $code = "<A HREF=\"".$clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&'.PARAM_DESTURL.'='.urlencode($specialDestUrl) : '')."\">";
            $code .= "<img src=\"".$this->getSetting('Aff_scripts_url')."sb.php?".PARAM_A_AID."=".$params['Affiliate_refid']."&".PARAM_A_BID."=".$this->BannerID."\" border=\"0\" alt=\"".$description."\">";
            //$code .= "<img src='".$sourceUrl."' border=0 alt='".$description."'><br>";
            $code .= "</A>";

            return $code;*/

            if($this->getSetting('Aff_bannerformat_graphicformat') && trim($this->getSetting('Aff_bannerformat_graphicformat')) != '') {
                $code = $this->getSetting('Aff_bannerformat_graphicformat');
            } else {
                $code = DEFAULT_GRAPHICS_BANNER_FORMAT;
            }

            $code = str_replace('$ALT', $description, $code);
            $code = str_replace('$DESTINATION', "'".$clickUrlOnly."&amp;".PARAM_A_BID."=".$bannerID.($specialDestUrl != '' ? '&amp;'.PARAM_DESTURL.'='.urlencode($specialDestUrl) : '')."'", $code);

            $image_src = $this->getSetting('Aff_scripts_url')."sb.php?".PARAM_A_AID."=".$params['Affiliate_id']."&amp;".PARAM_A_BID."=".$bannerID;

            $banner['titleDescription'] = str_replace('$IMAGE_SRC', "'".$sourceUrl."'", $code);

            $code = str_replace('$IMAGE_SRC', "'".$image_src."'", $code);

            return $code;
        }
        else if($bannerType == BANNERTYPE_POPUP || $bannerType == BANNERTYPE_POPUNDER)
        {
            $viewMerchBannerManager = QUnit_Global::newObj('Affiliate_Merchants_Views_BannerManager');
            $banner_details = $viewMerchBannerManager->parseBannerDescription($description, false);

            $banner_content = '';
            if($banner_details['display'] == URL_EXIST)
            {
                $original_banner = $this->getBannerInfo(array('bannerid' => array($sourceUrl)));

                $bannerData = $original_banner[$sourceUrl];

                if($bannerData['bannertype'] == BANNERTYPE_TEXT)
                {
                    $title = $bannerData['sourceurl'];
                    $title = str_replace('$Affiliate_id', $params['Affiliate_id'], $title);
                    $title = str_replace('$Affiliate_refid', $params['Affiliate_refid'], $title);
                    $title = str_replace('$Affiliate_name', $params['Affiliate_name'], $title);
                    $title = str_replace('$Affiliate_username', $params['Affiliate_username'], $title);

                    $bannerData['description'] = str_replace('$Affiliate_id', $params['Affiliate_id'], $bannerData['description']);
                    $bannerData['description'] = str_replace('$Affiliate_refid', $params['Affiliate_refid'], $bannerData['description']);
                    $bannerData['description'] = str_replace('$Affiliate_name', $params['Affiliate_name'], $bannerData['description']);
                    $bannerData['description'] = str_replace('$Affiliate_username', $params['Affiliate_username'], $bannerData['description']);

                    if($this->getSetting('Aff_bannerformat_textformat') != '') {
                        $banner_content = $this->getSetting('Aff_bannerformat_textformat');
                        $banner_content = str_replace('$TITLE', $title, $banner_content);
                        $banner_content = str_replace('$DESCRIPTION', $bannerData['description'], $banner_content);
                        $banner_content = str_replace('$DESTINATION', $clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&'.PARAM_DESTURL.'='.urlencode($specialDestUrl) : ''), $banner_content);
                        $banner_content = str_replace('$IMPRESSION_TRACK', "", $banner_content);
                    }
                    else
                    {
                        $banner_content = "<A HREF=".$clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&'.PARAM_DESTURL.'='.urlencode($specialDestUrl) : '').">";
                        $banner_content .= "<center><b>".$title."</b><br>".$bannerData['description']."</center>";
                        $banner_content .= "</A>";
                    }
                }
                else if($bannerData['bannertype'] == BANNERTYPE_HTML)
                {
                    $bannerData['description'] = str_replace('$Affiliate_id', $params['Affiliate_id'], $bannerData['description']);
                    $bannerData['description'] = str_replace('$Affiliate_name', $params['Affiliate_name'], $bannerData['description']);
                    $bannerData['description'] = str_replace('$Affiliate_username', $params['Affiliate_username'], $bannerData['description']);

                    $banner_content = str_replace('$CLICKURL', $clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&'.PARAM_DESTURL.'='.$specialDestUrl : ''), $bannerData['description']);
                }
                else if($bannerData['bannertype'] == BANNERTYPE_IMAGE)
                {
                    $banner_content = "<A HREF=".$clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&'.PARAM_DESTURL.'='.urlencode($specialDestUrl) : '').">";
                    $banner_content .= "<br><img src=".$bannerData['sourceurl']." border=0 alt=".$bannerData['description']."><br>";
                    $banner_content .= "</A>";
                }
            }
            else
            {
                $banner_content = $sourceUrl;
                $clickurl_link = '&clickurl='.urlencode($clickUrlOnly."&a_sbid=".$bannerID."&".PARAM_A_BID."=".$this->BannerID.($specialDestUrl != '' ? '&'.PARAM_DESTURL.'='.urlencode($specialDestUrl) : '')).'&special=1';
            }

            $banner['titleDescription'] = '<input class=formbutton type="button" VALUE="'.L_G_TEST.' '.
                            ($bannerType == BANNERTYPE_POPUNDER ? L_G_POPUNDER : L_G_POPUP).
                            '" onClick="showPopupPopunder(\''.urlencode($banner_content).'\',\''.$bannerType.'\',\''.$banner_details['rwidth'].'\',\''.$banner_details['rheight'].'\')">';

            if (GLOBAL_DB_ENABLED == 1) {
                $impression_content = $this->getSetting('Aff_scripts_url')."sb.php?lid=".$_SESSION[LID_PREFFIX.'lite_accountid']."&".PARAM_A_AID."=".$params['Affiliate_refid']."&".PARAM_A_BID."=".$this->BannerID;
            } else {
                $impression_content = $this->getSetting('Aff_scripts_url')."sb.php?".PARAM_A_AID."=".$params['Affiliate_refid']."&".PARAM_A_BID."=".$this->BannerID;
            }

            $code = 'var TheNewWindow = window.open("'.$this->getSetting('Aff_scripts_url').'showPop.php?banner_content='.urlencode($banner_content).'&impression_content='.urlencode($impression_content).$clickurl_link.'",\'ThePop\',';
            $code .= '\'top=0,left=0,width='.$banner_details['rwidth'].',height='.$banner_details['rheight'].',toolbar='.$banner_details['window_toolbar'].',location='.$banner_details['window_location'];
            $code .= ',directories='.$banner_details['window_directories'].',status='.$banner_details['window_status'].',menubar='.$banner_details['window_menubar'].',scrollbars='.$banner_details['window_scrollbars'].',resizable='.$banner_details['window_resizable'].'\');';
            if($bannerType == BANNERTYPE_POPUNDER) $code .= ' TheNewWindow.blur();';
            else $code .= ' TheNewWindow.focus();';

            return $code;
        }

        return false;
	}

	//--------------------------------------------------------------------------

    function getBannerInfo($params)
    {
        $IDs = $params['bannerid'];
        $sql = 'select * from wd_pa_banners '.
               'where deleted='._q('0');
        if(is_array($IDs) && count($IDs) > 0)
        {
            $sql .= " and bannerid in ('".implode("','", $IDs)."')";
        }
        $sql .= ' order by destinationurl';
        $rs =& $this->db->query($sql);
        if(!$rs) {
            QUnit_Messager::setErrorMessage(L_G_DBERROR);
            return false;
        }

        $bannerData = array();

        while($row = $rs->FetchRow())
        {
            $bannerData[$row['bannerid']]['bannerid'] = $row['bannerid'];
            $bannerData[$row['bannerid']]['name'] = $row['name'];
            $bannerData[$row['bannerid']]['description'] = $row['description'];
            $bannerData[$row['bannerid']]['destinationurl'] = $row['destinationurl'];
            $bannerData[$row['bannerid']]['sourceurl'] = $row['sourceurl'];
            $bannerData[$row['bannerid']]['bannertype'] = $row['bannertype'];
            $bannerData[$row['bannerid']]['campaignid'] = $row['campaignid'];
            $bannerData[$row['bannerid']]['hidden'] = $row['hidden'];
            $bannerData[$row['bannerid']]['size'] = $row['size'];
        }

        return $bannerData;
    }

}

function sb_array_chunk($input, $size, $preserve_keys = false)
{
    if(function_exists('array_chunk')) {
        return array_chunk($input, $size, $preserve_keys);
    } else {
       @reset( $input );

       $i = $j = 0;

       while( @list( $key, $value ) = @each( $input ) ) {
           if( !( isset( $chunks[$i] ) ) ) {
               $chunks[$i] = array();
           }

           if( count( $chunks[$i] ) < $size ) {
               if( $preserve_keys ) {
                   $chunks[$i][$key] = $value;
                   $j++;
               } else {
                   $chunks[$i][] = $value;
               }
           } else {
               $i++;

               if( $preserve_keys ) {
                   $chunks[$i][$key] = $value;
                   $j++;
               } else {
                   $j = 0;
                   $chunks[$i][$j] = $value;
               }
           }
       }

       return $chunks;
    }
}
?>
