<?php
/**
 * @desc this program will add or edit a logaholic profiles
 * for more information please read:
 * http://www.logaholic.com/manual/LogaholicManual/APIDocumentationForServiceProviderEditions
 */

class LogaholicDBProfile
{

    var $site;
    var $username;
    var $logfilelocation = "";
    var $trackermode = "0";
    var $splitlogs = "1";
    var $splitfilter = "";
    var $profile_name;
    var $equivdomains = "";
    var $urlparamfilter = "";
    var $urlparamfiltermode = "";
    var $activated = "0";
    var $recursive = "1";
    var $new_profilename;

    function __construct($ProfileName = null)
    {
        global $config, $running_from_command_line, $db, $databasedriver, $DatabaseName, $cm, $logaUtm;

        $running_from_command_line = true;
        include_once($config['path'] . "/common.inc.php");

        if (is_file($config['path'] . "/languages/english.php")) {
            include_once($config['path'] . "/languages/english.php");
        }

        if (LOGAHOLIC_BASE_EDITION == "cPanel Edition") {
            $this->activated = 1;
        }

        if (!isset($ProfileName)) {
            $this->CheckVars();
        }
    }

    function CheckVars()
    {
        global $action;

        $help = "Required variables:<br>\n";
        $help .= " - site (the (sub)domain to be added or deleted)<br>\n";
        $help .= " - profile_name (use this to overrule the automatic generation of a profilename from the site name)<br>\n";
        $help .= " - username (the username of the account that owns this site, only required when adding profiles)<br>\n";
        $help .= "Optional variables:<br>\n";
        $help .= " - logfilelocation (if empty, Data collection method will be set to javascript basedtracking)<br>\n";
        $help .= " - splitlogs (indicates if logfilelocation is a directory or a file)<br>\n";
        $help .= " - splitfilter (keyword or regex that files in logfilelocation dir must match)<br>\n";
        $help .= " - equivdomains (any aliases of the main domain name that point to the same site)<br>\n";
        $help .= " - urlparamfilter (comma delimited list of url params that need to be filtered)<br>\n";
        $help .= " - urlparamfiltermode (Include or Exclude params from urlparamfilter, default Exclude)<br>\n";
        $help .= " - activated (1 = active or 0 = not active, default 0)<br>\n";
        $help .= " - patternfilter ('false' turns off behaviour based bot detection (log files only), default 'true')<br>\n";


        $standalone_actions = array("listprofiles", "profilescount", "getupdatestatus");
        if (in_array($action, $standalone_actions)) {
            return; # no need for checks these guys can handle themselves.
        }


        if (!empty($_GET['site'])) {
            $this->site = $_GET['site'];
        } else {
            if (empty($_GET['profile_name'])) {
                Output($help, true);
            }
        }
        if (!empty($_GET['username'])) {
            $this->username = $_GET['username'];
        } else {
            if ($action == "addprofile") {
                Output($help, true);
            } else {
                $this->username = "";
            }
        }

        if (!empty($_GET['new_profilename'])) {
            $this->new_profilename = $_GET['new_profilename'];
        }

        if (!empty($_GET['logfilelocation'])) {
            $this->logfilelocation = $_GET['logfilelocation'];
        } else {
            $this->trackermode = "1";
        }
        if (isset($_GET['splitlogs']) && ($_GET["splitlogs"] == 1 || $_GET["splitlogs"] == 0)) {
            $this->splitlogs = $_GET['splitlogs'];
        }
        if (!empty($_GET['splitfilter'])) {
            $this->splitfilter = $_GET['splitfilter'];
        }
        if (!empty($_GET['profile_name'])) {
            $this->profile_name = $_GET['profile_name'];
        }
        if (!empty($_GET['equivdomains'])) {
            $this->equivdomains = $_GET['equivdomains'];
        }
        if (!empty($_GET['urlparamfilter'])) {
            $this->urlparamfilter = $_GET['urlparamfilter'];
        }
        if (!empty($_GET['urlparamfiltermode'])) {
            $this->urlparamfiltermode = $_GET['urlparamfiltermode'];
        }
        if (!empty($_GET['activated']) && ($_GET["activated"] == 1 || $_GET["activated"] == 0)) {
            $this->activated = $_GET['activated'];
        }

        if (!empty($_GET['recursive']) && ($_GET["recursive"] == 1 || $_GET["recursive"] == 0)) {
            $this->recursive = $_GET['recursive'];
        }

        if (!empty($_GET['patternfilter'])) {
            $this->patternfilter = $_GET['patternfilter'];
        } else {
            $this->patternfilter = "true";
        }

        if (substr($this->site, 0, 4) == "http") {
            Output("The site variable should not contain http prefix! <br><br>\n\n" . $help, true);
        }

        if (empty($this->profile_name)) {
            $this->profile_name = $this->siteToProfilename($this->site);
        }

        return;
    }

    private function siteToProfilename($site)
    {
        // return preg_replace('/[^a-z0-9]/', '', $site);
        return $site;
    }

    function LogaholicDBProfile($ProfileName = null)
    {
        __construct($ProfileName);
    }

    function GetUpdateStatus()
    {
        global $db;
        $r = $db->Execute("SELECT profilename, update_status FROM " . TBL_PROFILES . " WHERE update_status !='ready'");
        $data = array();
        $i = 0;
        while ($row = $r->fetchRow()) {
            $data[$i]['profilename'] = $row['profilename'];
            $data[$i]['update_status'] = $row['update_status'];
            $i++;
        }
        return $data;
    }

    function ResetUpdateFlag()
    {
        setProfileData($this->profile_name, "{$this->profile_name}.update_running", "no");
    }

    function ListProfiles()
    {
        global $db;
        $p = $db->Execute("SELECT profilename from " . TBL_PROFILES);
        $u = $db->Execute(
            "SELECT username , `profiles` from  " . TBL_USERS . " where `profiles` != '' and isAdmin != 1"
        );

        $profiles = array();
        $data = array();
        while ($row = $p->fetchRow()) {
            $profiles[$row['profilename']] = '';
        }

        while ($row = $u->fetchRow()) {
            $ups = explode(',', $row['profiles']);
            foreach ($ups as $up) {
                if (isset($profiles[$up])) {
                    $profiles[$up] = $row['username'];
                }
            }
        }

        $i = 0;
        foreach ($profiles as $k => $v) {
            $data[$i]['profilename'] = $k;
            $data[$i]['username'] = $v;
            $i++;
        }

        return $data;
    }

    function RenameProfile()
    {
        global $db, $databasedriver;
        if (empty($this->new_profilename)) {
            Output("Missing parameter new_profilename!", true);
        }

        if ($this->profile_name != "") {
            $p = $this->profile_name;
        } else {
            $p = $this->siteToProfilename($this->site);
        }

        # set up the profile object
        $profile = new SiteProfile($p);

        if ($profile->profileid == null) {
            Output("Profile does not exists!", true);
        }

        $profile->profilename = $this->new_profilename;
        $profile->dieonsqlerror = false;
        $profile->Save();
        if (empty($profile->lastsqlerror)) {
            Output("Renamed {$p} to {$this->new_profilename}");
        } else {
            Output($profile->lastsqlerror, true);
        }
    }

    function EditProfile()
    {
        global $db, $databasedriver;
        if ($this->profile_name != "") {
            $p = $this->profile_name;
        } else {
            $p = $this->siteToProfilename($this->site);
        }

        # set up the profile object
        $profile = new SiteProfile($p);

        if ($profile->profileid == null) {
            Output("Profile does not exists!", true);
        }

        foreach ($_GET as $key => $val) {
            switch ($key) {
                case "api_password";
                case "action";
                case "username";
                case "site";
                    break;
                default:
                    $profile->{$key} = $val;
            }
        }
        $profile->Save();
        Output("Edited profile {$this->site}");
    }

    function CountProfiles()
    {
        global $db;
        $q = "SELECT count(*) as total FROM " . TBL_PROFILES;
        $res = $db->Execute($q);
        $row = $res->fetchRow();
        return $row["total"];
    }

    function AddProfile()
    {
        global $db, $databasedriver;

        # set up the new profile
        $profile = new SiteProfile();
        if ($this->profile_name != "") {
            $profile->profilename = $this->profile_name;
        } else {
            $profile->profilename = $this->siteToProfilename($this->site);
        }
        if ($profile->profilename == "") {
            Output("Invalid profilename: $profile->profilename\n", true);
        }
        if ($this->profileExists($profile->profilename) == true) {
            $this->AddProfiletoUser($profile->profilename);
            Output("Profile '$profile->profilename' already exists\n", true);
        }

        $profile->confdomain = $this->site;
        $profile->equivdomains = $this->equivdomains;
        $profile->urlparamfilter = $this->urlparamfilter;
        $profile->activated = $this->activated;

        if (!empty($this->urlparamfiltermode)) {
            $profile->urlparamfiltermode = $this->urlparamfiltermode;
        }

        if ($this->trackermode == 1) {
            $profile->trackermode = 1;
            $profile->logfilefullpath = "";
            $profile->splitlogs = 0;
            $profile->visitoridentmethod = 3;
            $profile->recursive = $this->recursive;
        } else {
            $profile->logfilefullpath = $this->logfilelocation;
            $profile->splitlogs = $this->splitlogs;
            $profile->splitfilter = $this->splitfilter;
            $profile->recursive = $this->recursive;
            $profile->trackermode = 0;
            $profile->patternfilter = $this->patternfilter;
        }

        if (!empty($this->username)) {
            # now add the new profile to the profile list in the user table
            $this->AddProfiletoUser($profile->profilename);
        }

        $profile->logtime = true;

        $save_time = time();
        $profile->Save();
        $save_time = time() - $save_time;

        $create_tables_time = time();
        createDataTable($profile);
        $create_tables_time = time() - $create_tables_time;

        // $timers = "S: [T : {$save_time}, ". implode(",", $profile->logtimes) ."] | C: {$create_tables_time}";
        $timers = "S: [T : {$save_time} | C: {$create_tables_time}";


        Output("{$timers} | Created profile $profile->profilename for $this->site \n");
    }

    function profileExists($name)
    {
        global $db;

        $q = $db->Execute("select profileid from " . TBL_PROFILES . " where profilename=" . $db->Quote($name));
        if ($q->NumRows() > 0) {
            return true;
        } else {
            return false;
        }
    }

    function AddProfiletoUser($profile_name)
    {
        # first, get the list of profiles for this user
        $pl = getProfileList($this->username);
        if ($pl === false) {
            return false;
        }
        if ($pl != "") {
            $pl = explode(",", $pl);
            if (!in_array($profile_name, $pl)) {
                # add it
                $pl[] = $profile_name;
            }
            saveProfileList($this->username, implode(",", $pl));
        } else {
            $pl = $profile_name;
            saveProfileList($this->username, $pl);
        }
    }

    function DeleteProfile()
    {
        global $db;
        if ($this->profile_name != "") {
            $p = $this->profile_name;
        } else {
            $p = $this->siteToProfilename($this->site);
        }
        //dump($p);
        $profile = new SiteProfile($p);

        if ($profile->profileid == "") {
            # not found, still remove the profile from the users profile lists
            DeleteProfileFromUsers($p);
            return "Success: Deleted previously? Profile not found";
            //return;
        }

        # first, delete the profile from the profiles table
        $db->Execute("Delete from " . TBL_PROFILES . " where profileid = " . $profile->profileid) or Output(
            "An error occurred: " . $db->ErrorMsg(),
            true
        );

        # next, delete profile data from the globalsettings table
        deleteProfileData($profile->profilename);

        # now, delete the profile tables in the db
        deleteDataTable($profile);

        # now delete the remaining files from the data directory
        DeleteProfileFiles($profile);

        # finally, remove the profile from the users profile lists
        DeleteProfileFromUsers($profile->profilename);

        return "Success: Deleted profile for {$profile->profilename}";
    }

    function GetProfileInfo()
    {
        $profile = new Siteprofile($this->profile_name);
        $profile_dump = array();
        foreach ($profile as $k => $v) {
            $profile_dump[$k] = $v;
        }
        Output($profile_dump);
    }

    function getProfileDBSize($profile_name)
    {
        global $db, $DatabaseName;
        # first, get the tablename for this profiles
        $profile = new SiteProfile($profile_name);
        $query = "SELECT sum( data_length + index_length ) \"bytes\" ";
        $query .= "FROM information_schema.TABLES where table_schema=" . $db->Quote(
                $DatabaseName
            ) . " and (table_name=" . $db->Quote($profile->tablename) . " or table_name like " . $db->Quote(
                "{$profile->tablename}\_%"
            ) . ")";
        //error reporting
        error_reporting(0);
        $q = $db->Execute($query) or Output($db->ErrorMsg(), true);
        error_reporting(E_ALL);
        $data = $q->FetchRow();
        return $data[0];
    }

    function includeBackup()
    {
        global $db;

        $q = $db->Execute(
            "select Value from " . TBL_GLOBAL_SETTINGS . " where Profile=" . $db->Quote(
                $this->profile_name
            ) . " and Name = " . $db->Quote($this->profile_name . ".includebackup")
        );
        if ($data = $q->FetchRow()) {
            if ($data['Value'] == 1) {
                Output("true");
                return true;
            } else {
                Output("false", true);
                return false;
            }
        }
        Output("false", true);
        return false;
    }
}