<?php
$path = strrev(__FILE__);
define('__PATH__',strrev(substr($path,strpos($path,'/'))));
function unlock_file($filename) {
	if(!file_get_contents($filename)) {
		define('USE_PERMISSION_SECURITY',true);
		chmod(__DIR__.'/'.$filename,0777);
		register_shutdown_function('lock_file',__DIR__.'/config.txt');
	} else define('USE_PERMISSION_SECURITY',false);
	return true;
}
function lock_file($filename,$strong = false) {
	// Lock file only if needed
	chmod(__DIR__.'/'.$filename,0000);
	return true;
}
function loadConfig() {
	unlock_file('config.txt');
	$config = explode(', ',file_get_contents(__DIR__.'/config.txt'));
	return $config;
}
function saveConfig($config) {
	file_put_contents('config.txt',implode(', ',$config));
}
define('PERMISSION_BLOCKED_FILES',array('campaigns.txt','config.txt','campaigns.txt','discussions.xml','ecommerce.txt','liveupdate.txt','locked_ips.txt','log.txt','notes.xml','users.txt','opb/opbconf.txt','log','sharebuttons/slog.txt'));
function unlock_all_files() {
	if(USE_PERMISSION_SECURITY===true) {
		foreach(PERMISSION_BLOCKED_FILES AS $file) {
			chmod(__DIR__.'/'.$file,0777);
			register_shutdown_function('lock_file',__DIR__.'/'.$file);
		}
	}
	return true;
}
function loadLog() {
	if($_SESSION['site']!='all') return file(($_SESSION['site']=='main' OR !isset($_SESSION['site'])) ? 'log.txt' : 'log/'.$_SESSION['site'].'.txt');
	else {
		$files = array_slice(scandir('log'),2);
		$data = file('log.txt');
		foreach($files AS $file) {
			$data = array_merge($data,file('log/'.$file));
		}
		return $data;
	}
}
function isMobile() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}
function parseGet($parameters) {
$parameters = explode("&",$parameters);
$return = array();
foreach($parameters AS $parameter) {
$parameter = explode("=",$parameter);
$name = $parameter[0];
$return[$name] = $parameter[1];
}
return $return;
}
function visitors_per_day($date) {
$counter = 0;
if(strtotime($date) > time()) {
$date = date("d.m.Y", time());
}
foreach(file('log.txt') AS $durchschnitt) {
$durchschnitt = explode(', ', $durchschnitt);
if(strtotime($date)==strtotime(substr($durchschnitt[9], 0, 10))) {
$counter++;
}
}
return $counter;
}
function visitors_per_day_strict($date) {
$counter = array();
if(strtotime($date) > time()) {
$date = date("d.m.Y", time());
}
foreach(file('log.txt') AS $durchschnitt) {
$durchschnitt = explode(', ', $durchschnitt);
if(strtotime($date)==strtotime(substr($durchschnitt[9], 0, 10))) {
$counter[] = $durchschnitt[1];
}
}
return count(array_count_values($counter));
}
function return_if_future($date) {
if(strtotime($date) > time()) {
$date = date("d.m.Y", time());
}
return $date;
}
function searchengines_day($date) {
if(strtotime($date) > time()) {
$date = date("d.m.Y", time());
}
$search_engines = array();
foreach(file('log.txt') AS $durchschnitt) {
$durchschnitt = explode(', ', $durchschnitt);
if(strtotime($date)==strtotime(substr($durchschnitt[9], 0, -9))) {
if(strpos($durchschnitt[10], 'google')!==false) {
array_push($search_engines, "Google");
}
if(strpos($durchschnitt[10], 'bing.com')!==false) {
array_push($search_engines, "Bing");
}
if(strpos($durchschnitt[10], 'ask.com')!==false) {
array_push($search_engines, "Ask");
}
if(strpos($durchschnitt[10], 'yahoo.com')!==false) {
array_push($search_engines, "Yahoo");
}
if(strpos($durchschnitt[10], 'duckduckgo.com')!==false) {
array_push($search_engines, "DuckDuckGo");
}
}
}
if(!empty($search_engines)) {
return array_count_values($search_engines);
}
if(empty($search_engines)) {
return array("<i>Keine Daten verfügbar</i>" => "<i>Keine Daten verfügbar</i>");
}
}
function countries_day($date) {
$country = array();
foreach(file('log.txt') AS $durchschnitt) {
$durchschnitt = explode(', ', $durchschnitt);
if(strtotime($date)==strtotime(substr($durchschnitt[9], 0, -9))) {
array_push($country, trim($durchschnitt[14]));
}
}
if(!empty($country)) {
return array_count_values($country);
}
if(empty($country)) {
return array("<i>Keine Daten verfügbar</i>" => "<i>Keine Daten verfügbar</i>");
}
}
function keywords_day($date) {
if(strtotime($date) > time()) {
$date = date("d.m.Y", time());
}
$keywords = array();
foreach(file('log.txt') AS $durchschnitt) {
$durchschnitt = explode(', ', $durchschnitt);
if(strtotime($date)==strtotime(substr($durchschnitt[9], 0, -9))) {
if(strpos($durchschnitt[10], 'google')!==false) {
$keywords[] = "Google=>".$durchschnitt[11]."=>".str_replace(' ', '@opolyticswhitespace', str_replace('_', ',', $durchschnitt[12]))."=>".$durchschnitt[0]."=>".parseGet(parse_url($durchschnitt[10])["query"])["q"];
}
if(strpos($durchschnitt[10], 'bing.com')!==false) {
$keywords[] = "Bing=>".$durchschnitt[11]."=>".str_replace(' ', '@opolyticswhitespace', str_replace('_', ',', $durchschnitt[12]))."=>".$durchschnitt[0]."=>".parseGet(parse_url($durchschnitt[10])["query"])["q"];
}
if(strpos($durchschnitt[10], 'ask.com')!==false) {
$keywords[] = "Ask.com=>".$durchschnitt[11]."=>".str_replace(' ', '@opolyticswhitespace', str_replace('_', ',', $durchschnitt[12]))."=>".$durchschnitt[0]."=>".parseGet(parse_url($durchschnitt[10])["query"])["q"];
}
if(strpos($durchschnitt[10], 'yahoo.com')!==false) {
$keywords[] = "Yahoo=>".$durchschnitt[11]."=>".str_replace(' ', '@opolyticswhitespace', str_replace('_', ',', $durchschnitt[12]))."=>".$durchschnitt[0]."=>".parseGet(parse_url($durchschnitt[10])["query"])["p"];
}
if(strpos($durchschnitt[10], 'duckduckgo.com')!==false) {
$keywords[] = "DuckDuckGo=>".$durchschnitt[11]."=>".str_replace(' ', '@opolyticswhitespace', str_replace('_', ',', $durchschnitt[12]))."=>".$durchschnitt[0]."=>".parseGet(parse_url($durchschnitt[10])["query"])["q"];
}
}
}
return $keywords;
}
function visitors_at_hour($date) {
$date = substr($date,0,strpos($date," "));
$hours = array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
foreach(file('log.txt') AS $durchschnitt) {
$durchschnitt = explode(', ', $durchschnitt);
if(strtotime($date)==strtotime(substr($durchschnitt[9],0,10))) {
if(strtotime($date." 0:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[0]++;
}
if(strtotime($date." 1:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[1]++;
}
if(strtotime($date." 2:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[2]++;
}
if(strtotime($date." 3:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[3]++;
}
if(strtotime($date." 4:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[4]++;
}
if(strtotime($date." 5:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[5]++;
}
if(strtotime($date." 6:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[6]++;
}
if(strtotime($date." 7:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[7]++;
}
if(strtotime($date." 8:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[8]++;
}
if(strtotime($date." 9:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[9]++;
}
if(strtotime($date." 10:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[10]++;
}
if(strtotime($date." 11:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[11]++;
}
if(strtotime($date." 12:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[12]++;
}
if(strtotime($date." 13:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[13]++;
}
if(strtotime($date." 14:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[14]++;
}
if(strtotime($date." 15:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[15]++;
}
if(strtotime($date." 16:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[16]++;
}
if(strtotime($date." 17:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[17]++;
}
if(strtotime($date." 18:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[18]++;
}
if(strtotime($date." 19:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[19]++;
}
if(strtotime($date." 20:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[20]++;
}
if(strtotime($date." 21:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[21]++;
}
if(strtotime($date." 22:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[22]++;
}
if(strtotime($date." 23:00")==strtotime(substr($durchschnitt[9], 0, strpos($durchschnitt[9],":")).":00")) {
$hours[23]++;
}
}
}
return $hours;
}
function referrers_at_day($date) {
$referrers = array();
foreach(file('log.txt') AS $durchschnitt) {
$durchschnitt = explode(', ', $durchschnitt);
if(strtotime($date)==strtotime(substr($durchschnitt[9], 0, -9))) {
$referrers[] = $durchschnitt[10];
}
}
if(!empty($referrers)) {
return array_count_values($referrers);
}
return array("<i>Keine Daten verfügbar</i>"=>"<i>Keine Daten verfügbar</i>");
}
function regions_day($date) {
$region = array();
foreach(file('log.txt') AS $durchschnitt) {
$durchschnitt = explode(', ', $durchschnitt);
if(strtotime($date)==strtotime(substr($durchschnitt[9], 0, -9))) {
array_push($region,$durchschnitt[15]);
}
}
if(!empty($region)) {
return array_count_values($region);
}
if(empty($region)) {
return array("<i>Keine Daten verfügbar</i>"=>"<i>Keine Daten verfügbar</i>");
}
}
function get_favicon($source,$domain,$useragent) {
$found = false;
$dom = new DOMDocument;
$dom->loadHTML($source);
$links = $dom->getElementsByTagName('link');
foreach($links AS $link) {
if(strtolower($link->getAttribute("rel"))=="shortcut icon") {
if(preg_match('-http-',$link->getAttribute("href"))) {
return $link->getAttribute("href");
}
if(!preg_match('-http-',$link->getAttribute("href"))) {
return $domain.$link->getAttribute("href");
}
$found = true;
break;
}
}
if($found==false) {
$options = array(
    'http' => array(
        'timeout' => 4,
        'user_agent' => "Opolytics".$usergagent."Bot 1.0 (@".$_SERVER['SERVER_NAME'].", if you have got any problems with this Bot, please Contact the Webmaster)",
        'method'  => 'GET',
    )
);
$context = stream_context_create($options);
file_get_contents($domain."/favicon.ico",false,$context);
if(!preg_match("/404 Not Found/",$http_response_header[0])) {
return $domain."/favicon.ico";
$found = true;
}
}
if($found==false) {
return "Not Found";
}
}
function get_title($source) {
return substr($source,strpos($source,"<title>"),intval(strpos($source,"</title>")-strpos($source,"<title>")));
}
function parseHeaders($source) {
$return = array();
foreach($source AS $header) {
$header = explode(": ",$header);
$name = $header[0];
$return[$name] = $header[1];
}
return $return;
}
function opolytics_activate_security() {
session_regenerate_id();
$_SESSION['csrf'] = uniqid();
}
function opolytics_check_csrf($csrf) {
if($csrf==$_SESSION['csrf']) {
return true;
}
return false;
}
function increase($start,$end) {
if($start!=0 AND $end!=0) {
return (($end-$start)/$start)*100;
}
return 'Fehler: Start- oder Endwert 0';
}
function load_compressed_xml_file($path) {
$file = file_get_contents($path);
$file = gzuncompress($file);
$xml = simplexml_load_string($file);
return $xml;
}
function save_compressed_xml_file($xmlobject,$path) {
file_put_contents($path,gzcompress($xmlobject->asXML(),9));
}
function o_login_check($user,$password,$bool = true) {
	$wrong_attempts = unserialize(file_get_contents('locked_ips.txt',true));
	$ip = $_SERVER['REMOTE_ADDR'];
	$config = loadConfig();
	if(!isset($_SESSION['last-request'])) {
		$_SESSION['last-request'] = time();
		$wrong_attempts[$ip]['attempts'] = 0;
	}
	if(time() - $wrong_attempts[$ip]['time'] > (120*60) AND isset($wrong_attempts[$ip]['time'])) {
		$wrong_attempts[$ip]['attempts'] = 0;
		unset($wrong_attempts[$ip]);
		file_put_contents('locked_ips.txt',serialize($wrong_attempts),FILE_USE_INCLUDE_PATH);
	}
	if(time() - $_SESSION['last-request'] > (10*60) AND !preg_match('/login.php/',$_SERVER['HTTP_REFERER'])) {
		session_destroy();
		unset($_SESSION['last-request']);
		header('location: login.php?reason=err_session_timed_out');
		die();
	}
	if(intval($wrong_attempts[$ip]['attempts']) > 4) {
		header('location: login.php?reason=err_too_many_wrong_attempts');
		die();
	}
	$_SESSION['last-request'] = time();
	$wrong_attempts[$ip]['time'] = time();
	$data = unserialize(file_get_contents('users.txt',true));
	if(isset($data[$user]) AND password_verify($password,$data[$user])) {
		unset($wrong_attempts[$ip]);
		file_put_contents('locked_ips.txt',serialize($wrong_attempts),FILE_USE_INCLUDE_PATH);
		return true;
	}
	if($user==$config[1] AND password_verify($password,$config[2])) {
		unset($wrong_attempts[$ip]);
		file_put_contents('locked_ips.txt',serialize($wrong_attempts),FILE_USE_INCLUDE_PATH);
		return true;
	}
	else if($bool==true) {
		$wrong_attempts[$ip]['attempts']++;
		file_put_contents('locked_ips.txt',serialize($wrong_attempts),FILE_USE_INCLUDE_PATH);
		return false;
	}
}
function translateContinentNames($array) {
 $array['Europa'] = $array['Europe'];
 $array['Asien'] = $array['Asia'];
 $array['Afrika'] = $array['Africa'];
 $array['Nordamerika'] = $array['North America'];
 $array['Südamerika'] = $array['South America'];
 $array['Australien und Ozeanien'] = $array['Australia and Oceania'];
 unset($array['Europe']); unset($array['Asia']); unset($array['Africa']); unset($array['North America']); unset($array['South America']); unset($array['Australia and Oceania']);
return $array;
}
function getMonday($date) {
$stamp = strtotime($date);
return date("d.m.Y",$stamp - (date("N",$stamp)*86400-86400));
}
function getSunday($date) {
return date("d.m.Y",strtotime(getMonday($date))+518400);
}
function issearchengine($url) {
return preg_match('/google.[a-z]{2,3}|duckduckgo.com|yahoo.com|bing.com|ask.com/',$url);
}
function searchengine($url) {
if(preg_match('/google.[a-z]{2,3}/',$url)) return 'Google';
else if(preg_match('/bing.com/',$url)) return 'Bing';
else if(preg_match('/duckduckgo.com/',$url)) return 'DuckDuckGo';
else if(preg_match('/yahoo.com/',$url)) return 'Yahoo';
else if(preg_match('/ask.com/',$url)) return 'Ask.com';
else return false;
}
function searchengines_country($country) {
$file = file('log.txt');
$data = array();
foreach($file AS $call) {
$call = explode(', ',$call);
if($call[14]==$country AND issearchengine($call[10])) {
if(searchengine($call[10])=='Yahoo') $parameter = 'p'; else $parameter = 'q';
$data[] = serialize(array('enginename'=>searchengine($call[10]),'search'=>parseGet(parse_url($call[10])['query'])[$parameter],'title'=>str_replace('_ ',', ',$call[11]),'description'=>str_replace('_ ',', ',$call[12]),'url'=>$call[0]));
}
}
$data = array_count_values($data);
foreach($data AS $key=>$value) {
$notice = unserialize($key);
$notice['calls'] = $value;
$newdata[] = $notice;
}
return $newdata;
}
function array_percent($array) {
	$sum = array_sum($array);
	foreach(array_keys($array) AS $key) {
		$array[$key] = $array[$key] / $sum * 100;
	}
	return $array;
}
function searchengine_terms_country($country) {
	$file = file('log.txt');
	foreach($file AS $call) {
		$call = explode(', ',$call);
		if($call[14]==$country AND issearchengine($call[10])) {
			if(searchengine($call[10])=='Yahoo') $parameter = 'p'; else $parameter = 'q';
			$data[] = parseGet(parse_url($call[10])['query'])[$parameter];
		}
	}
	return array_count_values($data);
}	
function regions_country($country) {
	$file = file('log.txt');
	foreach($file AS $call) {
		$call = explode(', ',$call);
		if($call[14]==$country) $data[] = $call[15];
	}
	return array_count_values($data);
}
//
//
function searchenginenames_country($country) {
	$file = file('log.txt');
	foreach($file AS $call) {
		$call = explode(', ',$call);
		if($call[14]==$country AND issearchengine($call[10])) $data[] = searchengine($call[10]);
	}
	return array_count_values($data);
}

?>