<?php

$reports["_LOG_INSPECTOR"] = array(
    "ClassName" => "LogInspector",
    "Category" => "_PROBLEMS",
    "icon" => "images/icons/32x32/utilities-log_viewer.png",
    "Options" => "daterangeField,profileselector,columnSelector,limit",
    "Filename" => "log_inspector",
    "Distribution" => "Premium",
    "Order" => 7,
    "ReportVersion" => 1.0,
    "MinimumVersion" => 4.2,
    "EmailAlerts" => false,
    "Update" => false,
    "canAggregate" => false
);

class LogInspector extends Report
{
    function Settings()
    {
        $this->remove_outputmodes = array("xml");
        $this->datafiles = false;
        $this->allowDateFormat = false;
        $this->columnDefinitions[] = array("Label" => _DATE);
        $this->columnDefinitions[] = array("Label" => _IP_NUMBER);
        $this->columnDefinitions[] = array("Label" => "VID", "hide_column" => true, "dataType" => "String");
        $this->columnDefinitions[] = array("Label" => _URL);
        $this->columnDefinitions[] = array("Label" => _STATUS);
        $this->columnDefinitions[] = array("Label" => _BYTES, "hide_column" => true);
        $this->columnDefinitions[] = array("Label" => _REFERRER);
        $this->columnDefinitions[] = array("Label" => _CRAWLER, "hide_column" => true);
        $this->columnDefinitions[] = array("Label" => _COUNTRY);
        $this->columnDefinitions[] = array(
            "Label" => "detected name / version/ os / mobile/ device",
            "hide_column" => true
        );
        $this->columnDefinitions[] = array("Label" => _USER_AGENT);
        $this->displayTotalRow = false;

        if (!empty($this->options)) {
            # this creates our search conditions array
            foreach ($this->options as $option => $val) {
                if (substr($option, 0, 5) == 'field') {
                    $condition_options['field'][] = $val;
                } elseif (substr($option, 0, 9) == 'condition') {
                    $condition_options['condition'][] = $val;
                } elseif (substr($option, 0, 6) == 'cvalue') {
                    $condition_options['cvalue'][] = $val;
                }
            }
            if (!empty($condition_options)) {
                $this->conditions = $condition_options;
            }

            # this creates a string of conditions to show to the user
            if (!empty($condition_options['condition'])) {
                for ($c = 0; $c <= (count($condition_options['condition']) - 1); $c++) {
                    $condition_options['cvalue'][$c] = urldecode($condition_options['cvalue'][$c]);
                    if (strlen($condition_options['cvalue'][$c]) >= 50) {
                        $cvalue_val = substr($condition_options['cvalue'][$c], 0, 23) . "..." . substr(
                                $condition_options['cvalue'][$c],
                                -23
                            );
                    } else {
                        $cvalue_val = $condition_options['cvalue'][$c];
                    }
                    if ($c != 0) {
                        $this->addlabel .= !empty($this->andor) ? " {$this->andor} " : " AND ";
                    }
                    $this->addlabel .= isset($condition_options['field'][$c]) . " " . isset($condition_options['condition'][$c]) . " " . isset($cvalue_val);
                }
            }
        }
    }

    function DisplayCustomForm()
    {
        ?>
        <style>td::first-line:hover {
                color: #ff0000;
                font-variant: small-caps;
            }</style><?php

        $this->options = $_REQUEST;

        $condition_options = [];
        foreach ($this->options as $option => $val) {
            if (substr($option, 0, 5) == 'field') {
                $condition_options['field'][] = $val;
            } elseif (substr($option, 0, 9) == 'condition') {
                $condition_options['condition'][] = $val;
            } elseif (substr($option, 0, 6) == 'cvalue') {
                $condition_options['cvalue'][] = $val;
            }
        }


        echo "<div class='form-group' style='max-width: 540px;'>";
        echo "<span style=\"margin-top:8px;\"><b>" . _SEARCH . ":</b></span>";

        if (isset($condition_options['condition']) && count($condition_options['condition']) > 1) {
            echo "<div class='andor_selector'>";
            echo "<span style='float: left; margin-right: 20px;'>Mode: </span>";
            if (empty($this->andor) || $this->andor == "AND") {
                echo "<label style='float: left;'>AND</label><input type='radio' class='noTextInput' style='width: 25px; float: left;' name='andor' value='AND' checked />";
            } else {
                echo "<label style='float: left;'>AND</label><input type='radio' class='noTextInput' style='width: 25px; float: left;' name='andor' value='AND' />";
            }
            if (!empty($this->andor) && $this->andor == "OR") {
                echo "<label style='float: left;'>OR</label><input type='radio' class='noTextInput' style='width: 25px; float: left;' name='andor' value='OR' checked />";
            } else {
                echo "<label style='float: left;'>OR</label><input type='radio' class='noTextInput' style='width: 25px; float: left;' name='andor' value='OR' />";
            }
            echo "</div>";
            echo "<div class='clear'></div>";
        }

        echo "<div class='condition_descriptor' style='clear:both;'>(" . _FIELD . ", " . _CONDITION . ", " . _VALUE . ")</div>";

        $form_id = md5(time()) . rand(1, 500);
        echo "<table id='{$form_id}' class='conditions table'>";
        if (count($condition_options) == 0) {
            $fieldselect = LoadFieldSelectFull();
            $fieldselect = SelectField($fieldselect, 'field1');

            echo "<tr class='conditions_row' style='margin:5px 0;'>";
            echo "<td><select src='field' class='form-control' id='field1' name='field1'>" . $fieldselect . "</select></td>";
            echo "<td><select src='condition' class='form-control' id='condition1' name='condition1'>";
            echo "	<option value=\"" . isset($this->condition1) . "\" selected>" . isset($this->condition1);
            echo "	<option value='is'>" . _SELECT_IS . "</option>";
            echo "	<option value='contains'>" . _CONTAINS . "</option>";
            echo "	<option value='nocontain'>" . _NOT_CONTAINS . "</option>";
            echo "	<option value='start'>" . _STARTS_WITH . "</option>";
            echo "	<option value='end'>" . _ENDS_WITH . "</option>";
            echo "	<option value='isnot'>" . _SELECT_IS_NOT . "</option>";
            echo "</select></td>";
            echo "<td><input class='form-control qbuilderhelp' src='cvalue' rel='1' name='cvalue1' id='cvalue1' value='" . isset($this->cvalue1) . "' autocomplete='off'></td>";
            echo "<td><button type='button' class='plus_btn noOption btn btn-default'> &plus; </button></td>
						<td><button type='button' class='min_btn noOption btn btn-default' disabled='disabled'> &minus; </button></td>";
            echo "</tr>";
        } else {
            for ($c = 0; $c < count($condition_options['condition']); $c++) {
                $fieldselect = LoadFieldSelectFull();
                $fieldselect = SelectField($fieldselect, $condition_options['field'][$c]);

                echo "<tr class='conditions_row' style='margin:5px 0;'>";
                echo "<td><select src='field' class='form-control' id='field" . ($c + 1) . "' name='field" . ($c + 1) . "'>" . $fieldselect . "</select></td>";
                echo "<td><select src='condition' class='form-control' id='condition" . ($c + 1) . "' name='condition" . ($c + 1) . "'>";
                echo "	<option value=\"" . isset($condition_options['condition'][$c]) . "\" selected>" . isset($condition_options['condition'][$c]);
                echo "	<option value='is'>" . _SELECT_IS . "</option>";
                echo "	<option value='contains'>" . _CONTAINS . "</option>";
                echo "	<option value='nocontain'>" . _NOT_CONTAINS . "</option>";
                echo "	<option value='start'>" . _STARTS_WITH . "</option>";
                echo "	<option value='end'>" . _ENDS_WITH . "</option>";
                echo "	<option value='isnot'>" . _SELECT_IS_NOT . "</option>";
                echo "</select></td>";
                echo "<td><input src='cvalue' class='form-control qbuilderhelp' rel='" . ($c + 1) . "' name='cvalue" . ($c + 1) . "' id='cvalue" . ($c + 1) . "' value='" . isset($condition_options['cvalue'][$c]) . "' autocomplete='off'></td>";
                echo "<td><button type='button'class='plus_btn noOption btn btn-default'> &plus; </button></td>
								<td><button type='button' class='min_btn noOption btn btn-default'> &minus; </button></td>";
                echo "</tr>";
            }
        }
        echo "</table>";
        echo "</div>";

        echo "<script type='text/javascript'>
		$(document).ready(function(){
			plusMinusForm('{$form_id}', 'field', 'condition', 'cvalue');

			conf_name = '{$this->profile->profilename}';
			from_date = {$this->from};
			to_date = {$this->to};
  			$('.conditions').on('click keyup','.qbuilderhelp', function(event) {
  				QBuilderHelpForms($(this).val(), event, $(this).val() + '@' + 'cvalue' + $(this).attr('rel') + '@' + $('#field' + $(this).attr('rel')).val(), 'forminput');
  			});
		});

		</script>";


        echo "<br/>";
    }

    function DefineQuery()
    {
        global $db;

        $sqlstring = $this->makeSQLstring();
        if (!empty($sqlstring)) {
            $sqlstring = " AND $sqlstring";
        }

        # this first query creates a kind of log file 'table' that we can search more conveniently

        $log_q = "SELECT 
			FROM_UNIXTIME(a.timestamp, '%d-%b-%Y %H:%i:%s'),
			v.ipnumber AS ipnumber, 
			v.id as visitorid, 
			concat(u.url, up.params) as url, 
			a.status,
			a.bytes, 
			concat(r.referrer,rp.params),
			a.crawl as crawl,
			a.country as country,
			concat(b.name,' ',b.version,' / ',b.os_version,' / ',b.is_mobile,' / ',b.device),
			b.useragent AS useragent 			 
			FROM {$this->profile->tablename_merge} as a, {$this->profile->tablename_visitorids} AS v, {$this->profile->tablename_urls} AS u, {$this->profile->tablename_urlparams} AS up, {$this->profile->tablename_referrers} AS r, {$this->profile->tablename_refparams} AS rp, {$this->profile->tablename_useragents} AS b 
			WHERE a.timestamp BETWEEN $this->from AND $this->to 
			AND (a.visitorid = v.id AND a.url = u.id AND a.params = up.id AND a.referrer = r.id AND a.refparams = rp.id AND a.useragentid = b.id) 
			$sqlstring
			ORDER BY a.timestamp";

        $query = $log_q;

        $query .= "  limit $this->limit";
        //echoNotice($query);
        return $query;
    }

    function makeSQLstring()
    {
        global $db;
        if (!empty($this->visitorid) && isset($this->cvalue1) == "") {
            $this->cvalue1 = $this->visitorid;
            $this->condition1 = "is";
            $this->field1 = "visitorid";
        } else {
            if (!empty($this->ip) && (isset($this->cvalue1) && empty($this->cvalue1))) {
                $this->cvalue1 = $this->ip;
                $this->condition1 = "is";
                $this->field1 = "ipnumber";
            }
        }
        $sqlstring = "";
        if (isset($this->cvalue1) && $this->cvalue1 != "") {
            $i = 1;
            $andor = $andor ?? $this->andor;
            while ($i < 25) {
                $cvalue = "";
                $cvalue = $cvalue ?? $this->{'cvalue' . $i};
                if ($cvalue != "") {
                    $field = $field ?? $this->{'field' . $i};
                    if ($field == "") {
                        echoWarning(_UNKNOWN . " type: " . $cvalue . "<br>" . _PLEASE_SELECT_FIELD);
                        return false;
                    }

                    $condition = $condition ?? $this->{'condition' . $i};
                    if ($field == "keywords") {
                        //$cvalue=urlencode($cvalue);
                    } else {
                        // var_dump($cvalue);
                        $cvalue = urldecode($cvalue);
                    }
                    if ($field == "refparams" || $field == "params") {
                        $cvalue = str_replace(" ", "+", $cvalue);
                    }

                    //make sql string
                    if ($condition == "contains") {
                        $op = "$field LIKE " . $db->Quote("%{$cvalue}%");
                    } elseif ($condition == "nocontain") {
                        $op = "$field NOT LIKE " . $db->Quote("%{$cvalue}%");
                    } elseif ($condition == "start") {
                        $op = "$field LIKE " . $db->Quote("{$cvalue}%");
                    } elseif ($condition == "end") {
                        $op = "$field LIKE " . $db->Quote("%{$cvalue}");
                    } elseif ($condition == "is") {
                        $iid = $this->GetMatchingItemID($field, $cvalue);
                        if ($field == "ipnumber" || $field == "useragent" || $iid === false) {
                            $op = "$field =" . $db->Quote("$cvalue");
                        } else {
                            $op = "$field =" . $db->Quote($this->GetMatchingItemID($field, $cvalue));
                        }
                    } else {
                        if ($condition == "isnot") {
                            $iid = $this->GetMatchingItemID($field, $cvalue);
                            if ($field == "ipnumber" || $field == "useragent" || $iid === false) {
                                $op = "$field !=" . $db->Quote("$cvalue");
                            } else {
                                $op = "$field !=" . $db->Quote($this->GetMatchingItemID($field, $cvalue));
                            }
                        }
                    }

                    if ($i == 1) {
                        $sqlstring = " {$op}";
                    } else {
                        $sqlstring .= " {$andor} {$op}";
                    }
                    //echoWarning($sqlstring);
                }
                $i++;
            }
            $filter = 1;
        }

        //we need to rewrite the sqlstring to the new style tables
        $joincond = "";
        $addtables = "";
        if ($sqlstring) {
            if (strpos("  " . $sqlstring, " url ") != false) {
                $sqlstring = str_replace("url =", "a.url=", $sqlstring);
                $sqlstring = str_replace("url !=", "a.url!=", $sqlstring);
                $sqlstring = str_replace("url LIKE", "u.url LIKE", $sqlstring);
                $sqlstring = str_replace("url NOT LIKE", "u.url NOT LIKE", $sqlstring);
                $addtables = ",{$this->profile->tablename_urls} as u";
                $joincond = "and a.url=u.id";
            }

            if (strpos("  " . $sqlstring, " params ") != false) {
                $sqlstring = str_replace("params =", "a.params=", $sqlstring);
                $sqlstring = str_replace("params !=", "a.params!=", $sqlstring);
                $sqlstring = str_replace("params LIKE", "up.params LIKE", $sqlstring);
                $sqlstring = str_replace("params NOT LIKE", "up.params NOT LIKE", $sqlstring);
                $addtables .= ",{$this->profile->tablename_urlparams} as up";
                $joincond .= " and a.params=up.id";
            }

            if (strpos("  " . $sqlstring, " referrer ") != false) {
                $sqlstring = str_replace("referrer =", "a.referrer=", $sqlstring);
                $sqlstring = str_replace("referrer !=", "a.referrer!=", $sqlstring);
                $sqlstring = str_replace("referrer LIKE", "r.referrer LIKE", $sqlstring);
                $sqlstring = str_replace("referrer NOT LIKE", "r.referrer NOT LIKE", $sqlstring);
                $addtables .= ",{$this->profile->tablename_referrers} as r";
                $joincond .= " and a.referrer=r.id";
            }

            if (strpos("  " . $sqlstring, " refparams ") != false) {
                $sqlstring = str_replace("refparams =", "a.refparams=", $sqlstring);
                $sqlstring = str_replace("refparams !=", "a.refparams!=", $sqlstring);
                $sqlstring = str_replace("refparams LIKE", "rp.params LIKE", $sqlstring);
                $sqlstring = str_replace("refparams NOT LIKE", "rp.params NOT LIKE", $sqlstring);
                $addtables .= ",{$this->profile->tablename_refparams} as rp";
                $joincond .= " and a.refparams=rp.id";
            }

            if (strpos("  " . $sqlstring, " keywords ") != false) {
                $sqlstring = str_replace("keywords =", "a.keywords=", $sqlstring);
                $sqlstring = str_replace("keywords !=", "a.keywords!=", $sqlstring);
                $sqlstring = str_replace("keywords LIKE", "k.keywords LIKE", $sqlstring);
                $sqlstring = str_replace("keywords NOT LIKE", "k.keywords NOT LIKE", $sqlstring);
                $addtables .= ",{$this->profile->tablename_keywords} as k";
                $joincond .= " and a.keywords=k.id";
            }

            if (strpos("  " . $sqlstring, " ipnumber ") != false) {
                $sqlstring = str_replace("ipnumber =", "v.ipnumber=", $sqlstring);
                $sqlstring = str_replace("ipnumber !=", "v.ipnumber!=", $sqlstring);
                $sqlstring = str_replace("ipnumber LIKE", "v.ipnumber LIKE", $sqlstring);
                $sqlstring = str_replace("ipnumber NOT LIKE", "v.ipnumber NOT LIKE", $sqlstring);
            }

            if (strpos("  " . $sqlstring, " visitorid ") != false) {
                $sqlstring = str_replace("visitorid =", "v.visitorid=", $sqlstring);
                $sqlstring = str_replace("visitorid !=", "v.visitorid!=", $sqlstring);
                $sqlstring = str_replace("visitorid LIKE", "v.visitorid LIKE", $sqlstring);
                $sqlstring = str_replace("visitorid NOT LIKE", "v.visitorid NOT LIKE", $sqlstring);
            }

            if (strpos("  " . $sqlstring, " useragent ") != false) {
                $sqlstring = str_replace("useragent =", "b.name=", $sqlstring);
                $sqlstring = str_replace("useragent !=", "b.name!=", $sqlstring);
                $sqlstring = str_replace("useragent LIKE", "b.name LIKE", $sqlstring);
                $sqlstring = str_replace("useragent NOT LIKE", "b.name NOT LIKE", $sqlstring);
            }

            if (strpos("  " . $sqlstring, " crawl ") != false) {
                $sqlstring = str_replace("crawl =", "a.crawl=", $sqlstring);
                $sqlstring = str_replace("crawl !=", "a.crawl=!=", $sqlstring);
                $sqlstring = str_replace("crawl LIKE", "a.crawl= LIKE", $sqlstring);
                $sqlstring = str_replace("crawl NOT LIKE", "a.crawl= NOT LIKE", $sqlstring);
            }
        }
        //echoWarning($sqlstring);
        return $sqlstring;
    }

    function GetMatchingItemID($field, $cvalue)
    {
        $table = getTable($field);
        if ($table === false) {
            return false;
        }
        $tfield = getField($table);
        if ($tfield === false) {
            return false;
        }
        return getID($cvalue, $table);
    }

    function UpdateStats($from = '', $to = '', $print = 2)
    {
        return false;
    }
}
