<?php
/*
Plugin Name: Logaholic Web Analytics - Advanced web stats
Plugin URI: http://www.logaholic.com/
Description: The Logaholic Wordpress plugin installs a free full featured web stats solution on your blog with a single click. It provides in-depth traffic statistics, visitor analytics, navigation analysis, keyword and referrer stats, visit trends, custom website statistics dashboards and much more.
Version: 3.0
Author: Logaholic
Author URI: http://www.logaholic.com/
License: Commercial
*/
?>
<?php

?>
<?php
function logaholic_install_warning() {
	echo "<div id='logaholic-warning' class='updated fade'><p><strong>".__('Logaholic failed to install.')."</strong> ".sprintf(__('Set allow_url_fopen to true in the PHP ini file, or install cURL.'), "plugins.php")."</p></div>";
}
function installLogaholic() {
	if(createGlobalPHP() == true) {
		SetupLogaholic();
	}
}

function createTablenamePHP($profile) {
	if(!empty($profile->tablename)) {
		$real_path = realpath(__FILE__);
		$path = dirname($real_path);
		$gfile = $path . "/files/{$profile->profilename}_tables.php";
		
		if(!file_exists($gfile)) {
			$fp = fopen ($gfile,"w+");
			fwrite ($fp, "<?php \n");
			fwrite ($fp, "\$lg_tablename=\"{$profile->tablename}\";\n");
			fwrite ($fp, "?>");
			fclose ($fp);

			if(ini_get('allow_url_fopen') == true) {
				file_get_contents(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__)));
				return true;
			} elseif(function_exists('curl_init')) {
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__)));
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
				$exec = curl_exec($ch);
				curl_close($ch);
				return true;
			} else {
				add_action('admin_notices', 'logaholic_install_warning');
				return false;
			}
		}
	}
	
	return false;
}

function createGlobalPHP() {
	$myErrors = new WP_Error();
	
	$real_path = realpath(__FILE__);
	$path = dirname($real_path);
	$gfile = $path . "/files/global.php";
	
	if(is_writable($path."/files/") == true) {
		if(!file_exists($gfile)) {
			$fp = fopen ($gfile,"w+");
			fwrite ($fp, "<?php \$DatabaseName=\"".DB_NAME."\";\n");
			fwrite ($fp, "\$databasedriver=\"mysql\";\n");
			fwrite ($fp, "\$mysqlserver=\"".DB_HOST."\";\n");
			fwrite ($fp, "\$mysqluname=\"".DB_USER."\";\n");
			fwrite ($fp, "\$mysqlpw=\"".DB_PASSWORD."\";\n");
			fwrite ($fp, "\$mysqlprefix=\"LWA_\";\n");
			fwrite ($fp, "?>");
			fclose ($fp);

			if(ini_get('allow_url_fopen') == true) {
				file_get_contents(WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__)));
				return true;
			} elseif(function_exists('curl_init')) {
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__)));
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
				$exec = curl_exec($ch);
				curl_close($ch);
				return true;
			} else {
				add_action('admin_notices', 'logaholic_install_warning');
				return false;
			}
		}
	} else {
		die("<span style='font-family: Helvetica, Arial, Sans-Serif;'>The files directory is not writable. Please go to your wordpress plugins folder on your server, then go to logaholic and make sure the files directory is writable.</span>");
	}
	return false;
}

function SetupLogaholic() {
	global $db, $databasedriver, $mysqlprefix;
	
	include("common.inc.php");
	
	# set up the new profile
	$profile = new SiteProfile();
	
	$profile->profilename = $_SERVER['HTTP_HOST'];
	if (empty($profile->profilename)) {
		echo "Invalid profilename: $profile->profilename\n";
		exit();
	}
	if (profileExists($profile->profilename)==true) {
		echo "This profile already exists.";
		exit();
	}
	
	$profile->confdomain = $_SERVER['HTTP_HOST'];
	
	$profile->trackermode=1;
	$profile->logfilefullpath = "";    
	$profile->splitlogs = 0;
	$profile->visitoridentmethod = 3;
	$profile->activated = 1;

	$profile->Save();
	createDataTable($profile);
	
	createTablenamePHP($profile);
	
	echo "Success: Created profile {$profile->profilename} for {$profile->confdomain} \n";
	
	setGlobalSetting("UserAuthenticationType", "logaholic");
	setGlobalSetting("UserAuthenticationType_Var", "");
	setGlobalSetting("IsWordPressInstall", "true");
}

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 addLogaholicJavascriptTracker() {
	$w_path = WP_PLUGIN_URL."/".str_replace(basename( __FILE__),"",plugin_basename(__FILE__));
	
	echo "<!-- /* Logaholic Web Analytics Code */ -->
<script type=\"text/javascript\">
var lwa_profile = \"{$_SERVER[HTTP_HOST]}\";
var lwa_server = \"{$w_path}\";
document.write(unescape(\"%3Cscript type='text/javascript' src='\" + lwa_server + \"lwa.js'%3E%3C/script%3E\"));
</script>
<script type=\"text/javascript\">
var lwa = trackPage();
</script>";
	
	echo " /></a> <a href=>Web Analytics</a> by Logaholic</noscript>";
	
}

function WpLogaholic() {
	$plugin_dir = str_replace(basename( __FILE__),"",plugin_basename(__FILE__));
	if(substr($plugin_dir, -1) == '/'){ # check for '/' we do not want that
		$plugin_dir = substr($plugin_dir,0, -1);
	}

	include_once("languages/english/interface.php");
	include_once("includes/install.php");
	$lg_install = new Install();

	# Reset the logaholic path to the correct path
	$lg_install->path = WP_PLUGIN_DIR . "/" . $plugin_dir;
	$lg_install->warning_level = 1;

	# Do the checks and get the output
	ob_start();
	$lg_install->FilePermissionsChecks();
	$lg_install->PhpSettings();
	$content = ob_get_clean();

	# If there is output it are warnings and we need to show those
	if(!empty($content)){
		echo "<style>
			.warning.invalidbox{ border-radius: 4px; float: left; width: 743px;  margin:10px 0; padding: 8px 8px 8px 25px; border: 1px solid #FF3A3A; background: url(images/icons/cancel.gif) no-repeat scroll 5px 8px #F9F2F2; }
			#lg_install_output{ margin:30px; }
			</style>";

		echo "<div id='lg_install_output'>
			<h2>Logaholic Php and File Settings</h2>
			<p>Please read the warning message(s) below and resolve the problem. After resolving you can reload this screen to go to your Logaholic.</p>
			{$content}
		</div>";
		return;
	}

	$wp_lg_user = wp_get_current_user();
	syncLogaholicUser($wp_lg_user);

	if($wp_lg_user->wp_capabilities['administrator'] == 1) {
		$lgpkey = md5($wp_lg_user->data->user_login) . ":" . md5($wp_lg_user->data->user_pass);
		$url = WP_PLUGIN_URL."/{$plugin_dir}?lgpkey={$lgpkey}";

		echo "You will now be redirected to your Logaholic. If this does not work please <a href='$url'>click here</a>.";

		echo "<script type='text/javascript'>";
			echo "window.location = '$url';";
		echo "</script>";
	}
}

function addLogaholicButton() {
    	$page_title = __('Logaholic Stats','wp-logaholic');
    	$menu_title = __('Logaholic Stats','wp-logaholic');

    	# add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position )
    	add_menu_page($page_title, $menu_title , 'manage_options', 'logaholic', 'WpLogaholic',
                      'https://www.logaholic.com/favicon.png'
        );

}

function syncLogaholicUser($wp_lg_user) {
	global $db, $databasedriver, $mysqlprefix;
	if(empty($wp_lg_user)) {
		$wp_lg_user = wp_get_current_user();
	}
	
	include_once("common.inc.php");
	if($wp_lg_user->wp_capabilities['administrator'] == 1) {
		$db->Execute("INSERT INTO ".TBL_USERS." (`username`, `name`, `password`, `email`, `isAdmin`) VALUES (".$db->Quote($wp_lg_user->data->user_login).", ".$db->Quote($wp_lg_user->data->user_nicename).", ".$db->Quote(md5($wp_lg_user->data->user_pass)).", ".$db->Quote($wp_lg_user->data->user_email).", 1) ON DUPLICATE KEY UPDATE `password` = ".$db->Quote(md5($wp_lg_user->data->user_pass)).";");
	} else {
		$db->Execute("DELETE FROM ".TBL_USERS." WHERE `username` = ".$db->Quote($wp_lg_user->data->user_login));
	}
}

add_action ( 'wp_head', 'addLogaholicJavascriptTracker' );
add_action ( 'plugins_loaded', 'installLogaholic' );
add_action ( 'admin_menu', 'addLogaholicButton' );
?>