<?php

include_once("components/geoip/open_geoip.php");

$reporting = true;

require_once "common.inc.php";
$start = getmicrotime();

if ($validUserRequired && !$session->logged_in) {
    echo "<script>window.location.href='index.php';</script>";
    $template->LoginForm();
    exit();
}

if (empty($conf)) {
    echo "No profile selected";
    exit();
}

@set_time_limit(86400);

// Pull in variables that may have been passed in with the URL.
$print = @$_REQUEST["print"];

$notrail = @$_REQUEST["notrail"];
$formemail = @$_REQUEST["formemail"];
$submit = @$_REQUEST["submitbut"];
$showfields = @$_REQUEST["showfields"];
$filter = @$_REQUEST["filter"];
$item = @$_REQUEST["item"];
$item2 = @$_REQUEST["item2"];
$drilldown = @$_REQUEST["drilldown"];
$labels = @urldecode($_REQUEST["labels"]);
$status = @$_REQUEST["status"];
$agent = @$_REQUEST["agent"];
$csvpreview = @$_REQUEST["csvpreview"];
$csvexport = @$_REQUEST["csvexport"];
$country = @$_REQUEST["country"];
$search = @$_REQUEST["search"];
$searchmode = @$_REQUEST["searchmode"];
$statstable_only = @$_REQUEST["statstable_only"];
$xml = @$_REQUEST["xml"];
$old = @$_REQUEST["old"]; // this is just to be able to compare the speed to the old labels
$outputmode = @$_REQUEST["outputmode"];
unset($_REQUEST["outputmode"]); # Put it in the variable and never look back ;)

if (@$_SESSION["trafficsource"]) {
    $trafficsource = $_SESSION["trafficsource"];
    $applytrafficsource = true;
} else {
    $applytrafficsource = false;
}

if (isset($print)) {
    $noheader = 1;
}
$roadto = @$_REQUEST["roadto"];


/*
................................................
.......... Main program starts here ............
................................................
*/

if (defined($labels)) {
    $clabel = $labels;
    $labels = constant($labels);
} else {
    if (isset($get_constant[$labels])) {
        $clabel = $get_constant[$labels];
    } else {
        $clabel = _UNKNOWN;
    }
}

if ((!$ss && _LOGAHOLIC_EDITION == 0) && !empty($outputmode)) {
    if (strpos($clabel, "MINI") === false) {
        die('This feature is only available in Logaholic Pro');
    }
}

switch ($outputmode) {
    case "csv":
        // this creates the Report area only, no headers or interface needed
        $profile = new SiteProfile($conf);

        if (class_exists('Report')) {
            if (isset($clabel) && isset($reports[$clabel])) {
                # there is a class file for this report, let's use it
                $r = new $reports[$clabel]["ClassName"]();
                $r->DisplayCSV();
            }
        }
        break;

    case "json":
        $profile = new SiteProfile($conf);
        if (class_exists('Report')) {
            if (isset($clabel) && isset($reports[$clabel])) {
                # there is a class file for this report, let's use it
                $r = new $reports[$clabel]["ClassName"]();
                $r->DisplayJSON();
            }
        }
        break;

    case "xml":
        // this creates the Report area only, no headers or interface needed
        $profile = new SiteProfile($conf);

        if (class_exists('Report')) {
            if (isset($clabel) && isset($reports[$clabel])) {
                # there is a class file for this report, let's use it
                $r = new $reports[$clabel]["ClassName"]();
                $r->DisplayXML();
            }
        }
        break;

    case "html":

        if (isset($clabel) && isset($reports[$clabel])) {
            # there is a class file for this report, let's use it
            $r = new $reports[$clabel]["ClassName"]();
            $r->DisplaySimpleTable();
        }
        break;

    case "iframe":
        echo $template->HTMLheadTag();
        echo $template->BodyStart();
        if (isset($clabel) && isset($reports[$clabel])) {
            echo "<style>
				.report-header { padding:6px; font-size: 11px; color: #99ccff; border-top: 1px solid #50A5D3; text-shadow: 0 1px 0 #0E4067; background: url('../images/gradient_bg_blue.png') repeat-x scroll left top #1970B4; }				
				.graph_tooltip { background: url('images/rgba0x0x0x095.png') repeat scroll 0 0 transparent; border: 1px solid #CCCCCC; color: #FFFFFF; display: none; padding: 5px; position: absolute; right: 5px; top: 50px; width: 250px; z-index: 30; }
				.graph_title{ color: #999999; font-size: 12px; margin: 10px 0 0; padding: 0; text-align: center; width: 100%; }
				.graphcontainer{ margin:5px; }
			</style>";
            # there is a class file for this report, let's use it
            $r = new $reports[$clabel]["ClassName"]();
            $r->displayReportButtons = false;

            # this if statement handles special case for inpage analytics
            if (isset($_GET['subreport'])) {
                if (strpos($_GET['subreport'], 'Keywords') !== false) {
                    $r->columnDefinitions[0] = array("Label" => _KEYWORDS);
                    $r->columnDefinitions[1] = array("Label" => _VISITS);
                    $r->setupColumnDefinitions();
                    $data = $r->getKeywords($r->page);
                    $r->Table($data);
                    echo "</div></body></html>";
                    break;
                }
                if (strpos($_GET['subreport'], 'Referrers') !== false) {
                    $r->columnDefinitions[0] = array("Label" => _REFERRERS);
                    $r->columnDefinitions[1] = array("Label" => _VISITS);
                    $r->setupColumnDefinitions();
                    $data = $r->getReferrers($r->page);
                    $r->Table($data);
                    echo "</div></body></html>";
                    break;
                }
                if (strpos($_GET['subreport'], 'Clicks') !== false) {
                    $r->columnDefinitions[0] = array("Label" => _KEYWORDS);
                    $r->columnDefinitions[1] = array("Label" => _CLICKS);
                    $r->setupColumnDefinitions();
                    $data = $r->getNextPages($r->page);
                    $r->Table($data);
                    echo "</div></body></html>";
                    break;
                }
            }

            echo "<div class='dialog-content'>";
            $r->displayReportButtons = false;
            $r->DisplayReport();
            echo "</div>";
        }
        echo "</div></body></html>";
        break;

    case "print":

        echo $template->HTMLheadTag();
        echo $template->BodyStart();

        $icon = "<img src=images/icons/logaholiclogo.gif width=16 height=16 align=left style='margin-top:5px;'>";
        echo "<div id='print'>";
        echo "<h1 class='h1-title'>$icon Web Analytics Report for {$profile->confdomain}</h1>";

        if (isset($clabel) && isset($reports[$clabel])) {
            # there is a class file for this report, let's use it
            $r = new $reports[$clabel]["ClassName"]();
            $r->displayReportLabel = true;
            $r->displayReportButtons = false;
            echo "<div class='report'>";
            $r->DisplayReport();
            echo "</div>";
        }
        echo "</div><a class=nodec target=_blank style='font:10px;padding:15px;' href='https:///www.logaholic.com/'>&copy; Logaholic Web Analytics</a></body></html>";
        break;

    case "email":

        //echo $template->HTMLheadTag();
        //echo $template->BodyStart();

        if (isset($clabel) && isset($reports[$clabel])) {
            # there is a class file for this report, let's use it
            $r = new $reports[$clabel]["ClassName"]();
            ob_start();
            $r->DisplaySimpleTable();
            $contents = ob_get_clean();
        }

        include_once "includes/emailalerts.php";
        $email = new EmailAlerts();
        # set up the message
        $mail_contents = "<html><head>";
        $mail_contents .= $email->ApplyReportStyles();
        $mail_contents .= "</head><body>";
        $mail_contents .= $_REQUEST['message'] . "<br />\n";
        # create all the selected reports
        $mail_contents .= $contents;
        $mail_contents .= "<br /><br />Powered by <a href=\"http://www.logaholic.com/\">Logaholic Web Analytics</a><br /><br /></body></html>";
        # now send it

        if ($email->HtmlEmail($_REQUEST['email'], $_REQUEST['fromemail'], $_REQUEST['subject'], $mail_contents)) {
            # also send a copy to the sender (seperate cus it looks like outlook messes it up)
            $email->HtmlEmail($_REQUEST['fromemail'], $_REQUEST['fromemail'], $_REQUEST['subject'], $mail_contents);
            $msg = str_replace("%X%", $_REQUEST['email'], _SEND_EMAIL_WITH_SUBJECT);
            echo json_encode(array("Status" => "Success", "Message" => $msg . ": " . $_REQUEST['subject']));
            // .": ". $_REQUEST['subject']
        } else {
            echo json_encode(array("Status" => "Error", "Message" => implode(", ", $feedback)));
        }
        //echo "</div></body></html>";
        break;

    case "sparkline":

        // echo $template->HTMLheadTag();
        // echo $template->BodyStart();
        if (isset($clabel) && isset($reports[$clabel])) {
            # there is a class file for this report, let's use it
            $r = new $reports[$clabel]["ClassName"]();
            $r->DisplaySparkline();
        }
        break;
    // echo "</body></html>";

    case "heatbullets":
        if (isset($clabel) && isset($reports[$clabel])) {
            # there is a class file for this report, let's use it
            $r = new $reports[$clabel]["ClassName"]();
            $r->DisplayHeatBullets();
        }
        break;

    default:
        // this creates the Report area only, no headers or interface needed
        if (!isset($profile)) {
            $profile = new SiteProfile($conf);
        }

        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(
                $_SERVER['HTTP_X_REQUESTED_WITH']
            ) == 'xmlhttprequest') {
            //this is an ajax request
        } else {
            $vp = $string = str_replace(
                array("\n", "\r", "%0a", "%0d"),
                '',
                $_SERVER['QUERY_STRING']
            ); // prevent header injection
            header("Location: index.php?" . $vp);
            exit();
        }
        //header('Content-Type: text/html; charset=UTF-8');

        $cachename = md5($_SERVER['QUERY_STRING']);

        ob_start();
        if (isset($clabel) && isset($reports[$clabel])) {
            # there is a class file for this report, let's use it
            $r = new $reports[$clabel]["ClassName"]();

            # Directly check if the report is available or not
            if ($r->available === false) {
                $r->displayReportButtons = false;
                $r->ReportHeader();
                echoNotice(_REPORT_TEMP_UNAVAILABLE, "margin:10px; text-align:center;");
            } else {
                $r->ReportOptionsPanel();
                if ($r->ValidateReportEdition()) {
                    $r->DisplayReport();
                } else {
                    if (!CheckForSubscriptionsUsage() && $ss == false) {
                        $r->DisplayPromo($r);
                    } else {
                        if (CheckForSubscriptionsUsage()) {
                            $r->DisplaySubscriptionPromo($r);
                        } else {
                            echoNotice(
                                "The report is not available in this <a target=_blank href='https:///www.logaholic.com/'>Logaholic</a> installation.",
                                "margin:5px;"
                            );
                        }
                    }
                }
            }
        }
        //$contents = ob_get_clean();
        //echo $contents;
        echo "<div class='report_took' style='display: none;'>Report took:" . (getmicrotime(
                ) - $start) . " seconds</div>";
        print_gzipped_output();
        break;
}
if ($debug) {
    echoDebug("Report took:" . (getmicrotime() - $start) . " seconds");
    echoDebug("<a onclick=\"document.body.innerHTML=''; return false;\" href=\"#\">leeg</a>");
}