<?php

if(!defined('APP_INCLUDE')){ die('invalid inclusion'); }

set_time_limit(1800);

# For anti session bugs get the truly latest version.
$cur_dbver = getGlobalSetting("DB_MetadataVersion", 0.00);
$user_dbver = getGlobalSetting("DB_UserDataVersion", 0.00);

/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* --- profile table updates (profiloe structure_version) ------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */

/**
* If a data table doesn't have the right fields (or the wrong types), then let's "fix it", by moving
* columns or whatever is necessary.
* 
* This function assumes that the "TBL_USER_AGENTS" table exists already.
* @param SiteProfile The profile that needs to be updated.
**/

function updateDataTableForProfile($profiletoupdate) {
	global $db, $profile, $databasedriver;
	
	$style = "margin-left:10px;";
	
	# Make sure there's something to update.
	if ($profiletoupdate->structure_version >=  CURRENT_PROFILE_STRUCTURE_VERSION) {
	  return;
	}
	
	
	//$txt = Notice("\nUpdating Profile ".$profiletoupdate->profilename." from structure version $profiletoupdate->structure_version to version ".CURRENT_PROFILE_STRUCTURE_VERSION.". If you have a lot of data, this might take a while.","clear:both;$style");
	$txt = str_replace("%1", $profiletoupdate->structure_version, _PROFILE_STRUCTURE_UPDATE);
	$txt = str_replace("%2", CURRENT_PROFILE_STRUCTURE_VERSION, $txt);

	$txt = Notice("\n$txt","clear:both;$style");

	$txt.= Warning(_DONT_CLOSE_PAGE,$style);
	$txt.= Notice(_IF_ERROR_PROFILE_UPGRADE,$style);
	echoConsoleSafe($txt,true);
	flush();
	
	# Create the index prefix once for easy later reference.
	if ($databasedriver == "mysql") {
		$index_name_pre = "";
		
	} else {
		$index_name_pre = $profiletoupdate->tablename . "_";
		 
	}
	
	//$columns = $db->MetaColumns($profiletoupdate->tablename);

	if($profiletoupdate->structure_version < 4.81){
		echoWarning("This profile has an old stucture version and cannot be upgraded to Logaholic 6. We recommend you delete the profile and recreate it, OR downgrade your Logaholic to version 4.3.5 and try again.");
		exit();
	}

	if($profiletoupdate->structure_version < 4.82){
		# Reset the usergents
		$db->Execute("UPDATE {$profiletoupdate->tablename_useragents} SET name = NULL , is_bot = 0 WHERE name='unknown' AND is_bot = 1");

		$profiletoupdate->structure_version = 4.82;
		$profiletoupdate->Save();
	}

	if($profiletoupdate->structure_version < 4.83){
		# Remove the screenres, colordepth tables IF we are not in trackermode. We are removing these to cut down on files in the database dir, trying to prevent overhead for the filesystem
		if ($profiletoupdate->trackermode!=1) {
			$db->Execute("DROP TABLE {$profiletoupdate->tablename_colordepth}");
			$db->Execute("DROP TABLE {$profiletoupdate->tablename_screenres}");
		}
		$profiletoupdate->structure_version = 4.83;
		$profiletoupdate->Save();
	}

	# We need to this for Motionpoint.
	if($profiletoupdate->structure_version < 4.84){
		if(!empty($logaUtm)){
			$r = $db->Execute("SHOW COLUMNS FROM {$profiletoupdate->tablename} LIKE 'ecommerce_type'");
			$row = $r->fetchRow();
			if(!$row){
				# phew does not exists
			} else {
				# Aww Rename it to utm_type
				$db->Execute("ALTER TABLE {$profiletoupdate->tablename} CHANGE ecommerce_type utm_type CHAR(5) default ''");
				$db->Execute("ALTER TABLE {$profiletoupdate->tablename} ADD INDEX utm_type (utm_type)");
				$db->Execute("ALTER TABLE {$profiletoupdate->tablename_crawl} CHANGE ecommerce_type utm_type CHAR(5) default ''");
				$db->Execute("ALTER TABLE {$profiletoupdate->tablename_crawl} ADD INDEX utm_type (utm_type)");
				$db->Execute("DROP TABLE {$profiletoupdate->tablename_merge}");
			}
		}
		$profiletoupdate->structure_version = 4.84;
		$profiletoupdate->Save();
	}

	# Correct google referrers that had no parameters
	if($profiletoupdate->structure_version < 4.90){	
		
		# select the id of the empty keyword, select the id of the not provided keyword
		$empty_kw = getID("","keyword");
		$np_kw = getID("(not provided)","keyword");

		if (empty($empty_kw) || empty($np_kw)) {
			# never mind
		} else {
			# for all traffic that has a a referrer matching google.* AND empty keyword id, update to not provided id
			$query = "UPDATE {$profiletoupdate->tablename} set keywords='{$np_kw}' where keywords='{$empty_kw}' and referrer in (select id from {$profiletoupdate->tablename_referrers} where referrer like '%www.google.%')";
			//exit($query);
			$db->Execute($query);
		}
		$profiletoupdate->structure_version = 4.90;
		$profiletoupdate->Save();
	}

	# Adjust existing dashboards to account for the extra column
	if($profiletoupdate->structure_version < 4.91) {
		
		foreach ($profiletoupdate->dashboards as $key => $dash) {
			$config = json_decode($dash['Value'], true);
			//dump($config);
			if (!empty($config)) {
				array_unshift($config['reports'], []);
				$dash['Value'] = json_encode($config);
				$profiletoupdate->dashboards[$key] = $dash;
			}
		}
		$profiletoupdate->structure_version = 4.91;
		$profiletoupdate->Save();
	}

	if($profiletoupdate->structure_version < 4.92){
		# reset the default dashboard
		$profiletoupdate->setDefaultDashboard();
		$profiletoupdate->structure_version = 4.92;
		$profiletoupdate->Save();
	}

	if($profiletoupdate->structure_version < 4.93){
		# don't turn on patternfilter for existing profile automatically
		$profiletoupdate->patternfilter = "false";
		$profiletoupdate->structure_version = 4.93;
		$profiletoupdate->Save();
	}

	if($profiletoupdate->structure_version < 4.94){
		$profiletoupdate->AddNewsDashboard();
		$profiletoupdate->structure_version = 4.94;
		$profiletoupdate->Save();
	}

	echoSuccess(_PROFILE_UPDATE_COMPLETED,$style);
	flush();
}



/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* --- Shared table updates (cur_dbver) ------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
if($cur_dbver < 2.42){
	die(echoWarning("This Logaholic database cannot be upgraded to Logaholic version 6. Please upgrade to Logaholic version 4.3.5 first and then upgrade to Logaholic version 6."));
}

if($cur_dbver < 2.44) {
	setGlobalSetting("DB_MetadataVersion", 2.44);
}

if($cur_dbver < 2.45) {
	if(!empty($logaTA)){
		$logaTA->ResetLogTables();
	}
	setGlobalSetting("DB_MetadataVersion", 2.45);
}

if($cur_dbver < 2.46) {
	$r = $db->Execute("SHOW COLUMNS FROM ". TBL_TRAFFIC_SOURCES ." LIKE 'userid'");
	$row = $r->fetchRow();
	if(!$row){
		# Add column to traffic sources
        $db->Execute("ALTER TABLE ". TBL_TRAFFIC_SOURCES . " ADD COLUMN `userid` int(11) default 0");
	}
	setGlobalSetting("DB_MetadataVersion", 2.46);
}
if($cur_dbver < 2.47) {
	$f="CREATE FUNCTION `lg_getparam`(param varchar(55), url varchar(2048)) RETURNS varchar(2048) CHARACTER SET utf8 COLLATE utf8_unicode_ci
			BEGIN 
			declare val varchar(2048);
			declare _param varchar(60) DEFAULT CONCAT(param,'=');
			 
			select SUBSTRING_INDEX(SUBSTRING_INDEX(url,_param,-1), '&', 1)
			into val;
			 
			RETURN val;

			END";
	$db->Execute($f);
	
	setGlobalSetting("DB_MetadataVersion", 2.47);
	echoSuccess("DB_MetadataVersion "._UPDATED.": 2.46 -> 2.47");
}
if($cur_dbver < 2.48) {
	// remove facebook
	$q = $db->Execute("SELECT * FROM information_schema.tables WHERE table_schema = '$DatabaseName' AND table_name = '".TBL_REPORTS."' LIMIT 1");
	$res = "";
	if ($chk=$q->FetchRow()) {
		$q = $db->Execute("DELETE FROM ".TBL_REPORTS." WHERE filename LIKE 'facebook_%'");
		if ($session->isAdmin()) {
			$res = "Removed deprecated Facebook reports<br>";
		}
	}
	
	setGlobalSetting("DB_MetadataVersion", 2.48);
	echoSuccess("$res DB_MetadataVersion "._UPDATED.": 2.47 -> 2.48");
}

/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* --- User table updates ------------------------------------------------------------------------------------------------------------------------------ */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------- */

if (($loginSystemExists == true) && ($user_dbver < USER_DB_VERSION)) {
	
	if($user_dbver < 2.21) {
		echoWarning("This Logaholic database cannot be upgraded to Logaholic version 6. Please upgrade to Logaholic version 4.3.5 first and then upgrade to Logaholic version 6.");
	}
		 
}	

  
# If a "update_all_profiles" command is passed in, then iterate all the profiles and make sure they're
# of a valid version.  If not, then force it to be updated now.
if (isset($_REQUEST["update_all_profiles"]) && ($_REQUEST["update_all_profiles"] == 1)) {
		
	include_once "common.inc.php";
	
	if (($validUserRequired) && (!$session->isAdmin())) {
		die("Current user doesn't have access rights to update all profiles (admin rights required).");
	}
	$query = "Select profileid, profilename from ".TBL_PROFILES." where structure_version < " . 
							CURRENT_PROFILE_STRUCTURE_VERSION . " or structure_version is null";
	$result = $db->Execute($query);
	while ($profile_row = $result->FetchRow()) {
		$confname = $profile_row["profilename"];
		$profile = new SiteProfile($confname);
		updateLogTableForProfile($profile);
	}
}


$_SESSION["cur_dbver"] = getGlobalSetting("DB_MetadataVersion", $cur_dbver);
$_SESSION["user_dbver"] = getGlobalSetting("DB_UserDataVersion", $user_dbver);
?>