<?php
define("root", $_SERVER['DOCUMENT_ROOT']);
session_start();
require(root."/___simple_config.php");
require(root."/".adminFolder."/_common.php");
require(root."/".adminFolder."/_lib/db.php");
require(root."/".adminFolder."/_lib/main.php");
global $mainHttpHost;
require(root."/".adminFolder."/_lib/bootstraps.php");
$pageSubOf = "users";
$pageSubOf = "users";
$pageName = "user_visitors";
$pageTitle = "User Visitors";
$thisUrl = "users/visitors";
$ajax_page = "ajax_user_visitors.php";
$pageUrl = "/".adminFolder."/$thisUrl";
$pageUrl = "/".adminFolder."/users/activities";
$a=cekpost(cleanQuery($_REQUEST["a"]), "");
if ($a=="section_main") {
	$stgl = trim(cekpost(cleanQuery($_REQUEST["fil_stgl"]), date('d-m-Y', time())));
	$etgl = trim(cekpost(cleanQuery($_REQUEST["fil_etgl"]), date('d-m-Y', time())));
	$stgl = $etgl=="undefined"?date('d-m-Y', time()):$stgl;
	$etgl = $etgl=="undefined"?date('d-m-Y', time()):$etgl;
	$q_stgl = strtotime($stgl);
	$q_etgl = strtotime($etgl)+86400;
	$fil_stgl = strtotime($stgl);
	$fil_etgl = strtotime($etgl);
	$fil_limit = trim(cekpost(cleanQuery($_REQUEST["fil_limit"]), "0"));
	$fil_limit = trim($fil_limit)=="undefined"?20:$fil_limit;
	$swhere = "";
	if ($fil_limit!="0") { $act_ket .= '(LIMIT: '.$fil_limit.') '; }
	$ipLimit = "";
	$ipLimit .= " AND client_ip<>'175.100.28.148' AND client_ip2<>'175.100.28.148' AND client_ip3<>'175.100.28.148' ";
	$ipLimit .= " AND client_ip<>'119.82.254.162' AND client_ip2<>'119.82.254.162' AND client_ip3<>'119.82.254.162' ";
	$ipLimit .= " AND client_ip<>'119.82.254.197' AND client_ip2<>'119.82.254.197' AND client_ip3<>'119.82.254.197' ";
	$ipLimit .= " AND client_ip<>'125.162.12.109' AND client_ip2<>'125.162.12.109' AND client_ip3<>'125.162.12.109' ";
	$ipLimit .= "";
	$q = "SELECT * FROM _visitors a
		WHERE 1=1
			$ipLimit
		$swhere
		AND UNIX_TIMESTAMP(FROM_UNIXTIME(last_clicked))>=UNIX_TIMESTAMP(FROM_UNIXTIME(".$q_stgl.")) 
		AND UNIX_TIMESTAMP(FROM_UNIXTIME(last_clicked))< UNIX_TIMESTAMP(FROM_UNIXTIME(".$q_etgl.")) 
		ORDER BY last_clicked DESC
		LIMIT 0,$fil_limit";
	callRSL($rs, $q);
	$array_session = array();
	for ($i<0;$i<count($rs);$i++) {
		$tmp_array = array(
			"kd" => $rs[$i]["kd"],
			"http_referer" => $rs[$i]["http_referer"],
			"server_name" => $rs[$i]["server_name"],
			"http_host" => $rs[$i]["http_host"],
			"request_time" => $rs[$i]["request_time"],
			"request_time_s" => $rs[$i]["request_time_s"],
			"client_ip" => $rs[$i]["client_ip"],
			"client_ip2" => $rs[$i]["client_ip2"],
			"client_ip3" => $rs[$i]["client_ip3"],
			"browser_info" => $rs[$i]["browser_info"],
			"http_user_agent" => $rs[$i]["http_user_agent"],
			"last_clicked" => $rs[$i]["last_clicked"]
		);
		$array_session[$rs[$i]["session_id"]][] = $tmp_array;
	}
	#printR($array_session);
	if (count($rs)!=0) {
		$ld = $fil_limit;
		$cp = cekpost(cleanQuery($_GET["cp"]), "1");
		$tp = intval(count($rs) / $ld) + (count($rs)%$ld==0?0:1);
		$sr = ($cp-1) * $ld;
		$pagination = '';
		if ($tp!=1) {
			$pagination .= ('<ul class="pagination pagination-sm">');
				$disabled = '';
				$purl = '#';
				$onclick = '';
				if ($cp<=1) {
					$disabled = 'disabled';
					$onclick = ' onclick="return false;" ';
				}
				$pagination .= ('<li class="'.$disabled.'"><a href="'.$purl.'" '.($onclick!=""?$onclick:'onclick="filterReload(\''.$pageName.'\', 1);return false;"').'>&lt;&lt;</a></li>');
				$pagination .= ('<li class="'.$disabled.'"><a href="'.$purl.'" '.($onclick!=""?$onclick:'onclick="filterReload(\''.$pageName.'\', '.($cp-1).');return false;"').'>&lt;</a></li>');
				for ($c=1;$c<=$tp;$c++) {
					$active = '';
					$purl = '#';
					$disabled = '';
					$onclick = '';
					if ($c==$cp) {
						$active = 'active';
					} else {
						$purl = '#';
						$onclick = ' onclick="filterReload(\''.$pageName.'\', '.$c.');return false;" ';
					}
					$pagination .= ('<li class="'.$active.' '.$disabled.'"><a href="'.$purl.'" '.$onclick.'>'.$c.'</a></li>');
				}
				$disabled = '';
				$onclick = '';
				if ($cp>=$tp) {
					$disabled = 'disabled';
					$onclick = ' onclick="return false;" ';
				}
				$pagination .= ('<li class="'.$disabled.'"><a href="#" '.($onclick!=""?$onclick:'onclick="filterReload(\''.$pageName.'\', '.($cp+1).');return false;"').'>&gt;</a></li>');
				$pagination .= ('<li class="'.$disabled.'"><a href="#" '.($onclick!=""?$onclick:'onclick="filterReload(\''.$pageName.'\', '.$tp.');return false;"').'>&gt;&gt;</a></li>');
			$pagination .= ('</ul>');
		}
		cout('<div class="alert alert-info" role="alert"><strong>Total whole data</strong> <span class="badge">'.count($rs).'</span></div>');
		
		if ($tp!=1) {
			cout($pagination);
		}
		cout('<table class="table table-striped table-bordered">');
			cout('<thead>');
				cout('<tr>');
					cout('<th class="text-center" style="width:80px;">Host</th>');
					cout('<th class="text-center">Come From?</th>');
					cout('<th class="text-center">Data Request Time</th>');
					cout('<th class="text-center">IPs</th>');
					cout('<th class="text-center">Browser</th>');
					cout('<th class="text-center">Last Clicked</th>');
					cout('<th class="text-center"><input type="button" value="Refresh" onclick="filterReload(\''.$pageName.'\', '.$cp.');" /></th>');
				cout('</tr>');
			cout('</thead>');
			cout('<tbody>');
			$cnt = 0;
			foreach($array_session AS $key => $value) {
				#echo $key.'<br/>';
				$asess = $array_session[$key];
				if (trim($key)!="") {
					$session_id = $key;
					cout('<tr class="tr-data'.$kd.'">');
						cout('<td class="text-left" colspan="7">'.$session_id.' ('.count($asess).')</td>');
					cout('</tr>');
					for ($i=0;$i<count($asess);$i++) {
						$kd = $asess[$i]["kd"];;
						$http_referer = $asess[$i]["http_referer"];
						$referer = $http_referer;
						if (strlen($referer)>50) {
							$referer = substr($referer, 0, 50).'<br/>'.substr($referer, 51, strlen($referer)-50);
						}
						$referer = parse_url($http_referer);
						$str_referer = '';
						$just_host_referer = '';
						foreach($referer AS $a => $b) {
							if (trim($a)=="query") {
								parse_str($b, $get_query);
								$str_referer .= 'Query:';
								foreach($get_query AS $c => $d) {
									$d = str_replace("&amp;", "&", urldecode($d));
									$d = str_replace("&", "<br/>&amp;", $d);
									$str_referer .= $c .'='. urldecode($d) .'<br/>';
								}
							} else if (trim($a)=="host") {
								$just_host_referer = '<strong>'. $b .'</strong>';
								$str_referer .= $a .'=<strong>'. $b .'</strong><br/>';
							} else {
								$b = str_replace("&amp;", "<br/>&amp;", $b);
								$str_referer .= $a .'='. $b .'<br/>';
							}
						}
						$client_ip = $asess[$i]["client_ip"];
						$client_ip2 = $asess[$i]["client_ip2"];
						$client_ip3 = $asess[$i]["client_ip3"];
						#$detail1 = json_decode(file_get_contents("http://ipinfo.io/".$client_ip."/json"));
						#printR(file_get_contents("http://ipinfo.io/".$client_ip."/json"));
						#$detail2 = json_decode(file_get_contents("http://ipinfo.io/$client_ip2/json"));
						#$detail3 = json_decode(file_get_contents("http://ipinfo.io/$client_ip3/json"));
						#echo $detail1->city; // -> "Mountain View"
						$sip1 = '<a href="#" onclick="checkIP(\''.$client_ip.'\');return false;">'.$client_ip.'</a>';
						$sip2 = '<a href="#" onclick="checkIP(\''.$client_ip2.'\');return false;">'.$client_ip2.'</a>';
						$sip3 = '<a href="#" onclick="checkIP(\''.$client_ip3.'\');return false;">'.$client_ip3.'</a>';
						
						$server_name = $asess[$i]["server_name"];
						$http_host = $asess[$i]["http_host"];
						$http_host = str_replace("//", "***", $http_host);
						$http_host = str_replace("/", "/<br/>", $http_host);
						$http_host = str_replace("***", "//", $http_host);
						$last_clicked = $asess[$i]["last_clicked"];
						$sref_det = '<a href="#" onclick="getRefDet(\''.$kd.'\');return false;">Details ('.strlen($str_referer).')</a>';
						#$sref_det = (trim($str_referer)=="path=" && strlen($str_referer)==10)?'':$sref_det;
						if (trim($str_referer)=="path=<br/>" && strlen($str_referer)==10) {
							$sref_det = '';
						}
						cout('<tr class="tr-data'.$kd.'">');
							cout('<td class="text-center">'.$server_name.'<hr style="margin:5px 0;"/>'.$http_host.'</td>');
							#cout('<td class="text-center">'.printR($referer).'<br/>'.$asess[$i]["http_referer"].'</td>');
							cout('<td class="text-center">'.$just_host_referer.'<br/>'.$sref_det.'<div class="hidden ref'.$kd.'">'.$str_referer.'</div></td>');
							cout('<td class="text-center">'.$asess[$i]["request_time"].' / '.$asess[$i]["request_time_s"].'</td>');
							cout('<td class="text-center">'.$sip1.'<br/>'.$sip2.'<br/>'.$sip3.'</td>');
							$browser = trim($asess[$i]["browser_info"])!=''?$asess[$i]["browser_info"]:$asess[$i]["http_user_agent"];
							#cout('<td class="text-center">'.$asess[$i]["http_user_agent"].'</td>');
							cout('<td class="text-center">'.$browser.'</td>');
							cout('<td class="text-center" colspan="2">'.date('l', $last_clicked).'<br/>'.date('d M Y', $last_clicked).'<br/>'.date('H:i:s', $last_clicked).'</td>');
						cout('</tr>');
					}
				}
			}
			/*
			for ($i=$sr;$i<count($rs) && $cnt<$ld;$i++) {
				$cnt++;
				$kd = $rs[$i]["kd"];
				$session_id = $rs[$i]["session_id"];
				$http_referer = $rs[$i]["http_referer"];
				$referer = $http_referer;
				if (strlen($referer)>50) {
					$referer = substr($referer, 0, 50).'<br/>'.substr($referer, 51, strlen($referer)-50);
				}
				$referer = parse_url($http_referer);
				$str_referer = '';
				foreach($referer AS $a => $b) {
					if (trim($a)=="query") {
						parse_str($b, $get_query);
						$str_referer .= 'Query:';
						foreach($get_query AS $c => $d) {
							$str_referer .= $c .'='. $d .'<br/>';
						}
					} else if (trim($a)=="host") {
						$str_referer .= $a .'=<strong>'. $b .'</strong><br/>';
					} else {
						$str_referer .= $a .'='. $b .'<br/>';
					}
				}
				cout('<tr class="tr-data'.$kd.'">');
					cout('<td class="text-center" colspan="6">'.$session_id.'</td>');
					#cout('<td class="text-center">'.$rs[$i]["server_name"].' / '.$rs[$i]["http_host"].'</td>');
					##cout('<td class="text-center">'.printR($referer).'<br/>'.$rs[$i]["http_referer"].'</td>');
					#cout('<td class="text-center">'.$str_referer.'</td>');
					#cout('<td class="text-center">'.$rs[$i]["request_time"].' / '.$rs[$i]["request_time_s"].'</td>');
					#cout('<td class="text-center">'.$rs[$i]["client_ip"].'<br/>'.$rs[$i]["client_ip2"].'<br/>'.$rs[$i]["client_ip3"].'</td>');
					#$browser = trim($rs[$i]["browser_info"])!=''?$rs[$i]["browser_info"]:$rs[$i]["http_user_agent"];
					##cout('<td class="text-center">'.$rs[$i]["http_user_agent"].'</td>');
					#cout('<td class="text-center">'.$browser.'</td>');
					#cout('<td class="text-center" colspan="2">'.date('l, d M Y, H:i:s', $rs[$i]["last_clicked"]).'</td>');
				cout('</tr>');
				$qd = "SELECT * FROM _visitors a
					WHERE 1=1 AND session_id='$session_id'
						$ipLimit
					$swhere 
					AND UNIX_TIMESTAMP(FROM_UNIXTIME(last_clicked))>=UNIX_TIMESTAMP(FROM_UNIXTIME(".$q_stgl.")) 
					AND UNIX_TIMESTAMP(FROM_UNIXTIME(last_clicked))< UNIX_TIMESTAMP(FROM_UNIXTIME(".$q_etgl.")) 
					ORDER BY last_clicked DESC";
				#callRSL($rsd, $qd);
				for ($j=0;$j<count($rsd);$j++) {
					$http_referer = $rsd[$j]["http_referer"];
					$referer = $http_referer;
					if (strlen($referer)>50) {
						$referer = substr($referer, 0, 50).'<br/>'.substr($referer, 51, strlen($referer)-50);
					}
					$referer = parse_url($http_referer);
					$str_referer = '';
					foreach($referer AS $a => $b) {
						if (trim($a)=="query") {
							parse_str($b, $get_query);
							$str_referer .= 'Query:';
							foreach($get_query AS $c => $d) {
								$str_referer .= $c .'='. $d .'<br/>';
							}
						} else if (trim($a)=="host") {
							$str_referer .= $a .'=<strong>'. $b .'</strong><br/>';
						} else {
							$str_referer .= $a .'='. $b .'<br/>';
						}
					}
					cout('<tr class="tr-data'.$kd.'">');
						cout('<td class="text-center">'.$rsd[$j]["server_name"].' / '.$rsd[$j]["http_host"].'</td>');
						#cout('<td class="text-center">'.printR($referer).'<br/>'.$rsd[$j]["http_referer"].'</td>');
						cout('<td class="text-center">'.$str_referer.'</td>');
						cout('<td class="text-center">'.$rsd[$j]["request_time"].' / '.$rsd[$j]["request_time_s"].'</td>');
						cout('<td class="text-center">'.$rsd[$j]["client_ip"].'<br/>'.$rsd[$j]["client_ip2"].'<br/>'.$rsd[$j]["client_ip3"].'</td>');
						$browser = trim($rsd[$j]["browser_info"])!=''?$rsd[$j]["browser_info"]:$rsd[$j]["http_user_agent"];
						#cout('<td class="text-center">'.$rsd[$j]["http_user_agent"].'</td>');
						cout('<td class="text-center">'.$browser.'</td>');
						cout('<td class="text-center" colspan="2">'.date('l, d M Y, H:i:s', $rsd[$j]["last_clicked"]).'</td>');
					cout('</tr>');
				}
				cout('<tr class="tr-data'.$kd.'">');
					cout('<td class="text-center" colspan="6"></td>');
				cout('</tr>');
			}
			*/
			cout('</tbody>');
		cout('</table>');
		if ($tp!=1) {
			cout($pagination);
		}
		cout('<div class="alert alert-info" role="alert"><strong>Total whole data</strong> <span class="badge">'.count($rs).'</span></div>');
		cout('<!-- Modal -->
		<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
						<h4 class="modal-title">Modal title</h4>
					</div>
					<div class="modal-body row"><div class="te"></div></div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
						<button type="button" class="btn btn-primary">Save changes</button>
					</div>
				</div><!-- /.modal-content -->
			</div><!-- /.modal-dialog -->
		</div><!-- /.modal -->');
		$act_ket = "User Activities: Main List";
		if ($swhere!="") { $act_ket .= ": ".cleanQuery($swhere).""; }
		updateUserActivities($act_ket);
	} else {
		cout('<div class="alert alert-info" role="alert">');
			cout('<strong>No data available.</strong> Please add new data for display.');
		cout('</div>');
	}
}
if ($a=="checkip") {
	$ip = trim(cekpost(cleanQuery($_REQUEST["ip"]), ""));
	$the_url = "http://ipinfo.io/".$ip."/json";
	$ch = curl_init();
	#curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_COOKIEJAR, dirname( __FILE__ )."/cookie");
	curl_setopt($ch, CURLOPT_COOKIEFILE, dirname( __FILE__ )."/cookiejar");
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_VERBOSE, 1);
	$cookies = array();
	foreach ($_COOKIE as $key => $value) {
		if ($key != 'Array') {
			$cookies[] = $key . '=' . $value;
		}
	}
	curl_setopt($ch, CURLOPT_COOKIE, implode(';', $cookies));
	curl_setopt($ch, CURLOPT_URL, $the_url);
	$info = curl_exec($ch);
	$detail = json_decode($info,1);
	printR($detail);
	#echo '<hr>';
	#$detail = json_decode(file_get_contents("http://ipinfo.io/".$ip."/json"), 1);
	#printR($detail);
}
?>
