function phpAds_fetchBannerZone($remaining, $clientid, $context = 0, $source = '', $richmedia = true)
{
    global $phpAds_config;
    global $phpAds_followedChain;
    // Get first part, store second part
    $what = strtok($remaining, '|');
    $remaining = strtok('');
    $zoneid = substr($what, 5);
    // Check if zone was already evaluated in the chain
    if (isset($phpAds_followedChain) && in_array($zoneid, $phpAds_followedChain)) {
        return $remaining;
    } else {
        $phpAds_followedChain[] = $zoneid;
    }
    // Get cache
    if (!defined('LIBVIEWCACHE_INCLUDED')) {
        @(include phpAds_path . '/libraries/deliverycache/cache-' . $phpAds_config['delivery_caching'] . '.inc.php');
    }
    $cache = @phpAds_cacheFetch('what=zone:' . $zoneid);
    if (!$cache) {
        $zoneres = phpAds_dbQuery("SELECT * FROM " . $phpAds_config['tbl_zones'] . " WHERE zoneid='" . $zoneid . "'");
        if ($zone = phpAds_dbFetchArray($zoneres)) {
            // No linked banners
            if ($remaining == '') {
                $remaining = $zone['chain'];
            }
            if ($zone['what'] == '') {
                return $remaining;
            }
            if (!defined('LIBVIEWQUERY_INCLUDED')) {
                include phpAds_path . '/libraries/lib-view-query.inc.php';
            }
            $precondition = '';
            // Size preconditions
            if ($zone['width'] > -1) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".width = " . $zone['width'] . " ";
            }
            if ($zone['height'] > -1) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".height = " . $zone['height'] . " ";
            }
            // Text Ads preconditions
            // Matching against the value instead of the constant phpAds_ZoneText (3).
            // Didn't want to include the whole lib-zones just for a constant
            if ($zone['delivery'] == 3) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".storagetype = 'txt' ";
            } else {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".storagetype <> 'txt' ";
            }
            $select = phpAds_buildQuery($zone['what'], false, $precondition);
            $res = phpAds_dbQuery($select);
            // Build array for further processing...
            $rows = array();
            $prioritysum = 0;
            while ($tmprow = phpAds_dbFetchArray($res)) {
                // weight of 0 disables the banner
                if ($tmprow['priority']) {
                    $prioritysum += $tmprow['priority'];
                    $rows[] = $tmprow;
                }
            }
            $cache = array($zone['zoneid'], $rows, $zone['what'], $prioritysum, $zone['chain'], $zone['prepend'], $zone['append']);
            phpAds_cacheStore('what=zone:' . $zone['zoneid'], $cache);
            // Unpack cache
            list($zoneid, $rows, $what, $prioritysum, $chain, $prepend, $append) = $cache;
        } else {
            // Zone not found
            return $remaining;
        }
    } else {
        // Unpack cache
        list($zoneid, $rows, $what, $prioritysum, $chain, $prepend, $append) = $cache;
        if ($remaining == '') {
            $remaining = $chain;
        }
        if (count($rows) == 0) {
            return $remaining;
        }
    }
    // Build preconditions
    $excludeBannerID = array();
    $excludeCampaignID = array();
    $includeBannerID = array();
    $includeCampaignID = array();
    if (is_array($context)) {
        for ($i = 0; $i < count($context); $i++) {
            list($key, $value) = each($context[$i]);
            $type = 'bannerid';
            $valueArray = explode(':', $value);
            if (count($valueArray) == 1) {
                list($value) = $valueArray;
            } else {
                list($type, $value) = $valueArray;
            }
            if ($type == 'bannerid') {
                switch ($key) {
                    case '!=':
                        $excludeBannerID[$value] = true;
                        break;
                    case '==':
                        $includeBannerID[$value] = true;
                        break;
                }
            }
            if ($type == 'campaignid') {
                switch ($key) {
                    case '!=':
                        $excludeCampaignID[$value] = true;
                        break;
                    case '==':
                        $includeCampaignID[$value] = true;
                        break;
                }
            }
        }
    }
    // Get number of rows
    $maxindex = sizeof($rows);
    // Create campaign mapping
    $campaign_mapping = array();
    for ($i = 0; $i < $maxindex; $i++) {
        $campaign_mapping[$rows[$i]['clientid']][] = $i;
    }
    // Use a multiplier to make sure we don't have rounding problems afterwards
    $multiplier = 1000;
    // Make sure that prioritysum * multiplier works with mt_rand
    while ($prioritysum * $multiplier > mt_getrandmax()) {
        $multiplier /= 10;
    }
    // Track remaining rows
    $remaining_rows = sizeof($rows);
    // Start main loop
    while ($prioritysum >= 1 && $remaining_rows > 0) {
        $low = 0;
        $high = 0;
        $ranweight = $prioritysum > 1 ? mt_rand(0, $prioritysum * $multiplier - 1) : 0;
        for ($i = 0; $i < $maxindex; $i++) {
            if (is_array($rows[$i])) {
                $low = $high;
                $high += round($rows[$i]['priority'] * $multiplier);
                if ($high > $ranweight && $low <= $ranweight) {
                    $postconditionSuccess = true;
                    // Excludelist banners
                    if (isset($excludeBannerID[$rows[$i]['bannerid']])) {
                        $postconditionSuccess = false;
                    }
                    // Excludelist campaigns
                    if ($postconditionSuccess == true && isset($excludeCampaignID[$rows[$i]['clientid']])) {
                        $postconditionSuccess = false;
                    }
                    // Includelist banners
                    if ($postconditionSuccess == true && sizeof($includeBannerID) && !isset($includeBannerID[$rows[$i]['bannerid']])) {
                        $postconditionSuccess = false;
                    }
                    // Includelist campaigns
                    if ($postconditionSuccess == true && sizeof($includeCampaignID) && !isset($includeCampaignID[$rows[$i]['clientid']])) {
                        $postconditionSuccess = false;
                    }
                    // HTML or Flash banners
                    if ($postconditionSuccess == true && $richmedia == false && ($rows[$i]['contenttype'] != 'jpeg' && $rows[$i]['contenttype'] != 'gif' && $rows[$i]['contenttype'] != 'png')) {
                        $postconditionSuccess = false;
                    }
                    // Blocked
                    if ($postconditionSuccess == true && $rows[$i]['block'] > 0 && isset($_COOKIE['phpAds_blockAd'][$rows[$i]['bannerid']]) && $_COOKIE['phpAds_blockAd'][$rows[$i]['bannerid']] > time()) {
                        $postconditionSuccess = false;
                    }
                    // Capped
                    if ($postconditionSuccess == true && $rows[$i]['capping'] > 0 && isset($_COOKIE['phpAds_capAd'][$rows[$i]['bannerid']]) && $_COOKIE['phpAds_capAd'][$rows[$i]['bannerid']] >= $rows[$i]['capping']) {
                        $postconditionSuccess = false;
                    }
                    // ACLs
                    if ($postconditionSuccess == true && $phpAds_config['acl'] && !phpAds_aclCheck($rows[$i], $source)) {
                        $postconditionSuccess = false;
                    }
                    if ($postconditionSuccess == false) {
                        // Failed one of the postconditions
                        // Delete this row
                        $bannerpriority = $rows[$i]['priority'];
                        $campaignid = $rows[$i]['clientid'];
                        $rows[$i] = '';
                        $remaining_rows--;
                        // Assign lost priority to the other banners in the same campaign
                        // Start getting the sum of all priorities
                        $campaingprioritysum = 0;
                        foreach ($campaign_mapping[$campaignid] as $ii) {
                            if (is_array($rows[$ii]) && $rows[$ii]['priority']) {
                                $campaingprioritysum += $rows[$ii]['priority'];
                            }
                        }
                        if ($campaingprioritysum) {
                            // Distribute the priority in a weighted manner
                            $total_increment = 0;
                            foreach ($campaign_mapping[$campaignid] as $ii) {
                                if (is_array($rows[$ii]) && $rows[$ii]['priority']) {
                                    $increment = $bannerpriority * $rows[$ii]['priority'] / $campaingprioritysum;
                                    $rows[$ii]['priority'] += $increment;
                                    $total_increment += $increment;
                                }
                            }
                            // Adjust priority sum, there may have been roundings
                            $prioritysum += $total_increment - $bannerpriority;
                        } else {
                            // No other banners from the same campaign, discard priority
                            $prioritysum -= $bannerpriority;
                        }
                        // Break out of the for loop to try again
                        break;
                    }
                    // Found banner!
                    $rows[$i]['zoneid'] = $zoneid;
                    $rows[$i]['append'] = $append;
                    $rows[$i]['prepend'] = $prepend;
                    return $rows[$i];
                }
            }
        }
    }
    return $remaining;
}
function phpAds_fetchBannerDirect($remaining, $clientid = 0, $context = 0, $source = '', $richmedia = true)
{
    global $phpAds_config;
    // Get first part, store second part
    $what = strtok($remaining, '|');
    $remaining = strtok('');
    // Expand paths to regular statements
    if (strpos($what, '/') > 0) {
        if (strpos($what, '@') > 0) {
            list($what, $append) = explode('@', $what);
        } else {
            $append = '';
        }
        $seperate = explode('/', $what);
        $expanded = '';
        $collected = array();
        while (list(, $v) = each($seperate)) {
            $expanded .= ($expanded != '' ? ',+' : '') . $v;
            $collected[] = $expanded . ($append != '' ? ',+' . $append : '');
        }
        $what = strtok(implode('|', array_reverse($collected)), '|');
        $remaining = strtok('') . ($remaining != '' ? '|' . $remaining : '');
    }
    $cacheid = 'what=' . $what . '&clientid=' . $clientid . '&remaining=' . ($remaining == '' ? 'true' : 'false');
    // Get cache
    if (!defined('LIBVIEWCACHE_INCLUDED')) {
        @(include phpAds_path . '/libraries/deliverycache/cache-' . $phpAds_config['delivery_caching'] . '.inc.php');
    }
    $cache = @phpAds_cacheFetch($cacheid);
    if (!$cache) {
        if (!defined('LIBVIEWQUERY_INCLUDED')) {
            include phpAds_path . '/libraries/lib-view-query.inc.php';
        }
        if ($clientid > 0) {
            $precondition = " AND " . $phpAds_config['tbl_banners'] . ".clientid = '" . $clientid . "' ";
        } else {
            $precondition = '';
        }
        $select = phpAds_buildQuery($what, $remaining == '', $precondition);
        $res = phpAds_dbQuery($select);
        // Build array for further processing...
        $rows = array();
        $prioritysum = 0;
        while ($tmprow = phpAds_dbFetchArray($res)) {
            // weight of 0 disables the banner
            if ($tmprow['priority']) {
                $prioritysum += $tmprow['priority'];
                $rows[] = $tmprow;
            }
        }
        $cache = array($rows, $what, $prioritysum);
        phpAds_cacheStore($cacheid, $cache);
        // Unpack cache
        list($rows, $what, $prioritysum) = $cache;
    } else {
        // Unpack cache
        list($rows, $what, $prioritysum) = $cache;
    }
    // Build preconditions
    $excludeBannerID = array();
    $excludeCampaignID = array();
    $includeBannerID = array();
    $includeCampaignID = array();
    if (is_array($context)) {
        for ($i = 0; $i < count($context); $i++) {
            list($key, $value) = each($context[$i]);
            $type = 'bannerid';
            $valueArray = explode(':', $value);
            if (count($valueArray) == 1) {
                list($value) = $valueArray;
            } else {
                list($type, $value) = $valueArray;
            }
            if ($type == 'bannerid') {
                switch ($key) {
                    case '!=':
                        $excludeBannerID[$value] = true;
                        break;
                    case '==':
                        $includeBannerID[$value] = true;
                        break;
                }
            }
            if ($type == 'campaignid') {
                switch ($key) {
                    case '!=':
                        $excludeCampaignID[$value] = true;
                        break;
                    case '==':
                        $includeCampaignID[$value] = true;
                        break;
                }
            }
        }
    }
    // Get number of rows
    $maxindex = sizeof($rows);
    // Create campaign mapping
    $campaign_mapping = array();
    for ($i = 0; $i < $maxindex; $i++) {
        $campaign_mapping[$rows[$i]['clientid']][] = $i;
    }
    // Use a multiplier to make sure we don't have rounding problems afterwards
    $multiplier = 1000;
    // Make sure that prioritysum * multiplier works with mt_rand
    while ($prioritysum * $multiplier > mt_getrandmax()) {
        $multiplier /= 10;
    }
    // Track remaining rows
    $remaining_rows = sizeof($rows);
    // Start main loop
    while ($prioritysum >= 1 && $remaining_rows > 0) {
        $low = 0;
        $high = 0;
        $ranweight = $prioritysum > 1 ? mt_rand(0, $prioritysum * $multiplier - 1) : 0;
        for ($i = 0; $i < $maxindex; $i++) {
            if (is_array($rows[$i])) {
                $low = $high;
                $high += round($rows[$i]['priority'] * $multiplier);
                if ($high > $ranweight && $low <= $ranweight) {
                    $postconditionSuccess = true;
                    // Excludelist banners
                    if (isset($excludeBannerID[$rows[$i]['bannerid']])) {
                        $postconditionSuccess = false;
                    }
                    // Excludelist campaigns
                    if ($postconditionSuccess == true && isset($excludeCampaignID[$rows[$i]['clientid']])) {
                        $postconditionSuccess = false;
                    }
                    // Includelist banners
                    if ($postconditionSuccess == true && sizeof($includeBannerID) && !isset($includeBannerID[$rows[$i]['bannerid']])) {
                        $postconditionSuccess = false;
                    }
                    // Includelist campaigns
                    if ($postconditionSuccess == true && sizeof($includeCampaignID) && !isset($includeCampaignID[$rows[$i]['clientid']])) {
                        $postconditionSuccess = false;
                    }
                    // HTML or Flash banners
                    if ($postconditionSuccess == true && $richmedia == false && ($rows[$i]['contenttype'] != 'jpeg' && $rows[$i]['contenttype'] != 'gif' && $rows[$i]['contenttype'] != 'png')) {
                        $postconditionSuccess = false;
                    }
                    // Blocked
                    if ($postconditionSuccess == true && $rows[$i]['block'] > 0 && isset($_COOKIE['phpAds_blockAd'][$rows[$i]['bannerid']]) && $_COOKIE['phpAds_blockAd'][$rows[$i]['bannerid']] > time()) {
                        $postconditionSuccess = false;
                    }
                    // Capped
                    if ($postconditionSuccess == true && $rows[$i]['capping'] > 0 && isset($_COOKIE['phpAds_capAd'][$rows[$i]['bannerid']]) && $_COOKIE['phpAds_capAd'][$rows[$i]['bannerid']] >= $rows[$i]['capping']) {
                        $postconditionSuccess = false;
                    }
                    // ACLs
                    if ($postconditionSuccess == true && $phpAds_config['acl'] && !phpAds_aclCheck($rows[$i], $source)) {
                        $postconditionSuccess = false;
                    }
                    if ($postconditionSuccess == false) {
                        // Failed one of the postconditions
                        // Delete this row
                        $bannerpriority = $rows[$i]['priority'];
                        $campaignid = $rows[$i]['clientid'];
                        $rows[$i] = '';
                        $remaining_rows--;
                        // Assign lost priority to the other banners in the same campaign
                        // Start getting the sum of all priorities
                        $campaingprioritysum = 0;
                        foreach ($campaign_mapping[$campaignid] as $ii) {
                            if (is_array($rows[$ii]) && $rows[$ii]['priority']) {
                                $campaingprioritysum += $rows[$ii]['priority'];
                            }
                        }
                        if ($campaingprioritysum) {
                            // Distribute the priority in a weighted manner
                            $total_increment = 0;
                            foreach ($campaign_mapping[$campaignid] as $ii) {
                                if (is_array($rows[$ii]) && $rows[$ii]['priority']) {
                                    $increment = $bannerpriority * $rows[$ii]['priority'] / $campaingprioritysum;
                                    $rows[$ii]['priority'] += $increment;
                                    $total_increment += $increment;
                                }
                            }
                            // Adjust priority sum, there may have been roundings
                            $prioritysum += $total_increment - $bannerpriority;
                        } else {
                            // No other banners from the same campaign, discard priority
                            $prioritysum -= $bannerpriority;
                        }
                        // Break out of the for loop to try again
                        break;
                    }
                    // Found banner!
                    $rows[$i]['zoneid'] = 0;
                    return $rows[$i];
                }
            }
        }
    }
    return $remaining;
}
function phpAds_fetchBannerDirect($remaining, $clientid = 0, $campaignid = 0, $context = 0, $source = '', $richmedia = true)
{
    global $phpAds_config;
    /*
    //log
    ob_start();
    print_r($GLOBALS);
    $log = ob_get_contents();
    ob_end_clean();
    
    $fh = @fopen('/var/www/html/origin.awarez.net/cache/mydebug.log','a');
    @fwrite($fh, $log);
    @fclose($fh);
    */
    // Get first part, store second part
    $what = strtok($remaining, '|');
    $remaining = strtok('');
    // Expand paths to regular statements
    if (strpos($what, '/') > 0) {
        if (strpos($what, '@') > 0) {
            list($what, $append) = explode('@', $what);
        } else {
            $append = '';
        }
        $seperate = explode('/', $what);
        $expanded = '';
        $collected = array();
        while (list(, $v) = each($seperate)) {
            $expanded .= ($expanded != '' ? ',+' : '') . $v;
            $collected[] = $expanded . ($append != '' ? ',+' . $append : '');
        }
        $what = strtok(implode('|', array_reverse($collected)), '|');
        $remaining = strtok('') . ($remaining != '' ? '|' . $remaining : '');
    }
    $cacheid = 'what=' . $what . '&clientid=' . $clientid . '&campaignid=' . $campaignid . '&remaining=' . ($remaining == '' ? 'true' : 'false');
    // Get cache
    if (!defined('LIBVIEWCACHE_INCLUDED')) {
        include phpAds_path . '/libraries/deliverycache/cache-' . $phpAds_config['delivery_caching'] . '.inc.php';
    }
    $cache = phpAds_cacheFetch($cacheid);
    if (!$cache) {
        if (!defined('LIBVIEWQUERY_INCLUDED')) {
            include phpAds_path . '/libraries/lib-view-query.inc.php';
        }
        if ($campaignid > 0) {
            $precondition = " AND " . $phpAds_config['tbl_campaigns'] . ".campaignid=" . $campaignid . " ";
        } elseif ($clientid > 0) {
            $precondition = " AND " . $phpAds_config['tbl_campaigns'] . ".clientid=" . $clientid . " ";
        } else {
            $precondition = '';
        }
        $select = phpAds_buildQuery($what, $remaining == '', $precondition);
        $res = phpAds_dbQuery($select);
        // Build array for further processing...
        $rows = array();
        $prioritysum = 0;
        while ($tmprow = phpAds_dbFetchArray($res)) {
            // weight of 0 disables the banner
            if ($tmprow['priority']) {
                $prioritysum += $tmprow['priority'];
                $rows[] = $tmprow;
            }
        }
        $cache = array($rows, $what, $prioritysum);
        phpAds_cacheStore($cacheid, $cache);
        // Unpack cache
        list($rows, $what, $prioritysum) = $cache;
    } else {
        // Unpack cache
        list($rows, $what, $prioritysum) = $cache;
    }
    // Build preconditions
    $excludeBannerID = array();
    $excludeCampaignID = array();
    $includeBannerID = array();
    $includeCampaignID = array();
    if (is_array($context)) {
        for ($i = 0; $i < count($context); $i++) {
            list($key, $value) = each($context[$i]);
            $type = 'bannerid';
            $valueArray = explode(':', $value);
            if (count($valueArray) == 1) {
                list($value) = $valueArray;
            } else {
                list($type, $value) = $valueArray;
            }
            if ($type == 'bannerid') {
                switch ($key) {
                    case '!=':
                        $excludeBannerID[$value] = true;
                        break;
                    case '==':
                        $includeBannerID[$value] = true;
                        break;
                }
            }
            if ($type == 'campaignid') {
                switch ($key) {
                    case '!=':
                        $excludeCampaignID[$value] = true;
                        break;
                    case '==':
                        $includeCampaignID[$value] = true;
                        break;
                }
            }
        }
    }
    $maxindex = sizeof($rows);
    while ($prioritysum && sizeof($rows)) {
        $low = 0;
        $high = 0;
        $ranweight = $prioritysum > 1 ? mt_rand(0, $prioritysum - 1) : 0;
        for ($i = 0; $i < $maxindex; $i++) {
            if (is_array($rows[$i])) {
                $low = $high;
                $high += $rows[$i]['priority'];
                if ($high > $ranweight && $low <= $ranweight) {
                    $postconditionSucces = true;
                    // Excludelist banners
                    if (isset($excludeBannerID[$rows[$i]['bannerid']])) {
                        $postconditionSucces = false;
                    } elseif (isset($excludeCampaignID[$rows[$i]['clientid']])) {
                        $postconditionSucces = false;
                    } elseif (sizeof($includeBannerID) && !isset($includeBannerID[$rows[$i]['bannerid']])) {
                        $postconditionSucces = false;
                    } elseif (sizeof($includeCampaignID) && !isset($includeCampaignID[$rows[$i]['clientid']])) {
                        $postconditionSucces = false;
                    } elseif ($richmedia == false && ($rows[$i]['contenttype'] != 'jpeg' && $rows[$i]['contenttype'] != 'gif' && $rows[$i]['contenttype'] != 'png')) {
                        $postconditionSucces = false;
                    } elseif (phpAds_isAdBlocked($rows[$i]['bannerid'], $rows[$i]['block'])) {
                        $postconditionSucces = false;
                    } elseif (phpAds_isAdCapped($rows[$i]['bannerid'], $rows[$i]['capping'], $rows[$i]['session_capping'])) {
                        $postconditionSucces = false;
                    }
                    if ($postconditionSucces == false) {
                        // Failed one of the postconditions
                        // Delete this row and adjust $prioritysum
                        $prioritysum -= $rows[$i]['priority'];
                        $rows[$i] = '';
                        // Break out of the for loop to try again
                        break;
                    }
                    // Banner was not on exclude list
                    // and was on include list (if one existed)
                    // Now continue with ACL check
                    if ($phpAds_config['acl']) {
                        if (phpAds_aclCheck($rows[$i], $source)) {
                            $rows[$i]['zoneid'] = 0;
                            return $rows[$i];
                        }
                        // Matched, but phpAds_aclCheck failed.
                        // Delete this row and adjust $prioritysum
                        $prioritysum -= $rows[$i]['priority'];
                        $rows[$i] = '';
                        // Break out of the for loop to try again
                        break;
                    } else {
                        // Don't check ACLs, found banner!
                        $rows[$i]['zoneid'] = 0;
                        return $rows[$i];
                    }
                }
            }
        }
    }
    return $remaining;
}
function phpAds_showZoneBanners($zoneid)
{
    global $phpAds_config, $phpAds_TextDirection;
    global $strUntitled, $strName, $strID, $strWeight, $strShowBanner;
    global $strCampaignWeight, $strBannerWeight, $strProbability, $phpAds_TextAlignRight;
    global $strRawQueryString, $strZoneProbListChain, $strZoneProbNullPri, $strZoneProbListChainLoop;
    $zonechain = array();
    $what = '';
    $infinite_loop = false;
    while ($zoneid || $what) {
        if ($zoneid) {
            // Get zone
            $zoneres = phpAds_dbQuery("SELECT what,width,height,delivery FROM " . $phpAds_config['tbl_zones'] . " WHERE zoneid='{$zoneid}' ");
            if (phpAds_dbNumRows($zoneres) > 0) {
                $zone = phpAds_dbFetchArray($zoneres);
                // Set what parameter to zone settings
                if (isset($zone['what']) && $zone['what'] != '') {
                    $what = $zone['what'];
                } else {
                    $what = 'default';
                }
            } else {
                $what = '';
            }
            $precondition = '';
            // Size preconditions
            if ($zone['width'] > -1) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".width = " . $zone['width'] . " ";
            }
            if ($zone['height'] > -1) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".height = " . $zone['height'] . " ";
            }
            // Text Ads preconditions
            if ($zone['delivery'] == phpAds_ZoneText) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".storagetype = 'txt' ";
            } else {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".storagetype <> 'txt' ";
            }
            if (!defined('LIBVIEWQUERY_INCLUDED')) {
                include phpAds_path . '/libraries/lib-view-query.inc.php';
            }
            $select = phpAds_buildQuery($what, false, $precondition);
        } else {
            // Direct selection
            if (!defined('LIBVIEWQUERY_INCLUDED')) {
                include phpAds_path . '/libraries/lib-view-query.inc.php';
            }
            $select = phpAds_buildQuery($what, false, '');
            $zone = array('what' => $what);
        }
        $res = phpAds_dbQuery($select);
        $rows = array();
        $prioritysum = 0;
        while ($tmprow = phpAds_dbFetchArray($res)) {
            // weight of 0 disables the banner
            if ($tmprow['priority']) {
                $prioritysum += $tmprow['priority'];
                $rows[$tmprow['bannerid']] = $tmprow;
            }
        }
        if (!count($rows) && isset($zone['chain']) && strlen($zone['chain'])) {
            // Follow the chain if no banner was found
            if (ereg('^zone:([0-9]+)$', $zone['chain'], $match)) {
                // Zone chain
                $zoneid = $match[1];
                $what = '';
            } else {
                // Raw querystring chain
                $zoneid = 0;
                $what = $zone['chain'];
            }
            if (in_array($zone, $zonechain)) {
                // Chain already evaluated, exit
                $zoneid = 0;
                $what = '';
                $infinite_loop = true;
            } else {
                $zonechain[] = $zone;
            }
        } else {
            // No chain settings, exit loop
            $zoneid = 0;
            $what = '';
        }
    }
    if (isset($rows) && is_array($rows)) {
        $i = 0;
        if (count($zonechain)) {
            // Zone Chain
            echo "<br><br><div class='errormessage'><img class='errormessage' src='images/info.gif' width='16' height='16' border='0' align='absmiddle'>";
            echo $infinite_loop ? $strZoneProbListChainLoop : $strZoneProbListChain;
            echo "<br><img src='images/break-el.gif' height='1' width='100%' vspace='6'><br>";
            // echo "</div>";
            /*
            echo "<br><br><table width='100% border='0' align='center' cellspacing='0' cellpadding='0'>";
            echo "<tr><td valign='top'><img src='images/info.gif' align='absmiddle'>&nbsp;</td>";
            echo "<td width='100%'><b>".($infinite_loop ? $strZoneProbListChainLoop : $strZoneProbListChain)."</b></td></tr>";
            echo "</table>";
            phpAds_ShowBreak();
            */
            while (list(, $z) = each($zonechain)) {
                echo "<nobr><img src='images/icon-zone-d.gif' align='absmiddle'>&nbsp;" . phpAds_buildZoneName($z['zoneid'], $z['zonename']);
                echo "&nbsp;<img src='images/" . $phpAds_TextDirection . "/caret-rs.gif'></nobr> ";
            }
            if (isset($zone['zoneid'])) {
                echo "<nobr><img src='images/" . ($infinite_loop ? 'errormessage.gif' : 'icon-zone.gif') . "' align='absmiddle'>&nbsp;<b>" . phpAds_buildZoneName($zone['zoneid'], $zone['zonename']) . "</b></nobr><br>";
            } else {
                echo "<nobr><img src='images/icon-generatecode.gif' align='absmiddle'>&nbsp;<b>" . $GLOBALS['strRawQueryString'] . ":</b> " . htmlentities($zone['what']) . "</nobr><br>";
            }
            echo "</div>";
        }
        // Header
        echo "<br><br>";
        echo "<table width='100%' border='0' align='center' cellspacing='0' cellpadding='0'>";
        echo "<tr height='25'>";
        echo "<td height='25' width='40%'><b>&nbsp;&nbsp;" . $strName . "</b></td>";
        echo "<td height='25'><b>" . $strID . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>";
        echo "<td height='25'><b>" . $strProbability . "</b></td>";
        echo "<td height='25' align='" . $phpAds_TextAlignRight . "'>&nbsp;</td>";
        echo "</tr>";
        echo "<tr height='1'><td colspan='4' bgcolor='#888888'><img src='images/break.gif' height='1' width='100%'></td></tr>";
        // Banners
        for (reset($rows); $key = key($rows); next($rows)) {
            $name = phpAds_getBannerName($rows[$key]['bannerid'], 60, false);
            if ($i > 0) {
                echo "<tr height='1'><td colspan='4' bgcolor='#888888'><img src='images/break-l.gif' height='1' width='100%'></td></tr>";
            }
            echo "<tr height='25' " . ($i % 2 == 0 ? "bgcolor='#F6F6F6'" : "") . ">";
            echo "<td height='25'>";
            echo "&nbsp;&nbsp;";
            // Banner icon
            if ($rows[$key]['storagetype'] == 'html') {
                echo "<img src='images/icon-banner-html.gif' align='absmiddle'>&nbsp;";
            } elseif ($rows[$key]['storagetype'] == 'txt') {
                echo "<img src='images/icon-banner-text.gif' align='absmiddle'>&nbsp;";
            } elseif ($rows[$key]['storagetype'] == 'url') {
                echo "<img src='images/icon-banner-url.gif' align='absmiddle'>&nbsp;";
            } else {
                echo "<img src='images/icon-banner-stored.gif' align='absmiddle'>&nbsp;";
            }
            // Name
            if (phpAds_isUser(phpAds_Admin) || phpAds_isUser(phpAds_Agency)) {
                echo "<a href='banner-edit.php?clientid=" . phpAds_getCampaignParentClientID($rows[$key]['campaignid']) . "&campaignid=" . $rows[$key]['campaignid'] . "&bannerid=" . $rows[$key]['bannerid'] . "'>" . $name . "</a>";
            } else {
                echo $name;
            }
            echo "</td>";
            echo "<td height='25'>" . $rows[$key]['bannerid'] . "</td>";
            echo "<td height='25'>" . number_format($rows[$key]['priority'] / $prioritysum * 100, $phpAds_config['percentage_decimals']) . "%</td>";
            // Show banner
            if ($rows[$key]['contenttype'] == 'txt') {
                $width = 300;
                $height = 200;
            } else {
                $width = $rows[$key]['width'] + 64;
                $height = $rows[$key]['bannertext'] ? $rows[$key]['height'] + 90 : $rows[$key]['height'] + 64;
            }
            echo "<td height='25' align='" . $phpAds_TextAlignRight . "'>";
            echo "<a href='banner-htmlpreview.php?bannerid=" . $rows[$key]['bannerid'] . "' target='_new' ";
            echo "onClick=\"return openWindow('banner-htmlpreview.php?bannerid=" . $rows[$key]['bannerid'] . "', '', 'status=no,scrollbars=no,resizable=no,width=" . $width . ",height=" . $height . "');\">";
            echo "<img src='images/icon-zoom.gif' align='absmiddle' border='0'>&nbsp;" . $strShowBanner . "</a>&nbsp;&nbsp;";
            echo "</td>";
            echo "</tr>";
            $i++;
        }
        if (!$i) {
            echo "<tr height='25' bgcolor='#F6F6F6'>";
            echo "<td colspan='4'>&nbsp;&nbsp;" . $strZoneProbNullPri . "</td>";
            echo "</tr>";
        }
        // Footer
        echo "<tr height='1'><td colspan='4' bgcolor='#888888'><img src='images/break.gif' height='1' width='100%'></td></tr>";
        echo "</table>";
    }
}
function phpAds_fetchBannerZone($remaining, $clientid, $campaignid, $context = 0, $source = '', $richmedia = true)
{
    global $phpAds_config;
    global $phpAds_followedChain;
    // Get first part, store second part
    $what = strtok($remaining, '|');
    $remaining = strtok('');
    $zoneid = substr($what, 5);
    // Check if zone was already evaluated in the chain
    if (isset($phpAds_followedChain) && in_array($zoneid, $phpAds_followedChain)) {
        return $remaining;
    } else {
        $phpAds_followedChain[] = $zoneid;
    }
    // Get cache
    if (!defined('LIBVIEWCACHE_INCLUDED')) {
        include phpAds_path . '/libraries/deliverycache/cache-' . $phpAds_config['delivery_caching'] . '.inc.php';
    }
    $cache = phpAds_cacheFetch('what=zone:' . $zoneid);
    if (!$cache) {
        $zoneres = phpAds_dbQuery("SELECT * FROM " . $phpAds_config['tbl_zones'] . " WHERE zoneid='" . $zoneid . "'");
        if ($zone = phpAds_dbFetchArray($zoneres)) {
            // No linked banners
            if ($remaining == '') {
                $remaining = $zone['chain'];
            }
            if ($zone['what'] == '') {
                return $remaining;
            }
            if (!defined('LIBVIEWQUERY_INCLUDED')) {
                include phpAds_path . '/libraries/lib-view-query.inc.php';
            }
            $precondition = '';
            // Size preconditions
            if ($zone['width'] > -1) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".width = " . $zone['width'] . " ";
            }
            if ($zone['height'] > -1) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".height = " . $zone['height'] . " ";
            }
            // Text Ads preconditions
            // Matching against the value instead of the constant phpAds_ZoneText (3).
            // Didn't want to include the whole lib-zones just for a constant
            if ($zone['delivery'] == 3) {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".storagetype = 'txt' ";
            } else {
                $precondition .= " AND " . $phpAds_config['tbl_banners'] . ".storagetype <> 'txt' ";
            }
            $select = phpAds_buildQuery($zone['what'], false, $precondition);
            $res = phpAds_dbQuery($select);
            // Build array for further processing...
            $rows = array();
            $prioritysum = 0;
            while ($tmprow = phpAds_dbFetchArray($res)) {
                // weight of 0 disables the banner
                if ($tmprow['priority']) {
                    $prioritysum += $tmprow['priority'];
                    $rows[] = $tmprow;
                }
            }
            $cache = array($zone['zoneid'], $rows, $zone['what'], $prioritysum, $zone['chain'], $zone['prepend'], $zone['append']);
            phpAds_cacheStore('what=zone:' . $zone['zoneid'], $cache);
            // Unpack cache
            list($zoneid, $rows, $what, $prioritysum, $chain, $prepend, $append) = $cache;
        } else {
            // Zone not found
            return $remaining;
        }
    } else {
        // Unpack cache
        list($zoneid, $rows, $what, $prioritysum, $chain, $prepend, $append) = $cache;
        if ($remaining == '') {
            $remaining = $chain;
        }
        if (count($rows) == 0) {
            return $remaining;
        }
    }
    // Build preconditions
    $excludeBannerID = array();
    $excludeCampaignID = array();
    $includeBannerID = array();
    $includeCampaignID = array();
    if (is_array($context)) {
        for ($i = 0; $i < count($context); $i++) {
            list($key, $value) = each($context[$i]);
            $type = 'bannerid';
            $valueArray = explode(':', $value);
            if (count($valueArray) == 1) {
                list($value) = $valueArray;
            } else {
                list($type, $value) = $valueArray;
            }
            if ($type == 'bannerid') {
                switch ($key) {
                    case '!=':
                        $excludeBannerID[$value] = true;
                        break;
                    case '==':
                        $includeBannerID[$value] = true;
                        break;
                }
            }
            if ($type == 'campaignid') {
                switch ($key) {
                    case '!=':
                        $excludeCampaignID[$value] = true;
                        break;
                    case '==':
                        $includeCampaignID[$value] = true;
                        break;
                }
            }
        }
    }
    $maxindex = sizeof($rows);
    while ($prioritysum && sizeof($rows)) {
        $low = 0;
        $high = 0;
        $ranweight = $prioritysum > 1 ? mt_rand(0, $prioritysum - 1) : 0;
        for ($i = 0; $i < $maxindex; $i++) {
            if (is_array($rows[$i])) {
                $low = $high;
                $high += $rows[$i]['priority'];
                if ($high > $ranweight && $low <= $ranweight) {
                    $postconditionSucces = true;
                    // Excludelist banners
                    if (isset($excludeBannerID[$rows[$i]['bannerid']])) {
                        $postconditionSucces = false;
                    } elseif (isset($excludeCampaignID[$rows[$i]['campaignid']])) {
                        $postconditionSucces = false;
                    } elseif (sizeof($includeBannerID) && !isset($includeBannerID[$rows[$i]['bannerid']])) {
                        $postconditionSucces = false;
                    } elseif (sizeof($includeCampaignID) && !isset($includeCampaignID[$rows[$i]['campaignid']])) {
                        $postconditionSucces = false;
                    } elseif ($richmedia == false && ($rows[$i]['contenttype'] != 'jpeg' && $rows[$i]['contenttype'] != 'gif' && $rows[$i]['contenttype'] != 'png')) {
                        $postconditionSucces = false;
                    } elseif (phpAds_isAdBlocked($rows[$i]['bannerid'], $rows[$i]['block'])) {
                        $postconditionSucces = false;
                    } elseif (phpAds_isAdCapped($rows[$i]['bannerid'], $rows[$i]['capping'], $rows[$i]['session_capping'])) {
                        $postconditionSucces = false;
                    }
                    if ($postconditionSucces == false) {
                        // Failed one of the postconditions
                        // Delete this row and adjust $prioritysum
                        $prioritysum -= $rows[$i]['priority'];
                        $rows[$i] = '';
                        // Break out of the for loop to try again
                        break;
                    }
                    // Banner was not on exclude list
                    // and was on include list (if one existed)
                    // Now continue with ACL check
                    if ($phpAds_config['acl']) {
                        if (phpAds_aclCheck($rows[$i], $source)) {
                            $rows[$i]['zoneid'] = $zoneid;
                            $rows[$i]['append'] = $append;
                            $rows[$i]['prepend'] = $prepend;
                            return $rows[$i];
                        }
                        // Matched, but phpAds_aclCheck failed.
                        // Delete this row and adjust $prioritysum
                        $prioritysum -= $rows[$i]['priority'];
                        $rows[$i] = '';
                        // Break out of the for loop to try again
                        break;
                    } else {
                        // Don't check ACLs, found banner!
                        $rows[$i]['zoneid'] = $zoneid;
                        $rows[$i]['append'] = $append;
                        $rows[$i]['prepend'] = $prepend;
                        return $rows[$i];
                    }
                }
            }
        }
    }
    return $remaining;
}