<?php

if(!defined('APP_INCLUDE')){ die('invalid inclusion'); }
	
	
	if(!$session->isAdmin() && isset($_REQUEST["trackermode"])){
		# check if the user has any or all tracker modes disabled
		$meta = json_decode($session->userinfo['metadata'], true);
		$disabled_tracker_modus = 0;
		for ($i= 0; $i <= 3; $i++) { 
			if(isset($meta["trackermode_{$i}"]) && intval($meta["trackermode_{$i}"]) == 0){
				$disabled_tracker_modus ++;
			}
		}

		# If the user is not able so edit/save a tracker mode. Remove it from the requests.
		if($disabled_tracker_modus == 4){
			unset($_REQUEST["trackermode"]);
		} elseif(isset($meta["trackermode_{$_REQUEST["trackermode"]}"]) && intval($meta["trackermode_{$_REQUEST["trackermode"]}"]) == 0){ 
			# Also remove the request when the user tries so set it to a mode that is diabled
			unset($_REQUEST["trackermode"]);
		}
	}

	if (isset($_REQUEST["trackermode"]) && $editprofile->trackermode != $_REQUEST["trackermode"]) {
        # we're switching data colection method.
        if ($_REQUEST["trackermode"]==1) {
            if ($_REQUEST["visitoridentmethod"]!=3) {
                $_REQUEST["visitoridentmethod"]=3;
                $saved .= "<br>Visitor Identification method was automatically changed to: Cookie<br>";
            }
        } else {
            //$saved .= "<br>Please check if Visitor Identification method on the Advanced tab is still correct<br>";    
        } 
    }
    
    # These are all user editable values.    
	$editprofile->confdomain = (isset($_REQUEST["confdomain"])) ? $_REQUEST["confdomain"] : $editprofile->confdomain;
	#idiotproof this so people can't add http
	$editprofile->confdomain = str_ireplace("https://", "", $editprofile->confdomain);
	$editprofile->confdomain = str_ireplace("https://", "", $editprofile->confdomain);

	$editprofile->equivdomains = (isset($_REQUEST["equivdomains"])) ? $_REQUEST["equivdomains"] : $editprofile->equivdomains;
	$editprofile->equivdomains = stripslashes($editprofile->equivdomains);

	#idiotproof this so people can't add http
	$editprofile->equivdomains = str_ireplace("https://", "", $editprofile->equivdomains);
	$editprofile->equivdomains = str_ireplace("https://", "", $editprofile->equivdomains);

	$editprofile->defaultfile = (isset($_REQUEST["defaultfile"])) ? $_REQUEST["defaultfile"] : $editprofile->defaultfile;
	$editprofile->splitlogs = (isset($_REQUEST["splitlogs"])) ? $_REQUEST["splitlogs"] : 0;  // Checkboxes don't get posted in IE if they're false.
	$editprofile->splitfilter = (isset($_REQUEST["splitfilter"])) ? $_REQUEST["splitfilter"] : $editprofile->splitfilter;
    $editprofile->splitfilternegative = (isset($_REQUEST["splitfilternegative"])) ? $_REQUEST["splitfilternegative"] : $editprofile->splitfilternegative; 
	$editprofile->trackermode = (isset($_REQUEST["trackermode"])) ? $_REQUEST["trackermode"] : $editprofile->trackermode;
    $editprofile->skipips = (isset($_REQUEST["skipips"])) ? $_REQUEST["skipips"] : $editprofile->skipips;

    $editprofile->skipips = stripslashes($editprofile->skipips);

	$editprofile->skipfiles = (isset($_REQUEST["skipfiles"])) ? $_REQUEST["skipfiles"] : $editprofile->skipfiles;
	
	if(isset($_REQUEST["targetfiles"])){
		if($_REQUEST["targetfiles"] != $editprofile->targetfiles){
			$all_req = explode(",",$_REQUEST["targetfiles"]);
			$all_old = explode(",",$editprofile->targetfiles);
			$req = [];
			$i = 0;
			foreach($all_req as $k => $v){
				if(CheckSubscriptionOption('KPI_Limit')) {
					if($i < ($session->subscription['KPI_Limit'])){
						$req[$k] = trim($v);
					} else {
						break; # KPI Limit reached
					}
				} else {
					$req[$k] = trim($v);
				}
				$i ++;
			}

			$old = [];
			$i = 0;
			foreach($all_old as $k => $v){
				if(CheckSubscriptionOption('KPI_Limit')) {
					if($i < ($session->subscription['KPI_Limit'])){
						$old[$k] = trim($v);
					} else {
						break; # KPI Limit reached
					}
				} else {
					$old[$k] = trim($v);
				}
				$i ++;
			}

			$new_targets = [];
			# returns a array of the entry from $req that are not in $old.
			$new_targets = array_diff($req,$old);			
			
			if(!empty($new_targets)){
				$targets = [];
				foreach($new_targets as $k => $v){
					if(empty($v)){ continue; }
					if(in_array($v,$req)){
						$id = getID($v, "urls", $editprofile->tablename);
						if(!empty($id)){
							$targets[] = $id;
						}
					}
				}

				if(!empty($targets)){
					$db->Execute("insert into $editprofile->tablename_conversions select timestamp,visitorid,url from $editprofile->tablename WHERE url in (".implode(",",$targets).") and (status=200 or status=302) order by timestamp") or die("Error updating conversion stats. ".$db->ErrorMsg());
					
				}
			}
			
			$rem = [];
			# returns a array of the entry from $old that are not in $req.
			$rem = array_diff($old,$req);
			# Get removed targetfiles
			if(!empty($rem)){
				$targets = [];
				foreach($rem as $k => $v){
					if(empty($v)){ continue; }
					if(in_array($v,$old)){
						$id = getID($v, "urls", $editprofile->tablename);
						if(!empty($id)){
							$targets[] = $id;
						}
					}
				}
				if(!empty($targets)){					
					$db->Execute("delete from $editprofile->tablename_conversions where url in (".implode(",",$targets).")") or die($db->ErrorMsg());
				}
			}
			
			$editprofile->targetfiles = implode(",",$req);
		} else {
			$editprofile->targetfiles = $editprofile->targetfiles;
		}
	}
	
	$editprofile->animate = (isset($_REQUEST["animate"])) ? $_REQUEST["animate"] : $editprofile->animate;
    $editprofile->timezone = (isset($_REQUEST["timezone"])) ? $_REQUEST["timezone"] : $editprofile->timezone;
    $newvisitoridentmethod = (isset($_REQUEST["visitoridentmethod"])) ? $_REQUEST["visitoridentmethod"] : $editprofile->visitoridentmethod;
    $visitoridentmethodswitched = ($editprofile->visitoridentmethod != $newvisitoridentmethod);
    $editprofile->visitoridentmethod = $newvisitoridentmethod;
    // $editprofile->recursive = (isset($_REQUEST["recursive"])) ? $_REQUEST["recursive"] : $editprofile->recursive;    
    $editprofile->recursive = (isset($_REQUEST["recursive"])) ? 1 : 0;    
    $editprofile->caseinsensitiveurls = (isset($_REQUEST["caseinsensitiveurls"])) ? $_REQUEST["caseinsensitiveurls"] : $editprofile->caseinsensitiveurls;    

    $editprofile->ftpserver = (isset($_REQUEST["ftpserver"])) ? $_REQUEST["ftpserver"] : $editprofile->ftpserver;
    $editprofile->ftpuser = (isset($_REQUEST["ftpuser"])) ? $_REQUEST["ftpuser"] : $editprofile->ftpuser;
    $editprofile->ftppasswd = (isset($_REQUEST["ftppasswd"])) ? $_REQUEST["ftppasswd"] : $editprofile->ftppasswd;
    $editprofile->ftpfullpath = (isset($_REQUEST["ftpfullpath"])) ? $_REQUEST["ftpfullpath"] : $editprofile->ftpfullpath;
    $editprofile->ftpport = (isset($_REQUEST["ftpport"])) ? $_REQUEST["ftpport"] : $editprofile->ftpport;
    $editprofile->ftpmode = (isset($_REQUEST["ftpmode"])) ? $_REQUEST["ftpmode"] : $editprofile->ftpmode;

    $editprofile->visittimeout = (isset($_REQUEST["visittimeout"])) ? $_REQUEST["visittimeout"] : $editprofile->visittimeout;
    $editprofile->urlparamfilter = (isset($_REQUEST["urlparamfilter"])) ? $_REQUEST["urlparamfilter"] : $editprofile->urlparamfilter;
    $editprofile->urlparamfiltermode = (isset($_REQUEST["urlparamfiltermode"])) ? $_REQUEST["urlparamfiltermode"] : $editprofile->urlparamfiltermode;
    $editprofile->googleparams = (isset($_REQUEST["googleparams"])) ? $_REQUEST["googleparams"] : $editprofile->googleparams;
    $editprofile->feedurl = (isset($_REQUEST["feedurl"])) ? $_REQUEST["feedurl"] : $editprofile->feedurl;
    $editprofile->feedburneruri = (isset($_REQUEST["feedburneruri"])) ? $_REQUEST["feedburneruri"] : $editprofile->feedburneruri; 
	
	$editprofile->activated = (isset($_REQUEST["activated"])) ? $_REQUEST["activated"] : $editprofile->activated;
		
	$editprofile->customreportsonly = (isset($_REQUEST["customreportsonly"])) ? $_REQUEST["customreportsonly"] : $editprofile->customreportsonly;
	
	# Check global custom date and profile custom date.
	$format = array(
		"format1" => "m",
		"seperator1" => "-",
		"format2" => "d",
		"seperator2" => "-",
		"format3" => "Y",
		"seperator3" => " ",
		"format4" => ""				
	);
	$format = json_encode($format);
	$date_format = getGlobalSetting("profileDateFormat",$format);
	$date_format = json_decode($date_format, true);
	if(isset($_REQUEST["format1"])){
		$editprofile->dateFormat = array(
			"format1" => $_REQUEST["format1"],
			"seperator1" => $_REQUEST["seperator1"],
			"format2" => $_REQUEST["format2"],
			"seperator2" => $_REQUEST["seperator2"],
			"format3" => $_REQUEST["format3"],
			"seperator3" => $_REQUEST["seperator3"],
			"format4" => $_REQUEST["format4"]	
		);
		if($editprofile->dateFormat == $date_format){
			if(isset($editprofile->other_settings["profileDateFormat"])){
				unset($editprofile->other_settings["profileDateFormat"]);
			}
		} else {
			$save_dateformat = json_encode($editprofile->dateFormat);
			$editprofile->other_settings["profileDateFormat"] = $save_dateformat;
		}
	} else {
		$editprofile->dateFormat = $editprofile->dateFormat;
		
	}

	# Datamanager Settings
	if(isset($_REQUEST["datamanagerLimit"]) && ( $_REQUEST["datamanagerLimit"] != getGlobalSetting("datamanagersettings",0) ) ) {
		$editprofile->other_settings["datamanagersettings"] = $_REQUEST["datamanagerLimit"];
	} else if( $_REQUEST["datamanagerLimit"] == getGlobalSetting("datamanagersettings",0) ) {
		if(isset($editprofile->other_settings["datamanagersettings"])){
			unset($editprofile->other_settings["datamanagersettings"]);
		}
	}
	
	if(isset($_REQUEST["datamanagerDir"]) && ( $_REQUEST["datamanagerDir"] != getGlobalSetting("datamanagerDirectory",logaholic_dir()."data/") ) ) {
		$editprofile->other_settings["datamanagerDirectory"] = $_REQUEST["datamanagerDir"];
	} else if( $_REQUEST["datamanagerDir"] == getGlobalSetting("datamanagerDirectory",logaholic_dir()."data/") ) {
		if(isset($editprofile->other_settings["datamanagerDirectory"])){
			unset($editprofile->other_settings["datamanagerDirectory"]);
			// $editprofile->datamanagerDir = GetGlobalSetting("datamanagerDirectory",logaholic_dir()."data/");
		}
		
	}
	
	if(isset($_REQUEST["datamanagerMaxStorage"]) && ( $_REQUEST["datamanagerMaxStorage"] != getGlobalSetting("datamanagerStorageSize",5000) ) ) {
		$editprofile->other_settings["datamanagerStorageSize"] = $_REQUEST["datamanagerMaxStorage"];
	} else if( $_REQUEST["datamanagerMaxStorage"] == getGlobalSetting("datamanagerStorageSize",5000) ) {
		if(isset($editprofile->other_settings["datamanagerStorageSize"])){
			unset($editprofile->other_settings["datamanagerStorageSize"]);
		}
	}
	
	$editprofile->logparsertype = (isset($_REQUEST["logparsertype"])) ? $_REQUEST["logparsertype"] : $editprofile->logparsertype;
    $editprofile->includebackup = (isset($_REQUEST["includebackup"])) ? $_REQUEST["includebackup"] : $editprofile->includebackup;
    $editprofile->currency = (isset($_REQUEST["currency"])) ? $_REQUEST["currency"] : $editprofile->currency;
    $editprofile->vidm_custom_cookie = (isset($_REQUEST["vidm_custom_cookie"])) ? $_REQUEST["vidm_custom_cookie"] : $editprofile->vidm_custom_cookie;
                                                                                                       
    $editprofile->profiletype = (isset($_REQUEST["profiletype"])) ? $_REQUEST["profiletype"] : $editprofile->profiletype;
    $editprofile->patternfilter = (isset($_REQUEST["patternfilter"])) ? $_REQUEST["patternfilter"] : $editprofile->patternfilter;
    

	if (isset($_REQUEST["ipencoding"]) && $editprofile->ipencoding != $_REQUEST["ipencoding"] && $_REQUEST["ipencoding"]=='true') {
		// we need to mask all the Ip numbers in the visitorid table
		$db->Execute("update {$editprofile->tablename_visitorids} set ipnumber = CONCAT(SUBSTRING_INDEX(ipnumber, '.', 3),'.0') where ipnumber like '%.%'");
		$db->Execute("update {$editprofile->tablename_visitorids} set ipnumber = CONCAT(SUBSTRING_INDEX(ipnumber, '.', 4),':0:0:0:0') where ipnumber like '%:%'");
		$saved.="Converted IP numbers. ";
	}
    $editprofile->ipencoding = (isset($_REQUEST["ipencoding"])) ? $_REQUEST["ipencoding"] : $editprofile->ipencoding;

	# If we have proper security rights, edit these core values.
	if (!$validUserRequired || $session->canAddProfiles())  {

			# We're gonna have some slashes!
			if (isset($_REQUEST["logfilefullpath"])) {$_REQUEST["logfilefullpath"] = stripslashes($_REQUEST["logfilefullpath"]); }

		
		$editprofile->profilename = (isset($_REQUEST["newconfname"])) ? $_REQUEST["newconfname"] : $editprofile->profilename;
		$editprofile->logfilefullpath = (isset($_REQUEST["logfilefullpath"])) ? str_replace("\\", '/', $_REQUEST["logfilefullpath"]) : $editprofile->logfilefullpath;
	}
	
	# Check and see if variables are correctly set to save...
	$cansave = true;	
	
	if (!$editprofile->profilename) {
		$saved .= ""._NO_PROFILE_NAME_ENTERED."<br/>";
		$cansave = false;
		$saveerror = true;
		$edit=1;
	}

	
    if (!$editprofile->tablename && $conf!="newcnf") {
		$saved .= ""._NO_MYSQL_TABLE_ENTERED."<br/>";
		$cansave = false;
		$saveerror = true;
		$edit=1;
	}
    

	if ($conf=="newcnf" || $new==1) {
		$checklimits = "Select profilename from ".TBL_PROFILES;
		$checklimitsresult = $db->Execute($checklimits) or die(_COULDNT_QUERY_PROFILES.". " . $db->ErrorMsg());
		if (defined("_LIMIT_PROFILES") != 0) {
			  if ($checklimitsresult->RecordCount() > _LIMIT_PROFILES) {
				  $saved .= ""._TOO_MANY_PROFILES."<br>";
				  $cansave = false;
				  $saveerror = true;
				  $edit=1;            
			  }
		}
	}		
	
	if (defined("_ENABLE_IMPORTANT_PARAMETER_EDITOR_")) {		

		foreach ($editprofile->importantURLParams as $key => $value) {
			if(isset($_REQUEST["paramurl"][$key])){
				if($value["filename"] == $_REQUEST["paramurl"][$key] && $value["importantparams"] == $_REQUEST["paramnames"][$key]){
					continue;
				}
			}

			$editprofile->_importantURLParamsToDelete[] = $editprofile->importantURLParams[$key];
			unset($editprofile->importantURLParams[$key]);
		}

		foreach($_REQUEST["paramid"] as $k => $v){
			$new_p = array(
				"paramid" => (@$editprofile->importantURLParams[$k]['paramid']) ? $editprofile->importantURLParams[$k]['paramid'] : null
				, "filename" => $_REQUEST["paramurl"][$k]
				, "nameisregex" => (@$editprofile->importantURLParams[$k]['nameisregex']) ? $editprofile->importantURLParams[$k]['nameisregex'] : null
				, "importantparams" => $_REQUEST["paramnames"][$k]
			);
			$editprofile->importantURLParams[$k] = $new_p;
		}
	}	
	if ($cansave) {
		$editprofile->dieonsqlerror = false;
		$editprofile->Save();
		if ($validUserRequired) {
			if ($session->canAddProfiles() && !$session->isAdmin() && !$session->allProfiles) {
                //This does not work when renaming a profile. 2021-11-23
				if ($new==1) {
					if(!empty($session->user_profiles)){
						$concat = "concat(PROFILES,". $db->Quote(",$editprofile->profilename") .")";
					} else {
						$concat = $db->Quote($editprofile->profilename);
					}

					$q = "UPDATE ".TBL_USERS." SET PROFILES = {$concat} WHERE username = ".$db->Quote($session->username);
					$db->Execute($q);

					# If the user can add profiles, he should be the default manager as well
					$session->addToUserProfiles($editprofile->profilename);					
				}
			}
		}
		
		if ($editprofile->lastsqlerror) {
			$saved .= "<font color=\"red\">".$editprofile->lastsqlerror."</font><br>";
			$edit=1;
			$saveerror = true;
		} else {
			$saved .= 'Profile Saved' ;
			unset($edit);
			unset($new);
		}
		if ($visitoridentmethodswitched) {
			# We need to recalculate the current visitor identification method.
		}
	}

if (($editprofile->profileloaded) && (!$saveerror)) {

    createDataTable($editprofile);
}

?>