<?php
function force_redirect() {
	$CI =& get_instance();
	if(!$CI->input->is_ajax_request()) {
		$settings = $CI->DefaultModel->generalSettings();
		$redirectLocation = 0;
		if(($settings['www'] != 1 && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') || ($settings['www'] == 1 && substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.')) {
			$redirectLocation = 1;
		}
		else if(($settings['https'] == 1 && !httpsStatus()) || ($settings['https'] != 1 && httpsStatus())) {
			$redirectLocation = 1;
		}
		
		if($redirectLocation == 1) {
			$queryString  = $CI->input->server('QUERY_STRING');
			$url = base_url(uri_string()).(!empty($queryString) ? "?".$queryString : "");
			header("HTTP/1.1 301 Moved Permanently");
			redirect($url,"location",301);
			exit();
		}
	}
}

function count_statistics() {
	$CI =& get_instance();
	if(!$CI->input->is_ajax_request()) {
		$class = $CI->router->fetch_class();
		$forbiddenClasses = array("admin","auth");
		if(!in_array($class,$forbiddenClasses)) {
			$countUnique = 0;
			if($CI->input->cookie("vds_uv",true) == NULL) {
				$CI->input->set_cookie("vds_uv",md5(uniqid()),86400);
				$countUnique = 1;
			}
			
			$date = date("Y-m-d");
			$cacheVar = "vds_stats_entry_".$date;
			$statsEntry = $CI->cache->get($cacheVar);
			if(!is_null($statsEntry) && is_array($statsEntry) && count($statsEntry) > 0) {
				$statsEntry['pageViews'] = $statsEntry['pageViews'] + 1;
				$statsEntry['uniqueViews'] = ($countUnique == 1 ? $statsEntry['uniqueViews'] + 1 : $statsEntry['uniqueViews']);
				$CI->DefaultModel->updateStatisticsEntry($statsEntry,$date);
				$CI->cache->save($cacheVar,$statsEntry,86400);
			}
			else {
				$entryRecord = $CI->DefaultModel->getStatsEntryRecord($date);
				if(is_array($entryRecord) && count($entryRecord) > 0) {
					$values = array();
					$values['date'] = $entryRecord['date'];
					$values['pageViews'] = $entryRecord['pageViews'] + 1;
					$values['uniqueViews'] = ($countUnique == 1 ? $entryRecord['uniqueViews'] + 1 : $entryRecord['uniqueViews']);
					$values['downloads'] = $entryRecord['downloads'];
					$CI->DefaultModel->updateStatisticsEntry($values,$date);
					$CI->cache->save($cacheVar,$values,86400);
				}
				else {
					$statsEntry = array();
					$statsEntry['date'] = $date;
					$statsEntry['pageViews'] = 1;
					$statsEntry['uniqueViews'] = ($countUnique == 1 ? 1 : 0);
					$statsEntry['downloads'] = 0;
					$CI->DefaultModel->addStatisticsEntry($statsEntry);
					$CI->cache->save($cacheVar,$statsEntry,86400);
				}
			}
		}
	}
}
?>