function phpAds_getDaysLeft($campaignid)
{
    global $phpAds_config;
    global $date_format;
    // uses the following language settings:
    global $strExpiration, $strNoExpiration, $strDaysLeft, $strEstimated;
    // preset return values
    $estimated_end = "-";
    $days_left = "-";
    $description = "";
    $absolute = 0;
    // Get client record
    $campaign_query = "SELECT" . " views" . ",clicks" . ",expire" . ",DATE_FORMAT(expire, '" . $date_format . "') as expire_f" . ",TO_DAYS(expire)-TO_DAYS(NOW()) as days_left" . " FROM " . $phpAds_config['tbl_campaigns'] . " WHERE campaignid=" . $campaignid;
    $res_campaign = phpAds_dbQuery($campaign_query) or phpAds_sqlDie();
    if (phpAds_dbNumRows($res_campaign) == 1) {
        $row_campaign = phpAds_dbFetchArray($res_campaign);
        // Check if the expiration date is set
        if ($row_campaign['expire'] != '0000-00-00' && $row_campaign['expire'] != '') {
            $expiration[] = array("days_left" => round($row_campaign["days_left"]), "date" => $row_campaign["expire_f"], "absolute" => true);
        }
        if ($row_campaign["views"] != -1) {
            $view_query = "SELECT" . " SUM(views) as total_views" . ",MAX(TO_DAYS(day))-TO_DAYS(NOW()) as days_since_last_view" . ",TO_DAYS(NOW())-MIN(TO_DAYS(day)) as days_since_start" . " FROM " . $phpAds_config['tbl_banners'] . " AS b" . " LEFT JOIN " . $phpAds_config['tbl_adstats'] . " AS v" . " USING (bannerid)" . " WHERE b.campaignid=" . $campaignid;
            $res_views = phpAds_dbQuery($view_query) or phpAds_sqlDie();
            if (phpAds_dbNumRows($res_views) == 1) {
                $row_views = phpAds_dbFetchArray($res_views);
                if (!isset($row_views["days_since_start"]) || $row_views["days_since_start"] == '' || $row_views["days_since_start"] == 0 || $row_views["days_since_start"] == null) {
                    $row_views["days_since_start"] = 1;
                }
                if (!empty($row_views["total_views"]) && $row_views["total_views"] > 0) {
                    $days_left = round($row_campaign["views"] / ($row_views["total_views"] / $row_views["days_since_start"]));
                    if ($row_campaign["views"] > 0) {
                        $estimated_end = strftime($date_format, mktime(0, 0, 0, date("m"), date("d") + $days_left, date("Y")));
                        $expiration[] = array("days_left" => $days_left, "date" => $estimated_end, "absolute" => false);
                    } else {
                        $estimated_end = strftime($date_format, mktime(0, 0, 0, date("m"), date("d") - $row_views["days_since_last_view"], date("Y")));
                        $expiration[] = array("days_left" => 0 - $row_views["days_since_last_view"], "date" => $estimated_end, "absolute" => true);
                    }
                }
            }
        }
        if ($row_campaign["clicks"] != -1) {
            $click_query = "SELECT" . " SUM(clicks) as total_clicks" . ",MAX(TO_DAYS(day))-TO_DAYS(NOW()) as days_since_last_click" . ",TO_DAYS(NOW())-MIN(TO_DAYS(day)) as days_since_start" . " FROM " . $phpAds_config['tbl_adstats'] . " LEFT JOIN " . $phpAds_config['tbl_banners'] . " USING (bannerid)" . " WHERE campaignid=" . $clientid . " AND clicks > 0";
            $res_clicks = phpAds_dbQuery($click_query) or phpAds_sqlDie();
            if (phpAds_dbNumRows($res_clicks) == 1) {
                $row_clicks = phpAds_dbFetchArray($res_clicks);
                if (!isset($row_clicks["days_since_start"]) || $row_clicks["days_since_start"] == '' || $row_clicks["days_since_start"] == 0 || $row_clicks["days_since_start"] == null) {
                    $row_clicks["days_since_start"] = 1;
                }
                if (!empty($row_clicks["total_clicks"]) && $row_clicks["total_clicks"] > 0) {
                    $days_left = round($row_campaign["clicks"] / ($row_clicks["total_clicks"] / $row_clicks["days_since_start"]));
                    if ($row_campaign["clicks"] > 0) {
                        $estimated_end = strftime($date_format, mktime(0, 0, 0, date("m"), date("d") + $days_left, date("Y")));
                        $expiration[] = array("days_left" => $days_left, "date" => $estimated_end, "absolute" => false);
                    } else {
                        $estimated_end = strftime($date_format, mktime(0, 0, 0, date("m"), date("d") - $row_clicks["days_since_last_view"], date("Y")));
                        $expiration[] = array("days_left" => 0 - $row_clicks["days_since_last_view"], "date" => $estimated_end, "absolute" => true);
                    }
                }
            }
        }
    }
    // Build Return value
    if (isset($expiration) && sizeof($expiration) > 0) {
        $sooner = $expiration[0];
        for ($i = 0; $i < sizeof($expiration); $i++) {
            if ($expiration[$i]['days_left'] < $sooner['days_left']) {
                $sooner = $expiration[$i];
            }
        }
        if ($sooner['days_left'] < 0) {
            $sooner['days_left'] = 0;
        }
        if ($sooner['absolute']) {
            $ret_val[] = $strExpiration . ": " . $sooner['date'] . " (" . $strDaysLeft . ": " . $sooner['days_left'] . ")";
        } else {
            $ret_val[] = $strEstimated . ": " . $sooner['date'] . " (" . $strDaysLeft . ": " . $sooner['days_left'] . ")";
        }
        $ret_val[] = $sooner['date'];
        $ret_val[] = $sooner['days_left'];
    } else {
        // Unknown
        $ret_val[] = $strExpiration . ": " . $strNoExpiration;
        $ret_val[] = '';
        $ret_val[] = '';
    }
    return isset($ret_val) ? $ret_val : false;
}
                $zone_count++;
                $row['linked'] = true;
                $affiliates[$row['affiliateid']]['zones'][$row['zoneid']] = $row;
                $affiliates[$row['affiliateid']]['ZoneCampaigns']++;
            }
        }
    }
} else {
    if (phpAds_isUser(phpAds_Admin)) {
        $query = "SELECT" . " z.zoneid as zoneid" . ",z.affiliateid as affiliateid" . ",z.zonename as zonename" . ",z.description as description" . ",z.width as width" . ",z.height as height" . ",z.what as what" . ",z.zonetype as zonetype" . ",z.delivery as delivery" . " FROM " . $phpAds_config['tbl_zones'] . " AS z" . "," . $phpAds_config['tbl_banners'] . " AS b" . " WHERE b.bannerid=" . $bannerid . " AND (z.width=b.width OR z.width=-1)" . " AND (z.height=b.height OR z.height=-1)" . " AND z.zonetype=" . phpAds_ZoneBanners . " AND z.delivery != " . phpAds_ZoneText . phpAds_getZoneListOrder($listorder, $orderdirection);
    } elseif (phpAds_isUser(phpAds_Agency)) {
        $query = "SELECT" . " z.zoneid as zoneid" . ",z.affiliateid as affiliateid" . ",z.zonename as zonename" . ",z.description as description" . ",z.width as width" . ",z.height as height" . ",z.what as what" . ",z.zonetype as zonetype" . ",z.delivery as delivery" . " FROM " . $phpAds_config['tbl_zones'] . " AS z" . "," . $phpAds_config['tbl_banners'] . " AS b" . "," . $phpAds_config['tbl_affiliates'] . " AS a" . " WHERE a.affiliateid=z.affiliateid" . " AND a.agencyid=" . phpAds_getUserID() . " AND b.bannerid=" . $bannerid . " AND (z.width=b.width OR z.width=-1)" . " AND (z.height=b.height OR z.height=-1)" . " AND z.zonetype=" . phpAds_ZoneBanners . " AND z.delivery != " . phpAds_ZoneText . phpAds_getZoneListOrder($listorder, $orderdirection);
    }
    // Get banner zones
    $res = phpAds_dbQuery($query) or phpAds_sqlDie();
    $zone_count = phpAds_dbNumRows($res);
    while ($row = phpAds_dbFetchArray($res)) {
        if (isset($affiliates[$row['affiliateid']])) {
            $row['linked'] = phpAds_IsBannerInZone($bannerid, $row['zoneid'], $row['what']);
            $affiliates[$row['affiliateid']]['zones'][$row['zoneid']] = $row;
            $affiliates[$row['affiliateid']]['ZoneBanners']++;
        }
    }
    if (phpAds_isUser(phpAds_Admin)) {
        $query = "SELECT zoneid,affiliateid,zonename,description,width,height,what,zonetype,delivery" . " FROM " . $phpAds_config['tbl_zones'] . " WHERE zonetype=" . phpAds_ZoneCampaign . phpAds_getZoneListOrder($listorder, $orderdirection);
    } elseif (phpAds_isUser(phpAds_Agency)) {
        $query = "SELECT z.zoneid,z.affiliateid,z.zonename,z.description,z.width,z.height,z.what,z.zonetype,z.delivery" . " FROM " . $phpAds_config['tbl_zones'] . " AS z" . "," . $phpAds_config['tbl_affiliates'] . " AS a" . " WHERE z.affiliateid=a.affiliateid" . " AND a.agencyid=" . phpAds_getUserID() . " AND z.zonetype=" . phpAds_ZoneCampaign . phpAds_getZoneListOrder($listorder, $orderdirection);
    }
    // Get campaign zones
    $res = phpAds_dbQuery($query) or phpAds_sqlDie();
    while ($row = phpAds_dbFetchArray($res)) {
        echo "<a href='tracker-campaigns.php?clientid=" . $clientid . "&trackerid=" . $row_trackers['trackerid'] . "'><img src='images/icon-zone-linked.gif' border='0' align='absmiddle'>&nbsp;{$strLinkedCampaigns}</a>";
    } else {
        echo "&nbsp;";
    }
    echo "</td>\n";
    echo "\t\t\t\t\t<td height='25'>";
    if (phpAds_isUser(phpAds_Admin) || phpAds_isUser(phpAds_Agency) || phpAds_isAllowed(phpAds_DeleteTracker)) {
        echo "<a href='tracker-delete.php?clientid=" . $clientid . "&trackerid=" . $row_trackers['trackerid'] . "&returnurl=advertiser-trackers.php'" . phpAds_DelConfirm($strConfirmDeleteTracker) . "><img src='images/icon-recycle.gif' border='0' align='absmiddle' alt='{$strDelete}'>&nbsp;{$strDelete}</a>";
    } else {
        echo "&nbsp;";
    }
    echo "</td>\n";
    echo "\t\t\t\t</tr>\n";
    $i++;
}
if (phpAds_dbNumRows($res_trackers) > 0) {
    //	echo "\t\t\t\t<tr height='1'>\n";
    //	echo "\t\t\t\t\t<td colspan='4' bgcolor='#888888'><img src='images/break.gif' height='1' width='100%'></td>\n";
    //	echo "\t\t\t\t</tr>\n";
    //}
    //if (isset($campaigns) && count($campaigns))
    //{
    echo "\t\t\t\t<tr height='1'>\n";
    echo "\t\t\t\t\t<td colspan='4' bgcolor='#888888'><img src='images/break-el.gif' height='1' width='100%'></td>\n";
    echo "\t\t\t\t</tr>\n";
    echo "\t\t\t\t<tr height='25'>\n";
    echo "\t\t\t\t\t<td colspan='4' height='25' align='" . $phpAds_TextAlignRight . "'>";
    echo "<img src='images/icon-recycle.gif' border='0' align='absmiddle'>&nbsp;<a href='tracker-delete.php?clientid=" . $clientid . "&returnurl=advertiser-trackers.php'" . phpAds_DelConfirm($strConfirmDeleteAllTrackers) . ">{$strDeleteAllTrackers}</a>&nbsp;&nbsp;";
    echo "</td>\n";
    echo "\t\t\t\t</tr>\n";
}
// Include required files
include "lib-settings.inc.php";
include "lib-languages.inc.php";
// Register input variables
phpAds_registerGlobal('admin', 'pwold', 'pw', 'pw2', 'admin_fullname', 'admin_email', 'company_name', 'language', 'updates_frequency', 'admin_novice', 'userlog_email', 'userlog_priority', 'userlog_autoclean');
// Security check
phpAds_checkAccess(phpAds_Admin);
$errormessage = array();
$sql = array();
if (isset($HTTP_POST_VARS['submit']) && $HTTP_POST_VARS['submit'] == 'true') {
    if (isset($admin)) {
        if (!strlen($admin)) {
            $errormessage[0][] = $strInvalidUsername;
        } elseif (phpAds_dbNumRows(phpAds_dbQuery("SELECT * FROM " . $phpAds_config['tbl_clients'] . " WHERE LOWER(clientusername) = '" . strtolower($admin) . "'"))) {
            $errormessage[0][] = $strDuplicateClientName;
        } elseif (phpAds_dbNumRows(phpAds_dbQuery("SELECT * FROM " . $phpAds_config['tbl_affiliates'] . " WHERE LOWER(username) = '" . strtolower($admin) . "'"))) {
            $errormessage[0][] = $strDuplicateClientName;
        } else {
            phpAds_SettingsWriteAdd('admin', $admin);
        }
    }
    if (isset($pwold) && strlen($pwold) || isset($pw) && strlen($pw) || isset($pw2) && strlen($pw2)) {
        if (md5($pwold) != $phpAds_config['admin_pw']) {
            $errormessage[0][] = $strPasswordWrong;
        } elseif (!strlen($pw) || strstr("\\", $pw)) {
            $errormessage[0][] = $strInvalidPassword;
        } elseif (strcmp($pw, $pw2)) {
            $errormessage[0][] = $strNotSamePasswords;
        } else {
            $admin_pw = $pw;
            phpAds_SettingsWriteAdd('admin_pw', md5($admin_pw));
function days_left($clientid)
{
    global $phpAds_config;
    global $date_format;
    // uses the following language settings:
    global $strExpiration, $strNoExpiration, $strDaysLeft, $strEstimated;
    // preset return values
    $estimated_end = "-";
    $days_left = "-";
    $description = "";
    $absolute = 0;
    // Get client record
    $client_query = "\n\t\tSELECT\n\t\t\tviews,\n\t\t\tclicks,\n\t\t\texpire,\n\t\t\tDATE_FORMAT(expire, '" . $date_format . "') as expire_f,\n\t\t\tTO_DAYS(expire)-TO_DAYS(NOW()) as days_left\n\t\tFROM\n\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\tWHERE \n\t\t\tclientid = " . $clientid;
    $res_client = phpAds_dbQuery($client_query) or phpAds_sqlDie();
    if (phpAds_dbNumRows($res_client) == 1) {
        $row_client = phpAds_dbFetchArray($res_client);
        // Check if the expiration date is set
        if ($row_client['expire'] != '0000-00-00' && $row_client['expire'] != '') {
            $expiration[] = array("days_left" => round($row_client["days_left"]), "date" => $row_client["expire_f"], "absolute" => true);
        }
        if ($row_client["views"] != -1) {
            if ($phpAds_config['compact_stats']) {
                $view_query = "\n\t               \tSELECT\n\t                   \tSUM(views) as total_views,\n\t                    MAX(TO_DAYS(day))-TO_DAYS(NOW()) as days_since_last_view,\n\t                    TO_DAYS(NOW())-MIN(TO_DAYS(day)) as days_since_start\n\t                FROM\n\t                   \t" . $phpAds_config['tbl_banners'] . " AS b\n\t                    LEFT JOIN " . $phpAds_config['tbl_adstats'] . " AS v USING (bannerid)\n\t                WHERE\n\t                  \tb.clientid = {$clientid}";
            } else {
                $view_query = "\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tcount(*) as total_views,\n\t\t\t\t\t\tMAX(TO_DAYS(v.t_stamp))-TO_DAYS(NOW()) as days_since_last_view,\n\t\t\t\t\t\tTO_DAYS(NOW())-MIN(TO_DAYS(v.t_stamp)) as days_since_start\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . $phpAds_config['tbl_adviews'] . " AS v, \n\t\t\t\t\t\t" . $phpAds_config['tbl_banners'] . " AS b \n\t\t\t\t\tWHERE\n\t\t\t\t\t\tb.clientid = {$clientid} \n\t\t\t\t\t\tAND\n\t\t\t\t\t\tb.bannerid = v.bannerid";
            }
            $res_views = phpAds_dbQuery($view_query) or phpAds_sqlDie();
            if (phpAds_dbNumRows($res_views) == 1) {
                $row_views = phpAds_dbFetchArray($res_views);
                if (!isset($row_views["days_since_start"]) || $row_views["days_since_start"] == '' || $row_views["days_since_start"] == 0 || $row_views["days_since_start"] == null) {
                    $row_views["days_since_start"] = 1;
                }
                if (!empty($row_views["total_views"]) && $row_views["total_views"] > 0) {
                    $days_left = round($row_client["views"] / ($row_views["total_views"] / $row_views["days_since_start"]));
                    if ($row_client["views"] > 0) {
                        $estimated_end = strftime($date_format, @mktime(0, 0, 0, date("m"), date("d") + $days_left, date("Y")));
                        $expiration[] = array("days_left" => $days_left, "date" => $estimated_end, "absolute" => false);
                    } else {
                        $estimated_end = strftime($date_format, @mktime(0, 0, 0, date("m"), date("d") - $row_views["days_since_last_view"], date("Y")));
                        $expiration[] = array("days_left" => 0 - $row_views["days_since_last_view"], "date" => $estimated_end, "absolute" => true);
                    }
                }
            }
        }
        if ($row_client["clicks"] != -1) {
            if ($phpAds_config['compact_stats']) {
                $click_query = "\n                \tSELECT\n                    \tSUM(clicks) as total_clicks,\n                        MAX(TO_DAYS(day))-TO_DAYS(NOW()) as days_since_last_click,\n                        TO_DAYS(NOW())-MIN(TO_DAYS(day)) as days_since_start\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . $phpAds_config['tbl_adstats'] . "\n\t\t\t\t\t\tLEFT JOIN " . $phpAds_config['tbl_banners'] . " USING (bannerid)\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tclientid = '{$clientid}' AND\n\t\t\t\t\t\tclicks > 0";
            } else {
                $click_query = "\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tcount(*) as total_clicks,\n\t\t\t\t\t\tMAX(TO_DAYS(c.t_stamp))- TO_DAYS(NOW()) as days_since_last_click,\n\t\t\t\t\t\tTO_DAYS(NOW())-MIN(TO_DAYS(c.t_stamp)) as days_since_start\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . $phpAds_config['tbl_adclicks'] . " AS c, \n\t\t\t\t\t\t" . $phpAds_config['tbl_banners'] . " AS b \n\t\t\t\t\tWHERE \n\t\t\t\t\t\tb.clientid = {$clientid} AND\n\t\t\t\t\t\tb.bannerid = c.bannerid";
            }
            $res_clicks = phpAds_dbQuery($click_query) or phpAds_sqlDie();
            if (phpAds_dbNumRows($res_clicks) == 1) {
                $row_clicks = phpAds_dbFetchArray($res_clicks);
                if (!isset($row_clicks["days_since_start"]) || $row_clicks["days_since_start"] == '' || $row_clicks["days_since_start"] == 0 || $row_clicks["days_since_start"] == null) {
                    $row_clicks["days_since_start"] = 1;
                }
                if (!empty($row_clicks["total_clicks"]) && $row_clicks["total_clicks"] > 0) {
                    $days_left = round($row_client["clicks"] / ($row_clicks["total_clicks"] / $row_clicks["days_since_start"]));
                    if ($row_client["clicks"] > 0) {
                        $estimated_end = strftime($date_format, @mktime(0, 0, 0, date("m"), date("d") + $days_left, date("Y")));
                        $expiration[] = array("days_left" => $days_left, "date" => $estimated_end, "absolute" => false);
                    } else {
                        $estimated_end = strftime($date_format, @mktime(0, 0, 0, date("m"), date("d") - $row_clicks["days_since_last_view"], date("Y")));
                        $expiration[] = array("days_left" => 0 - $row_clicks["days_since_last_view"], "date" => $estimated_end, "absolute" => true);
                    }
                }
            }
        }
    }
    // Build Return value
    if (isset($expiration) && sizeof($expiration) > 0) {
        $sooner = $expiration[0];
        for ($i = 0; $i < sizeof($expiration); $i++) {
            if ($expiration[$i]['days_left'] < $sooner['days_left']) {
                $sooner = $expiration[$i];
            }
        }
        if ($sooner['days_left'] < 0) {
            $sooner['days_left'] = 0;
        }
        if ($sooner['absolute']) {
            $ret_val[] = $strExpiration . ": " . $sooner['date'] . " (" . $strDaysLeft . ": " . $sooner['days_left'] . ")";
        } else {
            $ret_val[] = $strEstimated . ": " . $sooner['date'] . " (" . $strDaysLeft . ": " . $sooner['days_left'] . ")";
        }
        $ret_val[] = $sooner['date'];
        $ret_val[] = $sooner['days_left'];
    } else {
        // Unknown
        $ret_val[] = $strExpiration . ": " . $strNoExpiration;
        $ret_val[] = '';
        $ret_val[] = '';
    }
    return isset($ret_val) ? $ret_val : false;
}
function phpAds_totalStats($table, $column, $bannerid, $timeconstraint = "")
{
    global $phpAds_config;
    if ($phpAds_config['compact_stats']) {
        $where = "";
        if (!empty($bannerid)) {
            $where = "WHERE bannerid = '{$bannerid}'";
        }
        if (!empty($timeconstraint)) {
            if (!empty($bannerid)) {
                $where .= " AND ";
            } else {
                $where = "WHERE ";
            }
            if ($timeconstraint == "month") {
                $begin = date('Ymd', mktime(0, 0, 0, date('m'), 1, date('Y')));
                $end = date('Ymd', mktime(0, 0, 0, date('m') + 1, 1, date('Y')));
                $where .= "day >= {$begin} AND day < {$end}";
            } elseif ($timeconstraint == "week") {
                $begin = date('Ymd', mktime(0, 0, 0, date('m'), date('d') - 6, date('Y')));
                $end = date('Ymd', mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')));
                $where .= "day >= {$begin} AND day < {$end}";
            } else {
                $begin = date('Ymd', mktime(0, 0, 0, date('m'), date('d'), date('Y')));
                $where .= "day = {$begin}";
            }
        }
        $res = phpAds_dbQuery("SELECT SUM({$column}) as qnt FROM " . $phpAds_config['tbl_adstats'] . " {$where}") or phpAds_sqlDie();
        if (phpAds_dbNumRows($res)) {
            $row = phpAds_dbFetchArray($res);
            return $row['qnt'];
        } else {
            return 0;
        }
    } else {
        $where = "";
        if (!empty($bannerid)) {
            $where = "WHERE bannerid = '{$bannerid}'";
        }
        if (!empty($timeconstraint)) {
            if (!empty($bannerid)) {
                $where .= " AND ";
            } else {
                $where = "WHERE ";
            }
            if ($timeconstraint == "month") {
                $begin = date('YmdHis', mktime(0, 0, 0, date('m'), 1, date('Y')));
                $end = date('YmdHis', mktime(0, 0, 0, date('m') + 1, 1, date('Y')));
                $where .= "t_stamp >= {$begin} AND t_stamp < {$end}";
            } elseif ($timeconstraint == "week") {
                $begin = date('YmdHis', mktime(0, 0, 0, date('m'), date('d') - 6, date('Y')));
                $end = date('YmdHis', mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')));
                $where .= "t_stamp >= {$begin} AND t_stamp < {$end}";
            } else {
                $begin = date('YmdHis', mktime(0, 0, 0, date('m'), date('d'), date('Y')));
                $end = date('YmdHis', mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')));
                $where .= "t_stamp >= {$begin} AND t_stamp < {$end}";
            }
        }
        $res = phpAds_dbQuery("SELECT count(*) as qnt FROM {$table} {$where}") or phpAds_sqlDie();
        if (phpAds_dbNumRows($res)) {
            $row = phpAds_dbFetchArray($res);
            return $row['qnt'];
        } else {
            return 0;
        }
    }
}
function phpAds_upgradeSplitClientTable()
{
    global $phpAds_config;
    if (!isset($phpAds_config['config_version']) || $phpAds_config['config_version'] < 200.162) {
        $res = phpAds_dbQuery("DESCRIBE " . $phpAds_config['tbl_clients']);
        if (phpAds_dbNumRows($res) > 0) {
            $res = phpAds_dbQuery("SELECT * FROM " . $phpAds_config['tbl_clients'] . " WHERE parent > 0");
            if ($row['target'] > 0 && $row['weight'] == 0) {
                $row['priority'] = 'h';
            } else {
                $row['priority'] = 'l';
            }
            $row['optimise'] = 'f';
            $row['anonymous'] = 'f';
            while ($row = phpAds_dbFetchArray($res)) {
                phpAds_dbQuery("INSERT INTO " . $phpAds_config['tbl_campaigns'] . " (campaignid" . ",campaignname" . ",views" . ",clicks" . ",conversions" . ",expire" . ",activate" . ",active" . ",weight" . ",target" . ",clientid" . ",priority" . ",optimise" . ",anonymous)" . " VALUES " . "('" . $row['clientid'] . "'" . ",'" . $row['clientname'] . "'" . ",'" . $row['views'] . "'" . ",'" . $row['clicks'] . "'" . ",'" . $row['conversions'] . "'" . ",'" . $row['expire'] . "'" . ",'" . $row['activate'] . "'" . ",'" . $row['active'] . "'" . ",'" . $row['weight'] . "'" . ",'" . $row['target'] . "'" . ",'" . $row['parent'] . "'" . ",'" . $row['priority'] . "'" . ",'" . $row['optimise'] . "'" . ",'" . $row['anonymous'] . "')") or phpAds_sqlDie();
            }
            // Delete rows moved into campaign table
            phpAds_dbQuery("DELETE FROM " . $phpAds_config['tbl_clients'] . " WHERE parent > 0");
            // Delete old columns
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN views");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN clicks");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN expire");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN activate");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN active");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN weight");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN target");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN parent");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN conversions");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN priority");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN optimise");
            phpAds_dbQuery("ALTER TABLE " . $phpAds_config['tbl_clients'] . " DROP COLUMN anonymous");
        }
    }
}
    echo "<tr height='25' " . ($i % 2 == 0 ? "bgcolor='#F6F6F6'" : "") . ">";
    // Empty
    echo "<td>&nbsp;</td>";
    // Button 1, 2 & 3
    echo "<td height='25' colspan='3'>";
    if (phpAds_isUser(phpAds_Admin) || phpAds_isAllowed(phpAds_LinkBanners)) {
        echo "<a href='zone-include.php?affiliateid=" . $affiliateid . "&zoneid=" . $row_zones['zoneid'] . "'><img src='images/icon-zone-linked.gif' border='0' align='absmiddle' alt='{$strIncludedBanners}'>&nbsp;{$strIncludedBanners}</a>&nbsp;&nbsp;&nbsp;&nbsp;";
    }
    echo "<a href='zone-probability.php?affiliateid=" . $affiliateid . "&zoneid=" . $row_zones['zoneid'] . "'><img src='images/icon-zone-probability.gif' border='0' align='absmiddle' alt='{$strProbability}'>&nbsp;{$strProbability}</a>&nbsp;&nbsp;&nbsp;&nbsp;";
    echo "<a href='zone-invocation.php?affiliateid=" . $affiliateid . "&zoneid=" . $row_zones['zoneid'] . "'><img src='images/icon-generatecode.gif' border='0' align='absmiddle' alt='{$strInvocationcode}'>&nbsp;{$strInvocationcode}</a>&nbsp;&nbsp;&nbsp;&nbsp;";
    if (phpAds_isUser(phpAds_Admin) || phpAds_isAllowed(phpAds_DeleteZone)) {
        echo "<a href='zone-delete.php?affiliateid=" . $affiliateid . "&zoneid=" . $row_zones['zoneid'] . "&returnurl=affiliate-zones.php'" . phpAds_DelConfirm($strConfirmDeleteZone) . "><img src='images/icon-recycle.gif' border='0' align='absmiddle' alt='{$strDelete}'>&nbsp;{$strDelete}</a>&nbsp;&nbsp;&nbsp;&nbsp;";
    }
    echo "</td></tr>";
    $i++;
}
if (phpAds_dbNumRows($res_zones) > 0) {
    echo "<tr height='1'><td colspan='4' bgcolor='#888888'><img src='images/break.gif' height='1' width='100%'></td></tr>";
}
echo "</table>";
echo "<br><br>";
/*********************************************************/
/* Store preferences                                     */
/*********************************************************/
$Session['prefs']['affiliate-zones.php']['listorder'] = $listorder;
$Session['prefs']['affiliate-zones.php']['orderdirection'] = $orderdirection;
phpAds_SessionDataStore();
/*********************************************************/
/* HTML framework                                        */
/*********************************************************/
phpAds_PageFooter();
function phpAds_ToggleCampaignInZone($clientid, $zoneid)
{
    global $phpAds_config;
    if (isset($zoneid) && $zoneid != '') {
        $res = phpAds_dbQuery("\n\t\t\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\t" . $phpAds_config['tbl_zones'] . "\n\t\t\tWHERE\n\t\t\t\tzoneid = '{$zoneid}'\n\t\t\t") or phpAds_sqlDie();
        if (phpAds_dbNumRows($res)) {
            $zone = phpAds_dbFetchArray($res);
            if ($zone['what'] != '') {
                $what_array = explode(",", $zone['what']);
            } else {
                $what_array = array();
            }
            $available = false;
            $changed = false;
            for ($k = 0; $k < count($what_array); $k++) {
                if (substr($what_array[$k], 0, 9) == "clientid:" && substr($what_array[$k], 9) == $clientid) {
                    // Remove from array
                    unset($what_array[$k]);
                    $available = true;
                    $changed = true;
                }
            }
            if ($available == false) {
                // Add to array
                $what_array[] = 'clientid:' . $clientid;
                $changed = true;
            }
            if ($changed == true) {
                // Convert back to a string
                $zone['what'] = implode(",", $what_array);
                // Store string back into database
                $res = phpAds_dbQuery("\n\t\t\t\t\tUPDATE\n\t\t\t\t\t\t" . $phpAds_config['tbl_zones'] . "\n\t\t\t\t\tSET \n\t\t\t\t\t\twhat = '" . $zone['what'] . "'\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tzoneid = '{$zoneid}'\n\t\t\t\t\t") or phpAds_sqlDie();
                // Rebuild cache
                if (!defined('LIBVIEWCACHE_INCLUDED')) {
                    include phpAds_path . '/libraries/deliverycache/cache-' . $phpAds_config['delivery_caching'] . '.inc.php';
                }
                phpAds_cacheDelete('what=zone:' . $zoneid);
            }
        }
    }
    return false;
}
function phpAds_showZoneBanners($width, $height, $what, $zonetype, $delivery)
{
    global $phpAds_config, $showcampaigns, $hideinactive, $affiliateid, $zoneid;
    global $strName, $strID, $strUntitled, $strDescription, $phpAds_TextAlignRight, $phpAds_TextAlignLeft;
    global $strEdit, $strCheckAllNone, $strShowBanner;
    global $strNoBannersToLink, $strSaveChanges, $strSelectBannerToLink, $strInactiveBannersHidden;
    global $strShowParentCampaigns, $strHideParentCampaigns, $strHideInactiveBanners, $strShowAll;
    global $tabindex;
    if ($zonetype == phpAds_ZoneBanners) {
        // Determine selected banners
        $what_array = explode(",", $what);
        for ($k = 0; $k < count($what_array); $k++) {
            if (substr($what_array[$k], 0, 9) == "bannerid:") {
                $bannerid = substr($what_array[$k], 9);
                $bannerids[$bannerid] = true;
            }
        }
    } elseif ($zonetype == phpAds_ZoneCampaign) {
        // Determine selected campaigns
        $clientids = array();
        $what_array = explode(",", $what);
        for ($k = 0; $k < count($what_array); $k++) {
            if (substr($what_array[$k], 0, 9) == "clientid:") {
                $clientid = substr($what_array[$k], 9);
                $clientids[] = 'clientid = ' . $clientid;
            }
        }
        // Determine banners owned by selected campaigns
        if (count($clientids)) {
            $res = phpAds_dbQuery("\n\t\t\t\tSELECT\n\t\t\t\t\tbannerid\n\t\t\t\tFROM\n\t\t\t\t\t" . $phpAds_config['tbl_banners'] . "\n\t\t\t\tWHERE\n\t\t\t\t\t" . implode(' OR ', $clientids) . "\n\t\t\t");
            while ($row = phpAds_dbFetchArray($res)) {
                $bannerids[$row['bannerid']] = true;
            }
        } else {
            $bannerids = array();
        }
    } else {
        $bannerids = array();
    }
    // Fetch all campaigns
    $res = phpAds_dbQuery("\n\t\tSELECT\n\t\t\t*\n\t\tFROM\n\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\tWHERE\n\t\t\tparent > 0\n\t") or phpAds_sqlDie();
    while ($row = phpAds_dbFetchArray($res)) {
        $campaigns[$row['clientid']] = $row;
    }
    // Fetch all banners which can be linked
    $query = "\n\t\tSELECT\n\t\t\t*\n\t\tFROM\n\t\t\t" . $phpAds_config['tbl_banners'] . "\n\t\t";
    if ($delivery != phpAds_ZoneText) {
        if ($width != -1 && $height != -1) {
            $query .= "WHERE width = {$width} AND height = {$height} AND contenttype != 'txt'";
        } elseif ($width != -1) {
            $query .= "WHERE width = {$width} AND contenttype != 'txt'";
        } elseif ($height != -1) {
            $query .= "WHERE height = {$height} AND contenttype != 'txt'";
        } else {
            $query .= "WHERE contenttype != 'txt'";
        }
    } else {
        $query .= "WHERE contenttype = 'txt'";
    }
    $query .= "\n\t\tORDER BY\n\t\t\tbannerid";
    $res = phpAds_dbQuery($query);
    $compact = phpAds_dbNumRows($res) > $phpAds_config['gui_link_compact_limit'];
    while ($row = phpAds_dbFetchArray($res)) {
        $campaigns[$row['clientid']]['banners'][$row['bannerid']] = $row;
    }
    $inactivehidden = 0;
    if (!$compact) {
        echo "<form name='zonetypeselection' method='post' action='zone-include.php'>";
        echo "<input type='hidden' name='zoneid' value='" . $GLOBALS['zoneid'] . "'>";
        echo "<input type='hidden' name='affiliateid' value='" . $GLOBALS['affiliateid'] . "'>";
        echo "<input type='hidden' name='zonetype' value='" . phpAds_ZoneBanners . "'>";
        echo "<input type='hidden' name='action' value='set'>";
    } else {
        echo "<br>" . $strSelectBannerToLink . "<br><br>";
        echo "<table cellpadding='0' cellspacing='0' border='0'><tr>";
        echo "<form name='zonetypeselection' method='get' action='zone-include.php'>";
        echo "<input type='hidden' name='zoneid' value='" . $GLOBALS['zoneid'] . "'>";
        echo "<input type='hidden' name='affiliateid' value='" . $GLOBALS['affiliateid'] . "'>";
        echo "<input type='hidden' name='zonetype' value='" . phpAds_ZoneBanners . "'>";
        echo "<td><img src='images/icon-client.gif' align='absmiddle'>&nbsp;";
        echo "<select name='clientid' onChange='this.form.submit();' tabindex='" . $tabindex++ . "'>";
        if (!isset($GLOBALS['clientid']) || $GLOBALS['clientid'] == '') {
            echo "<option value='' selected></option>";
        }
        // Fetch all campaigns
        $res = phpAds_dbQuery("\n\t\t\tSELECT\n\t\t\t\t*\n\t\t\tFROM\n\t\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\t\tWHERE\n\t\t\t\tparent = 0\n\t\t") or phpAds_sqlDie();
        while ($row = phpAds_dbFetchArray($res)) {
            if (isset($GLOBALS['clientid']) && $GLOBALS['clientid'] == $row['clientid']) {
                echo "<option value='" . $row['clientid'] . "' selected>[id" . $row['clientid'] . "] " . $row['clientname'] . "</option>";
            } else {
                echo "<option value='" . $row['clientid'] . "'>[id" . $row['clientid'] . "] " . $row['clientname'] . "</option>";
            }
        }
        echo "</select>";
        echo "</td></form>";
        if (isset($GLOBALS['clientid']) && $GLOBALS['clientid'] != '') {
            echo "<form name='zonetypeselection' method='get' action='zone-include.php'>";
            echo "<input type='hidden' name='zoneid' value='" . $GLOBALS['zoneid'] . "'>";
            echo "<input type='hidden' name='affiliateid' value='" . $GLOBALS['affiliateid'] . "'>";
            echo "<input type='hidden' name='clientid' value='" . $GLOBALS['clientid'] . "'>";
            echo "<input type='hidden' name='zonetype' value='" . phpAds_ZoneBanners . "'>";
            echo "<td>&nbsp;&nbsp;<img src='images/caret-r.gif' align='absmiddle'>&nbsp;&nbsp;";
            echo "<img src='images/icon-campaign.gif' align='absmiddle'>&nbsp;";
            echo "<select name='campaignid' onChange='this.form.submit();' tabindex='" . $tabindex++ . "'>";
            if (!isset($GLOBALS['campaignid']) || $GLOBALS['campaignid'] == '') {
                echo "<option value='' selected></option>";
            }
            // Fetch all campaigns
            $res = phpAds_dbQuery("\n\t\t\t\tSELECT\n\t\t\t\t\t*\n\t\t\t\tFROM\n\t\t\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\t\t\tWHERE\n\t\t\t\t\tparent = " . $GLOBALS['clientid'] . "\n\t\t\t") or phpAds_sqlDie();
            while ($row = phpAds_dbFetchArray($res)) {
                if (isset($GLOBALS['campaignid']) && $GLOBALS['campaignid'] == $row['clientid']) {
                    echo "<option value='" . $row['clientid'] . "' selected>[id" . $row['clientid'] . "] " . $row['clientname'] . "</option>";
                } else {
                    echo "<option value='" . $row['clientid'] . "'>[id" . $row['clientid'] . "] " . $row['clientname'] . "</option>";
                }
            }
            echo "</select>";
            echo "</td></form>";
            if (isset($GLOBALS['campaignid']) && $GLOBALS['campaignid'] != '') {
                echo "<form name='zonetypeselection' method='get' action='zone-include.php'>";
                echo "<input type='hidden' name='zoneid' value='" . $GLOBALS['zoneid'] . "'>";
                echo "<input type='hidden' name='affiliateid' value='" . $GLOBALS['affiliateid'] . "'>";
                echo "<input type='hidden' name='clientid' value='" . $GLOBALS['clientid'] . "'>";
                echo "<input type='hidden' name='campaignid' value='" . $GLOBALS['campaignid'] . "'>";
                echo "<input type='hidden' name='zonetype' value='" . phpAds_ZoneBanners . "'>";
                echo "<input type='hidden' name='action' value='toggle'>";
                echo "<td>&nbsp;&nbsp;<img src='images/caret-r.gif' align='absmiddle'>&nbsp;&nbsp;";
                echo "<img src='images/icon-banner-stored.gif' align='absmiddle'>&nbsp;";
                echo "<select name='bannerid' tabindex='" . $tabindex++ . "'>";
                // Fetch all banners which can be linked
                $query = "\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tbannerid,\n\t\t\t\t\t\tclientid,\n\t\t\t\t\t\talt,\n\t\t\t\t\t\tdescription,\n\t\t\t\t\t\tactive,\n\t\t\t\t\t\tstoragetype\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . $phpAds_config['tbl_banners'] . "\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tclientid = " . $GLOBALS['campaignid'] . "\n\t\t\t\t";
                if ($delivery != phpAds_ZoneText) {
                    if ($width != -1 && $height != -1) {
                        $query .= "AND width = {$width} AND height = {$height}";
                    } elseif ($width != -1) {
                        $query .= "AND width = {$width}";
                    } elseif ($height != -1) {
                        $query .= "AND height = {$height}";
                    }
                } else {
                    $query .= "AND contenttype = 'txt'";
                }
                $query .= "\n\t\t\t\t\tORDER BY\n\t\t\t\t\t\tbannerid";
                $res = phpAds_dbQuery($query);
                while ($row = phpAds_dbFetchArray($res)) {
                    if (!isset($bannerids[$row['bannerid']]) || $bannerids[$row['bannerid']] != true) {
                        $name = $strUntitled;
                        if (isset($row['alt']) && $row['alt'] != '') {
                            $name = $row['alt'];
                        }
                        if (isset($row['description']) && $row['description'] != '') {
                            $name = $row['description'];
                        }
                        echo "<option value='" . $row['bannerid'] . "'>[id" . $row['bannerid'] . "] " . $name . "</option>";
                    }
                }
                echo "</select>";
                echo "&nbsp;<input type='image' src='images/" . $GLOBALS['phpAds_TextDirection'] . "/go_blue.gif' border='0' tabindex='" . $tabindex++ . "'>";
                echo "</td></form>";
            }
        }
        echo "</tr></table>";
        echo "<br><br>";
    }
    // Header
    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'>&nbsp;</td>";
    echo "</tr>";
    echo "<tr height='1'><td colspan='3' bgcolor='#888888'><img src='images/break.gif' height='1' width='100%'></td></tr>";
    $i = 0;
    $checkedall = true;
    if (!$compact && phpAds_dbNumRows($res) == 0) {
        echo "<tr bgcolor='#F6F6F6'><td colspan='3' height='25'>&nbsp;&nbsp;" . $strNoBannersToLink . "</td></tr>";
    } else {
        foreach (array_keys($campaigns) as $ckey) {
            $campaign = $campaigns[$ckey];
            if (isset($campaign['banners']) && is_array($campaign['banners']) && count($campaign['banners'])) {
                $banners = $campaign['banners'];
                $activebanners = 0;
                foreach (array_keys($banners) as $bkey) {
                    $banner = $banners[$bkey];
                    $linkedrow = isset($bannerids[$banner['bannerid']]) && $bannerids[$banner['bannerid']] == true;
                    if ($compact) {
                        $showrow = $linkedrow;
                    } else {
                        $showrow = $hideinactive == false || $hideinactive == true && ($banner['active'] == 't' && $campaign['active'] == 't' || $linkedrow);
                    }
                    if ($showrow) {
                        $activebanners++;
                    }
                }
                if ($showcampaigns && $activebanners) {
                    if ($i > 0) {
                        echo "<tr height='1'><td colspan='3' bgcolor='#888888'><img src='images/break-l.gif' height='1' width='100%'></td></tr>";
                    }
                    echo "<tr height='25' " . ($i % 2 == 0 ? "bgcolor='#F6F6F6'" : "") . ">";
                    // Begin row
                    echo "<td height='25'>";
                    echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    if (!$compact) {
                        echo "&nbsp;&nbsp;";
                    }
                    // Banner icon
                    if ($campaign['active'] == 't') {
                        echo "<img src='images/icon-campaign.gif' align='absmiddle'>&nbsp;";
                    } else {
                        echo "<img src='images/icon-campaign-d.gif' align='absmiddle'>&nbsp;";
                    }
                    // Name
                    if (phpAds_isUser(phpAds_Admin)) {
                        echo "<a href='campaign-edit.php?clientid=" . $campaign['parent'] . "&campaignid=" . $campaign['clientid'] . "'>";
                        echo phpAds_breakString($campaign['clientname'], '60') . "</a>";
                    } else {
                        echo phpAds_breakString($campaign['clientname'], '60');
                    }
                    echo "</td>";
                    // ID
                    echo "<td height='25'>" . $campaign['clientid'] . "</td>";
                    echo "<td>&nbsp;</td></tr>";
                }
                foreach (array_keys($banners) as $bkey) {
                    $banner = $banners[$bkey];
                    $linkedrow = isset($bannerids[$banner['bannerid']]) && $bannerids[$banner['bannerid']] == true;
                    if ($compact) {
                        $showrow = $linkedrow;
                    } else {
                        $showrow = $hideinactive == false || $hideinactive == true && ($banner['active'] == 't' && $campaign['active'] == 't' || $linkedrow);
                    }
                    if (!$compact && !$showrow) {
                        $inactivehidden++;
                    }
                    if ($showrow) {
                        $name = $strUntitled;
                        if (isset($banner['alt']) && $banner['alt'] != '') {
                            $name = $banner['alt'];
                        }
                        if (isset($banner['description']) && $banner['description'] != '') {
                            $name = $banner['description'];
                        }
                        $name = phpAds_breakString($name, '60');
                        if (!$showcampaigns) {
                            if ($i > 0) {
                                echo "<tr height='1'><td colspan='3' bgcolor='#888888'><img src='images/break-l.gif' height='1' width='100%'></td></tr>";
                            }
                        } else {
                            echo "<tr height='1'>";
                            echo "<td " . ($i % 2 == 0 ? "bgcolor='#F6F6F6'" : "") . "><img src='images/spacer.gif' width='1' height='1'></td>";
                            echo "<td colspan='3' bgcolor='#888888'><img src='images/break-el.gif' height='1' width='100%'></td>";
                            echo "</tr>";
                        }
                        echo "<tr height='25' " . ($i % 2 == 0 ? "bgcolor='#F6F6F6'" : "") . ">";
                        // Begin row
                        echo "<td height='25'>";
                        echo "&nbsp;&nbsp;";
                        // Show checkbox
                        if (!$compact) {
                            if (isset($bannerids[$banner['bannerid']]) && $bannerids[$banner['bannerid']] == true) {
                                echo "<input type='checkbox' name='bannerid[]' value='" . $banner['bannerid'] . "' checked onclick='reviewall();' tabindex='" . $tabindex++ . "'>";
                            } else {
                                echo "<input type='checkbox' name='bannerid[]' value='" . $banner['bannerid'] . "' onclick='reviewall();' tabindex='" . $tabindex++ . "'>";
                                $checkedall = false;
                            }
                        } else {
                            echo "<a href='zone-include.php?affiliateid=" . $GLOBALS['affiliateid'] . "&zoneid=" . $GLOBALS['zoneid'] . "&bannerid=" . $banner['bannerid'] . "&zonetype=" . phpAds_ZoneBanners . "&action=toggle'>";
                            echo "<img src='images/caret-l.gif' border='0' align='absmiddle'></a>";
                        }
                        // Space
                        echo "&nbsp;&nbsp;";
                        if ($showcampaigns) {
                            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                        }
                        // Banner icon
                        if ($campaign['active'] == 't' && $banner['active'] == 't') {
                            if ($banner['storagetype'] == 'html') {
                                echo "<img src='images/icon-banner-html.gif' align='absmiddle'>&nbsp;";
                            } elseif ($banner['storagetype'] == 'url') {
                                echo "<img src='images/icon-banner-url.gif' align='absmiddle'>&nbsp;";
                            } elseif ($banner['storagetype'] == 'txt') {
                                echo "<img src='images/icon-banner-text.gif' align='absmiddle'>&nbsp;";
                            } else {
                                echo "<img src='images/icon-banner-stored.gif' align='absmiddle'>&nbsp;";
                            }
                        } else {
                            if ($banner['storagetype'] == 'html') {
                                echo "<img src='images/icon-banner-html-d.gif' align='absmiddle'>&nbsp;";
                            } elseif ($banner['storagetype'] == 'url') {
                                echo "<img src='images/icon-banner-url-d.gif' align='absmiddle'>&nbsp;";
                            } elseif ($banner['storagetype'] == 'txt') {
                                echo "<img src='images/icon-banner-text-d.gif' align='absmiddle'>&nbsp;";
                            } else {
                                echo "<img src='images/icon-banner-stored-d.gif' align='absmiddle'>&nbsp;";
                            }
                        }
                        // Name
                        if (phpAds_isUser(phpAds_Admin)) {
                            echo "<a href='banner-edit.php?clientid=" . $campaign['parent'] . "&campaignid=" . $campaign['clientid'] . "&bannerid=" . $banner['bannerid'] . "'>";
                            echo $name . "</a></td>";
                        } else {
                            echo $name;
                        }
                        // ID
                        echo "<td height='25'>" . $banner['bannerid'] . "</td>";
                        // Show banner
                        if ($banner['contenttype'] == 'txt') {
                            $width = 300;
                            $height = 200;
                        } else {
                            $width = $banner['width'] + 64;
                            $height = $banner['bannertext'] ? $banner['height'] + 90 : $banner['height'] + 64;
                        }
                        echo "<td height='25' align='" . $phpAds_TextAlignRight . "'>";
                        echo "<a href='banner-htmlpreview.php?bannerid=" . $banner['bannerid'] . "' target='_new' ";
                        echo "onClick=\"return openWindow('banner-htmlpreview.php?bannerid=" . $banner['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>";
                        // End row
                        echo "</tr>";
                        if (!$showcampaigns) {
                            $i++;
                        }
                    }
                }
                if ($showcampaigns && $activebanners) {
                    $i++;
                }
            }
        }
    }
    if (!$compact) {
        echo "<tr height='1'><td colspan='3' bgcolor='#888888'><img src='images/break-l.gif' height='1' width='100%'></td></tr>";
        echo "<tr " . ($i % 2 == 0 ? "bgcolor='#F6F6F6'" : "") . "><td height='25'>";
        echo "&nbsp;&nbsp;<input type='checkbox' name='checkall' value=''" . ($checkedall == true ? ' checked' : '') . " onclick='toggleall();' tabindex='" . $tabindex++ . "'>";
        echo "&nbsp;&nbsp;<b>" . $strCheckAllNone . "</b>";
        echo "</td><td>&nbsp;</td><td>&nbsp;</td></tr>";
    }
    echo "<tr height='1'><td colspan='3' bgcolor='#888888'><img src='images/break.gif' height='1' width='100%'></td></tr>";
    echo "<tr><td height='25' align='" . $phpAds_TextAlignLeft . "' nowrap>";
    if (!$compact) {
        if ($hideinactive == true) {
            echo "&nbsp;&nbsp;<img src='images/icon-activate.gif' align='absmiddle' border='0'>";
            echo "&nbsp;<a href='zone-include.php?affiliateid=" . $affiliateid . "&zoneid=" . $zoneid . "&zonetype=" . phpAds_ZoneBanners . "&hideinactive=0'>" . $strShowAll . "</a>";
            echo "&nbsp;&nbsp;|&nbsp;&nbsp;" . $inactivehidden . " " . $strInactiveBannersHidden;
        } else {
            echo "&nbsp;&nbsp;<img src='images/icon-hideinactivate.gif' align='absmiddle' border='0'>";
            echo "&nbsp;<a href='zone-include.php?affiliateid=" . $affiliateid . "&zoneid=" . $zoneid . "&zonetype=" . phpAds_ZoneBanners . "&hideinactive=1'>" . $strHideInactiveBanners . "</a>";
        }
    }
    echo "</td><td colspan='2' align='" . $phpAds_TextAlignRight . "' nowrap>";
    if ($showcampaigns == true) {
        echo "&nbsp;&nbsp;<img src='images/icon-campaign-d.gif' align='absmiddle' border='0'>";
        echo "&nbsp;<a href='zone-include.php?affiliateid=" . $affiliateid . "&zoneid=" . $zoneid . "&zonetype=" . phpAds_ZoneBanners . "&showcampaigns=0'>" . $strHideParentCampaigns . "</a>";
    } else {
        echo "&nbsp;&nbsp;<img src='images/icon-campaign.gif' align='absmiddle' border='0'>";
        echo "&nbsp;<a href='zone-include.php?affiliateid=" . $affiliateid . "&zoneid=" . $zoneid . "&zonetype=" . phpAds_ZoneBanners . "&showcampaigns=1'>" . $strShowParentCampaigns . "</a>";
    }
    echo "&nbsp;&nbsp;</td></tr>";
    echo "</table>";
    echo "<br><br>";
    echo "<br><br>";
    if (!$compact) {
        echo "<input type='submit' name='submit' value='{$strSaveChanges}' tabindex='" . $tabindex++ . "'>";
        echo "</form>";
    }
}
function phpAds_SendMaintenanceReport($clientid, $first_unixtimestamp, $last_unixtimestamp, $update = true)
{
    global $phpAds_config, $phpAds_CharSet, $date_format, $strBanner, $strCampaign, $strViews, $strClicks, $strConversions, $strLinkedTo, $strMailSubject, $strMailHeader, $strMailBannerStats, $strMailFooter, $strMailReportPeriod, $strMailReportPeriodAll, $strLogErrorBanners, $strLogErrorClients, $strLogErrorViews, $strLogErrorClicks, $strLogErrorConversions, $strNoStatsForCampaign, $strNoViewLoggedInInterval, $strNoClickLoggedInInterval, $strNoCampaignLoggedInInterval, $strTotal, $strTotalThisPeriod;
    // Convert timestamps to SQL format
    $last_sqltimestamp = date("YmdHis", $last_unixtimestamp);
    $first_sqltimestamp = date("YmdHis", $first_unixtimestamp);
    // Get Client information
    $res_client = phpAds_dbQuery("SELECT" . " clientid" . ",clientname" . ",contact" . ",email" . ",language" . ",report" . ",reportinterval" . ",reportlastdate" . ",UNIX_TIMESTAMP(reportlastdate) AS reportlastdate_t" . " FROM " . $phpAds_config['tbl_clients'] . " WHERE clientid=" . $clientid);
    if (phpAds_dbNumRows($res_client) > 0) {
        $client = phpAds_dbFetchArray($res_client);
        // Load client language strings
        @(include phpAds_path . '/language/english/default.lang.php');
        if ($client['language'] != '') {
            $phpAds_config['language'] = $client['language'];
        }
        if ($phpAds_config['language'] != 'english' && file_exists(phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php')) {
            @(include phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php');
        }
        $active_campaigns = false;
        $log = "";
        // Fetch all campaigns belonging to client
        $res_campaigns = phpAds_dbQuery("SELECT" . " campaignid" . ",campaignname" . ",views" . ",clicks" . ",conversions" . ",expire" . ",UNIX_TIMESTAMP(expire) as expire_st" . ",activate" . ",UNIX_TIMESTAMP(activate) as activate_st" . ",active" . " FROM " . $phpAds_config['tbl_campaigns'] . " WHERE clientid=" . $client['clientid']) or die($strLogErrorClients);
        while ($campaign = phpAds_dbFetchArray($res_campaigns)) {
            // Fetch all banners belonging to campaign
            $res_banners = phpAds_dbQuery("SELECT" . " bannerid" . ",campaignid" . ",URL" . ",active" . ",description" . ",alt" . " FROM " . $phpAds_config['tbl_banners'] . " WHERE campaignid=" . $campaign['campaignid']) or die($strLogErrorBanners);
            $active_banners = false;
            $log .= "\n" . $strCampaign . "  " . strip_tags(phpAds_buildName($campaign['campaignid'], $campaign['campaignname'])) . "\n";
            $log .= "=======================================================\n\n";
            while ($row_banners = phpAds_dbFetchArray($res_banners)) {
                $adviews = phpAds_totalViews($row_banners["bannerid"]);
                $client["views_used"] = $adviews;
                $adclicks = phpAds_totalClicks($row_banners["bannerid"]);
                $campaign["clicks_used"] = $adclicks;
                $adconversions = phpAds_totalConversions($row_banners["bannerid"]);
                $campaign["conversions_used"] = $adconversions;
                if ($adviews > 0 || $adclicks > 0 || $adconversions > 0) {
                    $log .= $strBanner . "  " . strip_tags(phpAds_buildBannerName($row_banners['bannerid'], $row_banners['description'], $row_banners['alt'])) . "\n";
                    $log .= $strLinkedTo . ": " . $row_banners['URL'] . "\n";
                    $log .= "-------------------------------------------------------\n";
                    $active_banner_stats = false;
                    if ($adviews > 0) {
                        $log .= $strViews . " (" . $strTotal . "):    " . $adviews . "\n";
                        // Fetch all adviews belonging to banner belonging to client, grouped by day
                        $res_adviews = phpAds_dbQuery("SELECT" . " SUM(views) as qnt" . ",DATE_FORMAT(day, '{$date_format}') as t_stamp_f" . ",TO_DAYS(day) AS the_day" . " FROM " . $phpAds_config['tbl_adstats'] . " WHERE bannerid=" . $row_banners['bannerid'] . " AND views>0" . " AND UNIX_TIMESTAMP(day)>=" . $first_unixtimestamp . " AND UNIX_TIMESTAMP(day)<" . $last_unixtimestamp . " GROUP BY day" . " ORDER BY day DESC") or die($strLogErrorViews . " " . phpAds_dbError());
                        if (phpAds_dbNumRows($res_adviews)) {
                            $total = 0;
                            while ($row_adviews = phpAds_dbFetchArray($res_adviews)) {
                                $log .= "      " . $row_adviews['t_stamp_f'] . ":   " . $row_adviews['qnt'] . "\n";
                                $total += $row_adviews['qnt'];
                            }
                            $log .= $strTotalThisPeriod . ": " . $total . "\n";
                            $active_banner_stats = true;
                        } else {
                            $log .= "      " . $strNoViewLoggedInInterval . "\n";
                        }
                    }
                    if ($adclicks > 0) {
                        // Total adclicks
                        $log .= "\n" . $strClicks . " (" . $strTotal . "):   " . $adclicks . "\n";
                        // Fetch all adclicks belonging to banner belonging to client, grouped by day
                        $res_adclicks = phpAds_dbQuery("SELECT" . " SUM(clicks) as qnt" . ",DATE_FORMAT(day, '{$date_format}') as t_stamp_f" . ",TO_DAYS(day) AS the_day" . " FROM " . $phpAds_config['tbl_adstats'] . " WHERE bannerid = " . $row_banners['bannerid'] . " AND clicks>0" . " AND UNIX_TIMESTAMP(day)>=" . $first_unixtimestamp . " AND UNIX_TIMESTAMP(day)<" . $last_unixtimestamp . " GROUP BY day" . " ORDER BY day DESC") or die($strLogErrorClicks . " " . phpAds_dbError());
                        if (phpAds_dbNumRows($res_adclicks)) {
                            $total = 0;
                            while ($row_adclicks = phpAds_dbFetchArray($res_adclicks)) {
                                $log .= "      " . $row_adclicks['t_stamp_f'] . ":   " . $row_adclicks['qnt'] . "\n";
                                $total += $row_adclicks['qnt'];
                            }
                            $log .= $strTotalThisPeriod . ": " . $total . "\n";
                            $active_banner_stats = true;
                        } else {
                            $log .= "      " . $strNoClickLoggedInInterval . "\n";
                        }
                    }
                    if ($adconversions > 0) {
                        // Total adconversions
                        $log .= "\n" . $strConversions . " (" . $strTotal . "):   " . $adconversions . "\n";
                        // Fetch all adclicks belonging to banner belonging to client, grouped by day
                        $res_adconversions = phpAds_dbQuery("SELECT" . " SUM(conversions) as qnt" . ",DATE_FORMAT(day, '{$date_format}') as t_stamp_f" . ",TO_DAYS(day) AS the_day" . " FROM " . $phpAds_config['tbl_adstats'] . " WHERE bannerid = " . $row_banners['bannerid'] . " AND conversions>0" . " AND UNIX_TIMESTAMP(day)>=" . $first_unixtimestamp . " AND UNIX_TIMESTAMP(day)<" . $last_unixtimestamp . " GROUP BY day" . " ORDER BY day DESC") or die($strLogErrorConversions . " " . phpAds_dbError());
                        if (phpAds_dbNumRows($res_adconversions)) {
                            $total = 0;
                            while ($row_adconversions = phpAds_dbFetchArray($res_adconversions)) {
                                $log .= "      " . $row_adcconversions['t_stamp_f'] . ":   " . $row_adconversions['qnt'] . "\n";
                                $total += $row_adconversions['qnt'];
                            }
                            $log .= $strTotalThisPeriod . ": " . $total . "\n";
                            $active_banner_stats = true;
                        } else {
                            $log .= "      " . $strNoConversionLoggedInInterval . "\n";
                        }
                    }
                    $log .= "\n\n";
                    if ($active_banner_stats == true || $active_banner_stats == false && $campaign['active'] == 't') {
                        $active_banners = true;
                    }
                }
            }
            if ($active_banners == true) {
                $active_campaigns = true;
            } else {
                $log .= $strNoStatsForCampaign . "\n\n\n";
            }
        }
        // E-mail Stats to active clients
        if ($client["email"] != '' && $active_campaigns == true) {
            $Subject = $strMailSubject . ": " . $client["clientname"];
            $Body = "{$strMailHeader}\n";
            $Body .= "{$strMailBannerStats}\n";
            if ($first_unixtimestamp == 0) {
                $Body .= "{$strMailReportPeriodAll}\n\n";
            } else {
                $Body .= "{$strMailReportPeriod}\n\n";
            }
            $Body .= "{$log}\n";
            $Body .= "{$strMailFooter}";
            $Body = str_replace("{clientname}", $client['clientname'], $Body);
            $Body = str_replace("{contact}", $client['contact'], $Body);
            $Body = str_replace("{adminfullname}", $phpAds_config['admin_fullname'], $Body);
            $Body = str_replace("{startdate}", date(str_replace('%', '', $date_format), $first_unixtimestamp), $Body);
            $Body = str_replace("{enddate}", date(str_replace('%', '', $date_format), $last_unixtimestamp), $Body);
            if ($phpAds_config['userlog_email']) {
                phpAds_userlogAdd(phpAds_actionAdvertiserReportMailed, $client['clientid'], $Subject . "\n\n" . $Body);
            }
            if (phpAds_sendMail($client['email'], $client['contact'], $Subject, $Body)) {
                // Update last run
                if ($update == true) {
                    $res_update = phpAds_dbQuery("UPDATE " . $phpAds_config['tbl_clients'] . " SET reportlastdate=NOW() WHERE clientid=" . $client['clientid']);
                }
                return true;
            }
        }
    }
    return false;
}
function phpAds_deactivateMail($campaign)
{
    global $phpAds_config;
    global $strMailSubjectDeleted, $strMailHeader, $strMailClientDeactivated;
    global $strNoMoreClicks, $strNoMoreViews, $strBeforeActivate, $strAfterExpire;
    global $strBanner, $strMailNothingLeft, $strMailFooter, $strUntitled;
    $clientresult = phpAds_dbQuery("SELECT *" . " FROM " . $phpAds_config['tbl_clients'] . " WHERE clientid=" . $campaign['clientid']);
    if ($client = phpAds_dbFetchArray($clientresult)) {
        if ($client["email"] != '' && $client["reportdeactivate"] == 't') {
            // Load config from the database
            if (!defined('LIBDBCONFIG_INCLUDED')) {
                include phpAds_path . '/libraries/lib-dbconfig.inc.php';
                phpAds_LoadDbConfig();
            }
            // Load client language strings
            @(include phpAds_path . '/language/english/default.lang.php');
            if ($client['language'] != '') {
                $phpAds_config['language'] = $client['language'];
            }
            if ($phpAds_config['language'] != 'english' && file_exists(phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php')) {
                @(include phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php');
            }
            // Build email
            $Subject = $strMailSubjectDeleted . ": " . $campaign['campaignname'];
            $Body = $strMailHeader . "\n";
            $Body .= $strMailClientDeactivated;
            if ($campaign['clicks'] == 0) {
                $Body .= ", {$strNoMoreClicks}";
            }
            if ($campaign['views'] == 0) {
                $Body .= ", {$strNoMoreViews}";
            }
            if (time() < $campaign["activate_st"]) {
                $Body .= ", {$strBeforeActivate}";
            }
            if (time() > $campaign["expire_st"] && $campaign["expire_st"] != 0) {
                $Body .= ", {$strAfterExpire}";
            }
            $Body .= ".\n\n";
            $res_banners = phpAds_dbQuery("SELECT" . " bannerid" . ",url" . ",description" . ",alt" . " FROM " . $phpAds_config['tbl_banners'] . " WHERE campaignid=" . $campaign['campaignid']);
            if (phpAds_dbNumRows($res_banners) > 0) {
                $Body .= "-------------------------------------------------------\n";
                while ($row_banners = phpAds_dbFetchArray($res_banners)) {
                    $name = "[id" . $row_banners['bannerid'] . "] ";
                    if ($row_banners['description'] != "") {
                        $name .= $row_banners['description'];
                    } elseif ($row_banners['alt'] != "") {
                        $name .= $row_banners['alt'];
                    } else {
                        $name .= $strUntitled;
                    }
                    $Body .= $strBanner . "  " . $name . "\n";
                    $Body .= "linked to: " . $row_banners['url'] . "\n";
                    $Body .= "-------------------------------------------------------\n";
                }
            }
            $Body .= "\n";
            $Body .= "{$strMailNothingLeft}\n\n";
            $Body .= "{$strMailFooter}";
            $Body = str_replace("{clientname}", $client["clientname"], $Body);
            $Body = str_replace("{contact}", $client["contact"], $Body);
            $Body = str_replace("{adminfullname}", $phpAds_config['admin_fullname'], $Body);
            // Send email
            phpAds_sendMail($client['email'], $client['contact'], $Subject, $Body);
            if ($phpAds_config['userlog_email']) {
                phpAds_userlogAdd(phpAds_actionDeactivationMailed, $campaign['campaignid'], $Subject . "\n\n" . $Body);
            }
        }
    }
}
function phpAds_SqlUniqueName($name)
{
    global $phpAds_config;
    $extension = substr($name, strrpos($name, ".") + 1);
    $base = substr($name, 0, strrpos($name, "."));
    $res = phpAds_dbQuery("SELECT filename FROM " . $phpAds_config['tbl_images'] . " WHERE filename='" . $base . "." . $extension . "'");
    if (phpAds_dbNumRows($res) == 0) {
        return $base . "." . $extension;
    } else {
        if (eregi("^(.*)_([0-9]+)\$", $base, $matches)) {
            $base = $matches[1];
            $i = $matches[2];
        } else {
            $i = 1;
        }
        $found = false;
        while ($found == false) {
            $i++;
            $res = phpAds_dbQuery("SELECT filename FROM " . $phpAds_config['tbl_images'] . " WHERE filename='" . $base . "_" . $i . "." . $extension . "'");
            if (phpAds_dbNumRows($res) == 0) {
                $found = true;
            }
        }
        return $base . "_" . $i . "." . $extension;
    }
}
function phpAds_AutoTargetingCaclulateFactor($profile, &$debuglog)
{
    global $phpAds_config;
    $debuglog .= "\n";
    // Use standard routine if the profile is empty
    if (!phpAds_AutoTargetingProfileSum($profile)) {
        $debuglog .= "Supplied profile is null, using default algorithm\n";
        return -1;
    }
    $target_profile = array(0, 0, 0, 0, 0, 0, 0);
    $autotarget_campaigns = 0;
    // Fetch all targeted campaigns and all which need autotargeting
    $res = phpAds_dbQuery("SELECT campaignid" . ",views" . ",UNIX_TIMESTAMP(expire) AS expire" . ",target" . " FROM " . $phpAds_config['tbl_campaigns'] . " WHERE active" . " AND weight = 0" . " AND ((expire > NOW() AND views > 0) OR target > 0)");
    $debuglog .= "Targeted campaigns: " . phpAds_dbNumRows($res) . "\n";
    while ($row = phpAds_dbFetchArray($res)) {
        $debuglog .= "\nCAMPAIGN " . $row['campaignid'] . " \n";
        $debuglog .= "--------------------------------------------------\n";
        if ($row['expire']) {
            // Expire date set, get remaining days
            $days = ($row['expire'] - phpAds_LastMidnight) / (double) (60 * 60 * 24);
            $debuglog .= "Days remaining: {$days}\n";
            if ($days <= 0) {
                continue;
            }
            if ($row['views']) {
                // Bought views set, use standard autotargeting
                $daily_target = ceil($row['views'] / $days);
                $autotarget_campaigns++;
                $debuglog .= "Campaign type: Autotargeting\n";
                $debuglog .= "Remaining AdViews: " . $row['views'] . "\n";
                $debuglog .= "Daily target: " . $daily_target . "\n";
            } elseif ($row['target']) {
                // Use target field
                $daily_target = $row['target'];
                $debuglog .= "Campaign type: Expiring high-pri\n";
                $debuglog .= "Daily target: " . $daily_target . "\n";
            } else {
                // Skip campaign
                continue;
            }
        } else {
            // Expire date not set, target field is needed
            if (!$row['target']) {
                // Skip campaign
                continue;
            }
            $daily_target = $row['target'];
            $debuglog .= "Daily target: " . $daily_target . "\n";
            if ($row['views']) {
                $debuglog .= "Campaign type: AdView based high-pri\n";
                // Bought views set, get remaining days using the current target
                $days = ceil($row['views'] / $daily_target);
                $debuglog .= "Remaining AdViews: " . $row['views'] . "\n";
            } else {
                // Set target for the whole week
                $days = 7;
                $debuglog .= "Campaign type: Default high-pri\n";
            }
            $debuglog .= "Days remaining: " . $days . "\n";
        }
        // Add this campaign to the targets profile
        for ($i = 0; $i < $days && $i < 7; $i++) {
            $target_profile[$i] += $daily_target;
        }
    }
    $debuglog .= "\nAutotargeted campaigns: " . $autotarget_campaigns . "\n";
    $debuglog .= "--------------------------------------------------\n";
    if (!$autotarget_campaigns) {
        // No autotargeting is needed, we can use default autotargeting safely
        $debuglog .= "No autotargeting needed, using default algorithm\n";
        return -1;
    }
    // Get the daily target
    $daily_target = phpAds_AutoTargetingProfileSum($target_profile);
    // Set default routine as best match
    $best = array('factor' => array(-1), 'views' => phpAds_AutoTargetingActualViews($profile, $target_profile));
    // Try factors - don't know why, but on my setup $x <= 1 skips $x == 1...
    for ($x = 0; $x <= 1.01; $x += 0.05) {
        // Smooth profile using the current factor and get the view sum
        $smooth_profile = phpAds_AutoTargetingSmoothProfile($profile, $x);
        $views = phpAds_AutoTargetingProfileSum($smooth_profile);
        // Skip if the profile is empty
        if (!$views) {
            continue;
        }
        // Fill the whieighted profile
        $new_profile = array();
        for ($i = 0; $i < 7; $i++) {
            $new_profile[$i] = round($daily_target / $views * $smooth_profile[$i]);
        }
        // Get actual views that could be reached using this profile
        $act_views = phpAds_AutoTargetingActualViews($profile, $new_profile);
        if ($act_views > $best['views']) {
            // Best factor found til now
            $best['factor'] = array($x);
            $best['views'] = $act_views;
        } elseif ($act_views == $best['views']) {
            // Add x to the best factors found til now
            $best['factor'][] = $x;
        }
    }
    if (is_array($best['factor'])) {
        // Get average factor
        $factor = 0;
        while (list(, $v) = each($best['factor'])) {
            $factor += $v;
        }
        $best['factor'] = round($factor * 100 / count($best['factor'])) / 100;
    }
    $debuglog .= "\n";
    return $best['factor'];
}
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>";
    }
}
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
// Prevent full path disclosure
if (!defined('phpAds_path')) {
    die;
}
// Include required files
require phpAds_path . "/libraries/lib-autotargeting.inc.php";
// Set defaults
$report = '';
// Save views into targetstats table
phpAds_TargetStatsSaveViews();
// Get campaigns that need autotargeting
$res = phpAds_dbQuery("\n\tSELECT\n\t\tclientid,\n\t\tclientname,\n\t\tviews,\n\t\tUNIX_TIMESTAMP(expire) AS expire\n\tFROM\n\t\t" . $phpAds_config['tbl_clients'] . "\n\tWHERE\n\t\tparent > 0 AND\n\t\tactive AND\n\t\texpire > NOW() AND\n\t\tviews > 0 AND\n\t\tweight = 0\n\tORDER BY\n\t\tclientid\n\t");
if (phpAds_dbNumRows($res)) {
    // Autotargeting needed
    $report .= "==================================================\n";
    $report .= "AUTOTARGETING STARTED\n";
    $report .= "==================================================\n\n";
    $report .= "--------------------------------------------------\n";
    $report .= "Smoothing factor calculation ";
    // Prepare the average view profile
    $profile = phpAds_AutoTargetingPrepareProfile();
    // Calculate the factor to use on sunday or if it's disabled
    if (!date('w') || !isset($phpAds_config['autotarget_factor']) || $phpAds_config['autotarget_factor'] == -1) {
        $report .= "started\n";
        $report .= "--------------------------------------------------\n";
        $phpAds_config['autotarget_factor'] = phpAds_AutoTargetingCaclulateFactor($profile, $report);
        // Save factor into db
        phpAds_dbQuery("\n\t\t\tUPDATE\n\t\t\t\t" . $phpAds_config['tbl_config'] . "\n\t\t\tSET\n\t\t\t\tautotarget_factor = " . $phpAds_config['autotarget_factor'] . "\n\t\t\tWHERE\n\t\t\t\tconfigid = 0\n\t\t\t");
        echo "<a href='JavaScript:GoOpener(\"zone-edit.php?affiliateid=" . $row_zones['affiliateid'] . "&zoneid=" . $row_zones['zoneid'] . "\")'>" . $name . "</a>";
        echo "</td>";
        echo "<td height='25'>" . $row_zones['zoneid'] . "</td>";
        // Empty
        echo "<td>&nbsp;</td>";
        // Button 1
        echo "<td height='25'>";
        echo "<a href='JavaScript:GoOpener(\"zone-include.php?affiliateid=" . $row_zones['affiliateid'] . "&zoneid=" . $row_zones['zoneid'] . "\")'><img src='images/icon-zone-linked.gif' border='0' align='absmiddle' alt='{$strIncludedBanners}'>&nbsp;{$strIncludedBanners}</a>&nbsp;&nbsp;&nbsp;&nbsp;";
        echo "</td>";
        // Button 2
        echo "<td height='25'>";
        echo "<a href='JavaScript:GoOpener(\"zone-delete.php?affiliateid=" . $row_zones['affiliateid'] . "&zoneid=" . $row_zones['zoneid'] . "\", true)'" . phpAds_DelConfirm($strConfirmDeleteZone) . "><img src='images/icon-recycle.gif' border='0' align='absmiddle' alt='{$strDelete}'>&nbsp;{$strDelete}</a>&nbsp;&nbsp;&nbsp;&nbsp;";
        echo "</td></tr>";
        $i++;
    }
}
if (phpAds_dbNumRows($res_clients) > 0 || phpAds_dbNumRows($res_campaigns) > 0 || phpAds_dbNumRows($res_banners) > 0 || phpAds_dbNumRows($res_affiliates) > 0 || phpAds_dbNumRows($res_zones) > 0) {
    echo "<tr height='1'><td colspan='5' bgcolor='#888888'><img src='images/break.gif' height='1' width='100%'></td></tr>";
} else {
    echo $strNoMatchesFound;
}
?>
</table>

</td><td width='20'>&nbsp;</td></tr>
</table>

<br><br> 

</body>
</html>
        echo "<br><br>";
        // Show welcome message
        if (!empty($phpAds_client_welcome_msg)) {
            echo $phpAds_client_welcome_msg;
        } else {
            include 'templates/welcome-advertiser.html';
        }
        echo "<br><br>";
    }
    phpAds_ShowSections(array("1.1", "1.2"));
}
/*********************************************************/
/* Main code                                             */
/*********************************************************/
$idresult = phpAds_dbQuery("\n\tSELECT\n\t\tb.bannerid\n\tFROM\n\t\t" . $phpAds_config['tbl_banners'] . " AS b,\n\t\t" . $phpAds_config['tbl_clients'] . " AS c\n\tWHERE\n\t\tc.parent = {$clientid} AND\n\t\tc.clientid = b.clientid\n");
if (phpAds_dbNumRows($idresult) > 0) {
    $bannerids = array();
    while ($row = phpAds_dbFetchArray($idresult)) {
        $bannerids[] = $row['bannerid'];
    }
    $lib_history_where = count($bannerids) ? "bannerid IN (" . implode(', ', $bannerids) . ")" : '';
    $lib_history_params = array('clientid' => $clientid);
    $lib_history_hourlyurl = "stats-client-daily.php";
    include "lib-history.inc.php";
    /*********************************************************/
    /* Maintenance                                           */
    /*********************************************************/
    if (phpAds_isUser(phpAds_Admin)) {
        echo "<br><br><br>";
        echo "<table width='100%' border='0' align='center' cellspacing='0' cellpadding='0'>";
        echo "<tr><td height='25'><b>{$strMaintenance}</b></td></tr>";
function phpAds_Login()
{
    global $phpAds_config;
    global $strPasswordWrong, $strEnableCookies, $strEnterBoth;
    if (phpAds_SuppliedCredentials()) {
        // Trim spaces from input
        $username = trim($_POST['phpAds_username']);
        $password = trim($_POST['phpAds_password']);
        // Add slashes to input if needed
        if (!ini_get('magic_quotes_gpc')) {
            $username = addslashes($username);
            $password = addslashes($password);
        }
        // Convert plain text password to md5 digest
        $md5digest = md5($password);
        // Exit if not both username and password are given
        if ($md5digest == '' || $md5digest == md5('') || $username == '') {
            $_COOKIE['sessionID'] = phpAds_SessionStart();
            phpAds_LoginScreen($strEnterBoth, $_COOKIE['sessionID']);
        }
        // Exit if cookies are disabled
        if ($_COOKIE['sessionID'] != $_POST['phpAds_cookiecheck']) {
            $_COOKIE['sessionID'] = phpAds_SessionStart();
            phpAds_LoginScreen($strEnableCookies, $_COOKIE['sessionID']);
        }
        if (phpAds_isAdmin($username, $md5digest)) {
            // User is Administrator
            return array("usertype" => phpAds_Admin, "loggedin" => "t", "username" => $username);
        } else {
            // Check client table
            $res = phpAds_dbQuery("\n\t\t\t\tSELECT\n\t\t\t\t\tclientid,\n\t\t\t\t\tpermissions,\n\t\t\t\t\tlanguage\n\t\t\t\tFROM\n\t\t\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\t\t\tWHERE\n\t\t\t\t\tclientusername = '******'\n\t\t\t\t\tAND clientpassword = '******'\n\t\t\t") or phpAds_sqlDie();
            if (phpAds_dbNumRows($res) > 0) {
                // User found with correct password
                $row = phpAds_dbFetchArray($res);
                return array("usertype" => phpAds_Client, "loggedin" => "t", "username" => $username, "userid" => $row['clientid'], "permissions" => $row['permissions'], "language" => $row['language']);
            } else {
                $res = phpAds_dbQuery("\n\t\t\t\t\tSELECT\n\t\t\t\t\t\taffiliateid,\n\t\t\t\t\t\tpermissions,\n\t\t\t\t\t\tlanguage\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . $phpAds_config['tbl_affiliates'] . "\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tusername = '******'\n\t\t\t\t\t\tAND password = '******'\n\t\t\t\t\t");
                if ($res && phpAds_dbNumRows($res) > 0) {
                    // User found with correct password
                    $row = phpAds_dbFetchArray($res);
                    return array("usertype" => phpAds_Affiliate, "loggedin" => "t", "username" => $username, "userid" => $row['affiliateid'], "permissions" => $row['permissions'], "language" => $row['language']);
                } else {
                    // Password is not correct or user is not known
                    // Set the session ID now, some server do not support setting a cookie during a redirect
                    $_COOKIE['sessionID'] = phpAds_SessionStart();
                    phpAds_LoginScreen($strPasswordWrong, $_COOKIE['sessionID']);
                }
            }
        }
    } else {
        // User has not supplied credentials yet
        if (defined('phpAds_installing')) {
            // We are trying to install, grant access...
            return array("usertype" => phpAds_Admin, "loggedin" => "t", "username" => 'admin');
        }
        // Set the session ID now, some server do not support setting a cookie during a redirect
        $_COOKIE['sessionID'] = phpAds_SessionStart();
        phpAds_LoginScreen('', $_COOKIE['sessionID']);
    }
}
echo "\t\t\t\t\t\t<b>" . $GLOBALS['strConversionWindow'] . "</b>\n";
echo "\t\t\t\t\t</td>\n";
echo "\t\t\t\t</tr>\n";
echo "\t\t\t\t<tr height='1'>\n";
echo "\t\t\t\t\t<td colspan='4' bgcolor='#888888'><img src='images/break.gif' height='1' width='100%'></td>\n";
echo "\t\t\t\t</tr>\n";
$i = 0;
$checkedall = true;
if (isset($campaignid) && $campaignid > 0) {
    $res = phpAds_dbQuery("SELECT *" . " FROM " . $phpAds_config['tbl_campaigns_trackers'] . " WHERE campaignid=" . $campaignid) or phpAds_sqlDie();
    while ($row = phpAds_dbFetchArray($res)) {
        $campaign_tracker_row[$row['trackerid']] = $row;
    }
}
$res = phpAds_dbQuery("SELECT *" . " FROM " . $phpAds_config['tbl_trackers'] . " WHERE clientid=" . $clientid . phpAds_getTrackerListOrder($listorder, $orderdirection)) or phpAds_sqlDie();
if (phpAds_dbNumRows($res) == 0) {
    echo "\t\t\t\t<tr bgcolor='#F6F6F6'>\n";
    echo "\t\t\t\t\t<td colspan='4' height='25'>&nbsp;&nbsp;" . $strNoTrackersToLink . "</td>\n";
    echo "\t\t\t\t</tr>\n";
} else {
    echo "\t\t\t\t<form name='availabletrackers' method='post' action='campaign-trackers.php'>\n";
    echo "\t\t\t\t<input type='hidden' name='campaignid' value='" . $GLOBALS['campaignid'] . "'>\n";
    echo "\t\t\t\t<input type='hidden' name='clientid' value='" . $GLOBALS['clientid'] . "'>\n";
    echo "\t\t\t\t<input type='hidden' name='action' value='set'>\n";
    while ($row = phpAds_dbFetchArray($res)) {
        $trackers[$row['trackerid']] = $row;
    }
    for (reset($trackers); $tkey = key($trackers); next($trackers)) {
        $tracker = $trackers[$tkey];
        if ($i > 0) {
            echo "\t\t\t\t<tr height='1'>\n";
function phpAds_SendMaintenanceReport($clientid, $first_unixtimestamp, $last_unixtimestamp, $update = true)
{
    global $phpAds_config;
    global $date_format;
    global $strMailSubject, $strMailHeader, $strMailBannerStats, $strMailFooter, $strMailReportPeriod;
    global $strLogErrorClients, $strLogErrorBanners, $strLogErrorViews, $strNoStatsForCampaign;
    global $strLogErrorClicks, $strNoClickLoggedInInterval, $strNoViewLoggedInInterval;
    global $strTotal, $strTotalThisPeriod;
    global $strCampaign, $strBanner, $strLinkedTo, $strViews, $strClicks, $strMailReportPeriodAll;
    global $phpAds_CharSet;
    // Convert timestamps to SQL format
    $last_sqltimestamp = date("YmdHis", $last_unixtimestamp);
    $first_sqltimestamp = date("YmdHis", $first_unixtimestamp);
    // Get Client information
    $res_client = phpAds_dbQuery("\n\t\tSELECT\n\t\t\tclientid,\n\t\t\tclientname,\n\t\t\tcontact,\n\t\t\temail,\n\t\t\tlanguage,\n\t\t\treport,\n\t\t\treportinterval,\n\t\t\treportlastdate,\n\t\t\tUNIX_TIMESTAMP(reportlastdate) AS reportlastdate_t\n\t\tFROM\n\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\tWHERE\n\t\t\tclientid='" . $clientid . "'\n\t\t");
    if (phpAds_dbNumRows($res_client) > 0) {
        $client = phpAds_dbFetchArray($res_client);
        // Load client language strings
        @(include phpAds_path . '/language/english/default.lang.php');
        if ($client['language'] != '') {
            $phpAds_config['language'] = $client['language'];
        }
        if ($phpAds_config['language'] != 'english' && file_exists(phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php')) {
            @(include phpAds_path . '/language/' . $phpAds_config['language'] . '/default.lang.php');
        }
        $active_campaigns = false;
        $log = "";
        // Fetch all campaings belonging to client
        $res_campaigns = phpAds_dbQuery("\n\t\t\tSELECT\n\t\t\t\tclientid,\n\t\t\t\tclientname,\n\t\t\t\tviews,\n\t\t\t\tclicks,\n\t\t\t\texpire,\n\t\t\t\tUNIX_TIMESTAMP(expire) as expire_st,\n\t\t\t\tactivate,\n\t\t\t\tUNIX_TIMESTAMP(activate) as activate_st,\n\t\t\t\tactive\n\t\t\tFROM\n\t\t\t\t" . $phpAds_config['tbl_clients'] . "\n\t\t\tWHERE\n\t\t\t\tparent = " . $client['clientid'] . "\n\t\t\n\t\t") or die($strLogErrorClients);
        while ($campaign = phpAds_dbFetchArray($res_campaigns)) {
            $current_log = '';
            // Fetch all banners belonging to campaign
            $res_banners = phpAds_dbQuery("\n\t\t\t\tSELECT\n\t\t\t\t\tbannerid,\n\t\t\t\t\tclientid,\n\t\t\t\t\turl,\n\t\t\t\t\tactive,\n\t\t\t\t\tdescription,\n\t\t\t\t\talt\n\t\t\t\tFROM\n\t\t\t\t\t" . $phpAds_config['tbl_banners'] . "\n\t\t\t\tWHERE\n\t\t\t\t\tclientid = " . $campaign['clientid'] . "\n\t\t\t\t") or die($strLogErrorBanners);
            $active_banners = false;
            $current_log .= "\n" . $strCampaign . "  " . phpAds_buildClientName($campaign['clientid'], $campaign['clientname'], false) . "\n";
            $current_log .= "=======================================================\n\n";
            while ($row_banners = phpAds_dbFetchArray($res_banners)) {
                $adviews = phpAds_totalViews($row_banners["bannerid"]);
                $client["views_used"] = $adviews;
                $adclicks = phpAds_totalClicks($row_banners["bannerid"]);
                $campaign["clicks_used"] = $adclicks;
                $current_log .= $strBanner . "  " . phpAds_buildBannerName($row_banners['bannerid'], $row_banners['description'], $row_banners['alt'], 0, false) . "\n";
                $current_log .= $strLinkedTo . ": " . $row_banners['url'] . "\n";
                $current_log .= "-------------------------------------------------------\n";
                $active_banner_stats = false;
                if ($adviews > 0) {
                    $current_log .= $strViews . " (" . $strTotal . "):    " . $adviews . "\n";
                    // Fetch all adviews belonging to banner belonging to client, grouped by day
                    if ($phpAds_config['compact_stats']) {
                        $res_adviews = phpAds_dbQuery("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tSUM(views) as qnt,\n\t\t\t\t\t\t\t\tDATE_FORMAT(day, '{$date_format}') as t_stamp_f,\n\t\t\t\t\t\t\t\tTO_DAYS(day) AS the_day\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t" . $phpAds_config['tbl_adstats'] . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tbannerid = " . $row_banners['bannerid'] . " AND\n\t\t\t\t\t\t\t\tviews > 0 AND\n\t\t\t\t\t\t\t\tUNIX_TIMESTAMP(day) >= {$first_unixtimestamp} AND\n\t\t\t\t\t\t\t\tUNIX_TIMESTAMP(day) < {$last_unixtimestamp}\n\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\tday\n\t\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t\tday DESC\n\t\t\t\t\t\t\t") or die("{$strLogErrorViews} " . phpAds_dbError());
                    } else {
                        $res_adviews = phpAds_dbQuery("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\t*,\n\t\t\t\t\t\t\t\tcount(*) as qnt,\n\t\t\t\t\t\t\t\tDATE_FORMAT(t_stamp, '{$date_format}') as t_stamp_f,\n\t\t\t\t\t\t\t\tTO_DAYS(t_stamp) AS the_day\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t" . $phpAds_config['tbl_adviews'] . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tbannerid = " . $row_banners['bannerid'] . " AND\n\t\t\t\t\t\t\t\tt_stamp >= {$first_sqltimestamp} AND\n\t\t\t\t\t\t\t\tt_stamp < {$last_sqltimestamp}\n\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\tthe_day\n\t\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t\tthe_day DESC\n\t\t\t\t\t\t\t") or die("{$strLogErrorViews} " . phpAds_dbError());
                    }
                    if (phpAds_dbNumRows($res_adviews)) {
                        $total = 0;
                        while ($row_adviews = phpAds_dbFetchArray($res_adviews)) {
                            $current_log .= "      " . $row_adviews['t_stamp_f'] . ":   " . $row_adviews['qnt'] . "\n";
                            $total += $row_adviews['qnt'];
                        }
                        $current_log .= $strTotalThisPeriod . ": " . $total . "\n";
                        $active_banner_stats = true;
                    } else {
                        $current_log .= "      " . $strNoViewLoggedInInterval . "\n";
                    }
                }
                if ($adclicks > 0) {
                    // Total adclicks
                    $current_log .= "\n" . $strClicks . " (" . $strTotal . "):   " . $adclicks . "\n";
                    // Fetch all adclicks belonging to banner belonging to client, grouped by day
                    if ($phpAds_config['compact_stats']) {
                        $res_adclicks = phpAds_dbQuery("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tSUM(clicks) as qnt,\n\t\t\t\t\t\t\t\tDATE_FORMAT(day, '{$date_format}') as t_stamp_f,\n\t\t\t\t\t\t\t\tTO_DAYS(day) AS the_day\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t" . $phpAds_config['tbl_adstats'] . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tbannerid = " . $row_banners['bannerid'] . " AND\n\t\t\t\t\t\t\t\tclicks > 0 AND\n\t\t\t\t\t\t\t\tUNIX_TIMESTAMP(day) >= {$first_unixtimestamp} AND\n\t\t\t\t\t\t\t\tUNIX_TIMESTAMP(day) < {$last_unixtimestamp}\n\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\tday\n\t\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t\tday DESC\n\t\t\t\t\t\t\t") or die("{$strLogErrorClicks} " . phpAds_dbError());
                    } else {
                        $res_adclicks = phpAds_dbQuery("\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tcount(*) as qnt,\n\t\t\t\t\t\t\t\tDATE_FORMAT(t_stamp, '{$date_format}') as t_stamp_f,\n\t\t\t\t\t\t\t\tTO_DAYS(t_stamp) AS the_day\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t" . $phpAds_config['tbl_adclicks'] . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tbannerid = " . $row_banners['bannerid'] . " AND\n\t\t\t\t\t\t\t\tt_stamp >= {$first_sqltimestamp} AND\n\t\t\t\t\t\t\t\tt_stamp < {$last_sqltimestamp}\n\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\tthe_day\n\t\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t\tthe_day DESC\n\t\t\t\t\t\t\t") or die("{$strLogErrorClicks} " . phpAds_dbError());
                    }
                    if (phpAds_dbNumRows($res_adclicks)) {
                        $total = 0;
                        while ($row_adclicks = phpAds_dbFetchArray($res_adclicks)) {
                            $current_log .= "      " . $row_adclicks['t_stamp_f'] . ":   " . $row_adclicks['qnt'] . "\n";
                            $total += $row_adclicks['qnt'];
                        }
                        $current_log .= $strTotalThisPeriod . ": " . $total . "\n";
                        $active_banner_stats = true;
                    } else {
                        $current_log .= "      " . $strNoClickLoggedInInterval . "\n";
                    }
                }
                if ($adclicks == 0 && $adviews == 0) {
                    $current_log .= "      " . $strNoStatsForCampaign . "\n";
                }
                $current_log .= "\n\n";
                if ($campaign['active'] == 't' || $active_banner_stats == true) {
                    $active_banners = true;
                }
            }
            if ($active_banners == true) {
                $active_campaigns = true;
                $log .= $current_log;
            }
        }
        // E-mail Stats to active clients
        if ($client["email"] != '' && $active_campaigns == true) {
            $Subject = $strMailSubject . ": " . $client["clientname"];
            $Body = "{$strMailHeader}\n";
            $Body .= "{$strMailBannerStats}\n";
            if ($first_unixtimestamp == 0) {
                $Body .= "{$strMailReportPeriodAll}\n\n";
            } else {
                $Body .= "{$strMailReportPeriod}\n\n";
            }
            $Body .= "{$log}\n";
            $Body .= "{$strMailFooter}";
            $Body = str_replace("{clientname}", $client['clientname'], $Body);
            $Body = str_replace("{contact}", $client['contact'], $Body);
            $Body = str_replace("{adminfullname}", $phpAds_config['admin_fullname'], $Body);
            $Body = str_replace("{startdate}", date(str_replace('%', '', $date_format), $first_unixtimestamp), $Body);
            $Body = str_replace("{enddate}", date(str_replace('%', '', $date_format), $last_unixtimestamp), $Body);
            if ($phpAds_config['userlog_email']) {
                phpAds_userlogAdd(phpAds_actionAdvertiserReportMailed, $client['clientid'], $Subject . "\n\n" . $Body);
            }
            phpAds_sendMail($client['email'], $client['contact'], $Subject, $Body);
            // Update last run
            if ($update == true) {
                $res_update = phpAds_dbQuery("UPDATE " . $phpAds_config['tbl_clients'] . " SET reportlastdate=NOW() WHERE clientid=" . $client['clientid']);
            }
            return true;
        }
    }
    return false;
}