<?php // Script Copyright 2020 Econfirmpro Contact: webmaster@econfirmpro.com
define('AUTHACCESS',"affirmative");


// ===== CONFIG ===== //
$block_duration = 3600; // seconds (1 hour)
$rate_limit = 60; // max requests per time window
$time_window = 60; // seconds

$storage_file = __DIR__ . '/ip_blocklist.json';

// Known bad bot keywords
$bad_bots = [
    'curl', 'wget', 'python', 'scrapy', 'httpclient',
    'libwww', 'nikto', 'sqlmap', 'nmap',
    'ahrefsbot', 'semrushbot', 'mj12bot',
    'dotbot', 'petalbot', 'bytespider',
    'serpstatbot', 'yandexbot'
];

// Optional whitelist (safe bots or your IP)
$whitelist = [
    '66.249.', // Googlebot IP range example
];

// ===== GET USER INFO ===== //
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$user_agent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');

// ===== LOAD DATA ===== //
$data = [];
if (file_exists($storage_file)) {
    $json = file_get_contents($storage_file);
    $data = json_decode($json, true) ?: [];
}

// Cleanup expired blocks
$now = time();
foreach ($data as $stored_ip => $info) {
    if (isset($info['blocked_until']) && $info['blocked_until'] < $now) {
        unset($data[$stored_ip]);
    }
}

// ===== WHITELIST CHECK ===== //
foreach ($whitelist as $safe) {
    if (strpos($ip, $safe) === 0) {
        return; // allow
    }
}

// ===== BLOCK IF ALREADY BLOCKED ===== //
if (isset($data[$ip]['blocked_until']) && $data[$ip]['blocked_until'] > $now) {
    http_response_code(403);
    exit('Access denied.');
}

// ===== USER AGENT CHECK ===== //
if (empty($user_agent)) {
    block_ip($ip, $data, $block_duration, $storage_file);
}

foreach ($bad_bots as $bot) {
    if (strpos($user_agent, $bot) !== false) {
        block_ip($ip, $data, $block_duration, $storage_file);
    }
}

// ===== RATE LIMITING ===== //
if (!isset($data[$ip])) {
    $data[$ip] = ['requests' => [], 'blocked_until' => 0];
}

// Remove old requests
$data[$ip]['requests'] = array_filter(
    $data[$ip]['requests'],
    fn($t) => $t > ($now - $time_window)
);

// Add current request
$data[$ip]['requests'][] = $now;

// Check limit
if (count($data[$ip]['requests']) > $rate_limit) {
    block_ip($ip, $data, $block_duration, $storage_file);
}

// ===== SAVE DATA ===== //
file_put_contents($storage_file, json_encode($data));

// ===== BLOCK FUNCTION ===== //
function block_ip($ip, &$data, $duration, $file) {
    $data[$ip]['blocked_until'] = time() + $duration;
    file_put_contents($file, json_encode($data));

    http_response_code(403);
    exit('Blocked.');
}


























$xreq = 0;
foreach($_REQUEST as $k=>$v){
	if( (strlen($k) > 30) || (strlen($v) > 150)){echo "Error";exit();}
	$key = cleanname($k);
	$_REQUEST[$key] = cleanname($v);
	$clean_req[$key] = cleanname($_REQUEST[$key]);
	$xreq++;
	if ($xreq > 10){echo "Error";exit();}		
}
$xmlmodels = array();
$allmodel_array = array();


require('site_config.php');



if(!empty($_POST)){
	$_POST['db'] = cleanname($_POST['db']);
	if(!in_array($_POST['db'], $all_feeds) ) {
		echo "Bad Request" . " " . $_POST['db'];
		exit();
	}
}
if (!empty($clean_req['camframe']) && ($clean_req['camframe'] == "yes" ) ) {

	if ( !empty($clean_req['camfeed']) && in_array($clean_req['camfeed'], $all_feeds) && (!empty($clean_req['model_name'])) ) {
		camframe();
	} else {
		echo "invalid request";
		exit(0);
	}

}
$checkfeed = $default_feed;
$media_type = $default_media_type;

if (!empty($clean_req['media_type']) && $clean_req['media_type'] == "video" && empty($clean_req['db']) ) {
	$clean_req['db'] = $defaultvideopage;
}
if (!empty($clean_req['media_type']) && empty($clean_req['db']) ||  !empty($clean_req['db']) && $clean_req['db'] == "theme")  {
	$clean_req['media_type'] = "cams";
	$clean_req['db'] = $default_feed;
}

if($videositeonly == "yes"){
	$clean_req['media_type'] = "video";
	$media_type = "video";
	$clean_req['db'] = $defaultvideopage;
	$checkfeed = $defaultvideopage;

}
$active_feeds = array($checkfeed=>"xml");
$theme = "";
$doingsearch = "";
if(!empty($clean_req['page'])) {
	$p_start = clean_int($clean_req['page']);
	$p_start = 	$p_start - 1;
	$p_start = 	$p_start * $thumbs_per_page;
	if($p_start<0){$p_start=0;}
	$p_end = $p_start+$thumbs_per_page;
	$pgn_currentPage = $clean_req['page'];
}
else {
	$p_start = 0;
	$p_end = $thumbs_per_page;
	$pgn_currentPage = 1;
}


$single_feed_mode = false;
if ( !empty($clean_req['media_type']) && $clean_req['media_type'] == "cams" && !empty($clean_req['db'])  ) {
	$checkfeed = $clean_req['db'];
	$media_type = "cams";
	if(!empty($mix_all_feeds) && ($checkfeed == "allcams") ){
		$active_feeds = $mix_all_feeds;
		$clean_req['db'] = "allcams";
		$checkfeed = 'allcams';
	}else {
		//unset($mix_all_feeds);
		$mix_all_feeds = array();

		$active_feeds = array($checkfeed=>"xml");
		$clean_req['media_type'] = "cams";
		$clean_req['db'] = "$checkfeed";
		$single_feed_mode = true;
	}

}

if ( !empty($clean_req['media_type']) && $clean_req['media_type'] == "video" && !empty($clean_req['db'])  ) {

	$checkfeed = $clean_req['db'];
	$media_type = "video";
	if(!empty($mix_all_video) && ($checkfeed == "allmovies") ){
		$active_feeds = $mix_all_video;
		$clean_req['media_type'] = "video";
		$clean_req['db'] = "allmovies";
		$checkfeed = 'allmovies';
	}else {
		$mix_all_video = array();

		$active_feeds = array($checkfeed=>"xml");
		$clean_req['media_type'] = "video";
		$clean_req['db'] = "$checkfeed";
		$single_feed_mode = true;
	}

}


if (empty($clean_req['media_type'])) {

	$clean_req['media_type'] = "cams";
	if(!empty($mix_all_feeds) ){
		$active_feeds = $mix_all_feeds;
		$clean_req['db'] = "allcams";
		$checkfeed = 'allcams';
		$media_type = "cams";
	}else{
		$clean_req['db'] = $default_feed;
		$checkfeed = $default_feed;
		$media_type= $default_media_type;
	}
	
}


// if themes are live and visible
if( (!empty($clean_req['themestyle'])) && ($run_test_themes == "yes") ) {
	if(in_array($clean_req['themestyle'], $allowed_themes)){
		$template = $clean_req['themestyle'];
		$theme = "/theme/$template";
	}else{
		echo "ERROR! Not allowed.";exit();
	}
}

if( !empty($clean_req['model_profile']) ) {
	if(!empty($mix_all_feeds) ){
		$active_feeds = $mix_all_feeds;
	}
}

$current_time = time();
feedupdatetime();


if( !empty($clean_req) && !empty($clean_req['search']) ){
	foreach($clean_req as $k=>$v){
		$clean_req[$k] = cleanname_search($v);
	}
	$clean_req['search'] = substr($clean_req['search'], 0, 100);
	$clean_req['search'] = trim($clean_req['search']);
	$doingsearch = true;
	if ( !empty($clean_req['media_type']) ) {
		$media_type = $clean_req['media_type'];
		if ($media_type == "video") {
			searchvids();
		}
		if ($media_type == "cams") {
			searchcams();
		}
	} //not empty media_type 
} 
// show model profile
if( !empty($clean_req['model_profile']) ) {
	modelpage($clean_req['model_profile']);
	exit();
}
// show video page
if( !empty($clean_req['clip']) ) {
	videopage($clean_req['clip']);
	exit();
}

include(__DIR__ . "/themes/$template/header.php");
if (in_array($checkfeed,$all_feeds)) {
	makepage();
} elseif (!empty($thispage)) {
	echo $thispage;
} else {
	echo "<center><span class=\"pagenotfound\">Page not found</span></center>";
}
include(__DIR__ . "/themes/$template/mid_page.php");
include(__DIR__ . "/themes/$template/footer.php");

exit();


function feedupdatetime() {
	global $active_feeds, $never_update, $update_secs, $xmlfile, $feed_url,$total_item_count,$allowed_genders;
	global $xmlparse,$mndx,$mnndx_all,$xmlmodels_allcams,$allcams,$xmlmodels_names_allcams,$musername,$num_related_models,$sponsor_cmp,$page_model,$related_model,$xmlfile,$xmlmodels_names;
	global $extra_data,$used_modelnames,$clean_req,$mix_all_feeds;
	
	if (($clean_req['media_type'] == "video") || ($clean_req['media_type'] == "movies") ) {
		return;
	}
	
	$these_feeds = array();
	$mnndx_all = 0;
	$allcams = array();
	$xmlmodels_names_allcams = array();
	$current_time = time();
	$xmlmodels_names = array();
	$update=false;
	if(!empty($mix_all_feeds)){
		$these_feeds = $mix_all_feeds;
	}else{
		$these_feeds = $active_feeds;
	}
	foreach($these_feeds as $k=>$v) {
		if (!in_array($k, $never_update)) {
			$in_file = __DIR__ . "/feeds/" . $k . "_update.txt";
			$feed_time = @file_get_contents($in_file);
			if($feed_time < $current_time){
				$update="ok";
				$feed_time = $current_time + $update_secs;
				$out_file = $in_file;
				$file = fopen("$out_file","w+");
				if (flock($file,LOCK_EX)) {
					fwrite($file,$feed_time);
				  	fflush($file);
				  	flock($file,LOCK_UN);
				} else {
				 	 echo "Error locking file! $in_file";
				}
				fclose($file);
				if ($k != 'allcams') {
					$multrequrl[$k] = $feed_url[$k];
				}
			}//update current time
		}// if never update
	}//foreach	

	if ($update == "ok") {	
		$responses = array();
		$responses = mult_req($multrequrl);
		foreach($responses as $k=>$v) {
			$xmlfile = $v;
			parse_feed($k, "update");
		
		}
	}
	
	if ( ($update == "ok") && (is_array($xmlmodels_allcams)) ) {
		$temp_xmlmodels_allcams = array();
		$temp_xmlmodels_names_allcams = array();
		$npt = count($xmlmodels_allcams);
		$npp = $npt;
		$npt--;
		$ordinator = get_ordinator($npt);
		for($x=0;$x<$npp;$x++) {
			$rsindx = (int)$ordinator[$x];
			$temp_xmlmodels_allcams[$x] = $xmlmodels_allcams[$rsindx];
			$mmnm = $xmlmodels_allcams[$rsindx]['username'];
			$temp_xmlmodels_names_allcams[$mmnm] = $x;
		}
		$xmlmodels_allcams = $temp_xmlmodels_allcams;
		$xmlmodels_names_allcams = $temp_xmlmodels_names_allcams;
		$out_file = __DIR__ . "/feeds/feed_allcams.txt";
		$filedata = serialize($xmlmodels_allcams);
		writetxtfile($out_file, $filedata);
		$out_file = __DIR__ . "/feeds/modelndx_allcams.txt";
		$filedata = serialize($xmlmodels_names_allcams);
		writetxtfile($out_file, $filedata);	
	}
}
		
function swmatch($s_array) {
	global $media_type,$words,$clean_req;
	$search_db = array();
	$phrase1 = "";
	$phrase2 = "";
	$phrase3 = "";
	$xxx_phrase_db = array();
	$temp = array();
	if (!empty($clean_req['words'])) {
		$words = explode("-", $clean_req['words']);
		$phrase1 = preg_replace("/-/", "", $clean_req['words']);
		$phrase2 = preg_replace("/-/", " ", $clean_req['words']);
	} else {
		if (strpos($clean_req['search'], "-") !== false){
				$words = explode("-", $clean_req['search']);
		}else{
				$words = explode(" ", $clean_req['search']);
		}
		$phrase1 = preg_replace("/ /", "", $clean_req['search']);
		$phrase2 = $clean_req['search'];
		$phrase3 = preg_replace("/-/", " ", $clean_req['search']);
	}
	$xxx_db = array();
	$foundphrase = false;
	$foundword = false;
	$foundone = false;
	$ndx = 0;
	foreach ($s_array as $haystack) {
		$foundword = false;
		$foundphrase = false;
		if (stripos($haystack,$phrase1) !== false){
			$foundphrase = true;
			$foundone = true;
		} 
		if (stripos($haystack,$phrase2) !== false){
			$foundphrase = true;
			$foundone = true;
		}
		if (stripos($haystack,$phrase3) !== false){
			$foundphrase = true;
			$foundone = true;
		}
		$jwords = implode("", $words);
		if(  (count($words) > 10) || (strlen($jwords) > 100)    ){
			echo "ERROR : Search too long"; 
			exit(0);
		}		
		$ccx=0;
		foreach($words as $wwx) {
			if (stripos($haystack,$wwx) !== false){
				$foundphrase = true;
				$foundone = true;
			}
		$ccx++;
		if($ccx>10){echo "Error Search phrase too long"; exit();}
		}
		if ($foundphrase == true) {
			$xxx_phrase_db[] = $ndx;
		}
	$ndx++;
	}
	if($foundone === false){
		$ndx = 0;
		foreach ($s_array as $haystack) {
			$foundword = false;
			foreach($words as $wd) {
				if (strpos($haystack,$wd) !== false){
					$foundword = true;
				}	 
			}
			if ($foundword == true) {
				$xxx_db[] = $ndx;
			}
		$ndx++;
		}
	}											
	if($media_type=="cams"){
		$search_db =  $s_array;
	}
	foreach($xxx_phrase_db as $n) {
		if($media_type=="video" || $media_type=="movies"){
			$search_db[] =  $s_array[$n] . "|" . $n;
		}	
	}
	foreach($xxx_db as $n) {
		if($media_type=="video" || $media_type=="movies"){
			$search_db[] =  $s_array[$n] . "|" . $n;
		}
	}



	return $search_db;
}

function makepage() {
	global $xmlparse,$all_feeds,$all_cams,$all_movies,$media_type,$checkfeed,$sidebar_float;
	global $p_start, $p_end,$model_thbcells, $active_feeds,$update_feeds_url,$thumbs_per_page,$total_item_count,$run_test_themes;
	global $movie_pages,$feed_nice_name,$search_db,$words,$doingsearch, $site_directory, $lks, $use_sidebar,$clean_req,$theme,$template,$pgn_currentPage,$mndx;
	global $mix_all_feeds,$allmodel_array,$single_feed_mode;
	$p_diff = 0;
	if(!empty($clean_req['page'])) {
		$p_start = clean_int($clean_req['page']);
		$p_start = 	$p_start - 1;
		$p_start = 	$p_start * $thumbs_per_page;
		if($p_start<0){$p_start=0;}
		$p_end = $p_start+$thumbs_per_page;
		$pgn_currentPage = $clean_req['page'];
	}
	else {
		$p_start = 0;
		$p_end = $thumbs_per_page;
		$pgn_currentPage = 1;
	}
/// limit number of models to under 10000
	if($p_end> 9999) {
		$p_end = 9999;
	}
	if ((!empty($mix_all_feeds) && count($mix_all_feeds) > 0) && ($clean_req['media_type'] == 'cams') && !$single_feed_mode ) {
		$cf = "allcams";
	}else{
		foreach($active_feeds as $k => $v) {
			$cf = $k;
		}
	}
	if( (!empty($clean_req['db'])) && (!empty($clean_req['search'])) ){
		if ($clean_req['media_type'] == 'cams') {
			$xmlparse["$cf"] = $search_db;
		}
		if ($clean_req['media_type'] == 'video') {
			$xmlparse["$cf"] = $model_thbcells;
		}
		$p_diff = $p_end - $total_item_count;
	} 
	if( ($clean_req['media_type'] == 'cams') && in_array($clean_req['db'],$all_feeds)) {  
		$in_file = __DIR__ . "/feeds/feed_". $cf . ".txt";
		$filename = $in_file;
		$handle = fopen($filename, "r");
		if (flock($handle,LOCK_EX)) {
			$xmlparse["$cf"] = fread($handle, filesize($filename));
			flock($handle,LOCK_UN);
		} else {
				echo "Error locking file! $in_file";
		}
		fclose($handle);
	 
		$tempmodels = array();
		if (!empty($clean_req['search'])) {
			$tempmodels = $allmodel_array;

		} else {
			$tempmodels = unserialize($xmlparse["$cf"]);
		}
		$total_item_count = count($tempmodels);
		if($p_end > $total_item_count){
			$p_diff = $p_end - $total_item_count;
			$p_end = $total_item_count;
		}
		for($x=$p_start;$x<$p_end;$x++) {
			$model_thbcells .= thbcell_html($tempmodels[$x]);
		}
		echo $model_thbcells;
		$model_thbcells = "";
	}
	
	if( ($clean_req['media_type'] == 'video') && in_array($clean_req['db'],$all_feeds) ) {  
			sponsorhostedvideo($clean_req['db']);
			echo $model_thbcells;
	}
	if($total_item_count < 1) {
		echo "<div class=\"pagenotfound\"> No more found</div>";
	}
	if($p_diff > $thumbs_per_page) {
		echo "<div class=\"pagenotfound\"> Current page numbers exceeded</div>";
	}
}//makepage

function sponsorhostedvideo($sponsor_nm) {
	global $xmlparse,$model_thbcells,$site_directory;
	global $p_start, $p_end, $total_item_count,$search_db,$clean_req, $doingsearch;
	if( empty($search_db) && !empty($clean_req['search']) ){return;}
	if(!empty($search_db)){
		$xmlmodelsarray = $search_db;
	} else {
		include("add_hosted_video.php");
	}
	if(!empty($xmlmodelsarray)){
	} else {
		return;
	}
	if(!empty($clean_req['page'])) {
		if($p_start>=count($xmlmodelsarray)){
			return;
		}
	}
	if($p_end>count($xmlmodelsarray)) {
		$p_end = count($xmlmodelsarray);
	}
	$t_ndx = 0;
	$npt = count($xmlmodelsarray);
	$npt--;
	$ordinator = get_ordinator($npt);
	for($x=$p_start;$x<$p_end;$x++) {
		$rsindx = (int)$ordinator[$x];
		$xmlmodels[] = $xmlmodelsarray[$rsindx];
		$trk_rsindx[] = $rsindx;
	$t_ndx++;
	if($t_ndx>900){echo "overflow!";exit();}
	}
	$zx=0;
	foreach($xmlmodels as $value) {
		$model_info = array();
		$df = explode("|", $value);
		$model_info['feed_name'] = $sponsor_nm;
		$model_info['sponsor'] = $df[0];
		$model_info['iframe_src'] = $df[1];
		$model_info['thumb'] = $df[2];
		$model_info['display_name'] = cleandisplayname($df[3]);
		$model_info['username'] = clean_username($df[3]);
		$model_info['site_link'] = $df[4];
		$model_info['topic'] = $df[6];
		$model_info['media_type'] = "movies";
		if ($doingsearch){
			$model_info['zx'] = $df[7];				
		} else {
			$model_info['zx'] = $trk_rsindx[$zx];
		}
	 	$allmodel_array[] = $model_info;
		$model_thbcells .=  thbcell_html($model_info);
	$zx++;
	}
	$total_item_count = count($xmlmodelsarray);
}//sponsorhostedvideo

function req($myURL) {
	$curl_handle=curl_init();
	curl_setopt($curl_handle,CURLOPT_URL,$myURL);
	curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,60);
	curl_setopt($curl_handle,CURLOPT_TIMEOUT,60);
	curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
	$buffer = curl_exec($curl_handle);
	curl_close($curl_handle);
	if (empty($buffer))
	{
	    return "ERROR";
	}
	else
	{
	    return $buffer;
	}
}
function cleanthumb($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_\-.\/=?:\&]/", "", $tag );
	return $tag;
}
function cleansub($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_\- ,.;#&]/", "", $tag );
	$tag=preg_replace("/http/i", "", $tag );
	return $tag;
}
function cleanname($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_\- ]/", "", $tag );
	$tag=preg_replace("/http/i", "", $tag );
	$tag=str_replace("[", "", $tag );
	$tag=str_replace("[", "", $tag );
	return $tag;
}
function cleanname_replace($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_\- ]/", "x", $tag );
	$tag=preg_replace("/http/i", "", $tag );
	return $tag;
}
function cleanname_search($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_ \-+]/", "", $tag );
	$tag=preg_replace("/http/i", "", $tag );
	return $tag;
}
function cleandisplayname($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_\&\#\- )(♈♉♊♋♌♍♎♏♐♑♒♓❤❥🍒🌺👽🍑💕👅🐰웃유♋☮✌☏☢☠✔☑♚▲♪✈⌚♥❣♂♀☿👍✍✉☣☤✘☒♛▼♫⌘⌛¡♡ღツ☼☁❅♾️✎©®™Σ✪✯☭➳Ⓐ✞℃℉°✿⚡☃☂✄¢€£∞✫★½☯✡☪☩☨☦✞✛✜✝✙✚†‡†☨✞✝☥☦☓☩☯☧☬☸✡♁✙♆⋆✢✣✤✥❋✦✧✩✰✪✫✬✭✮✯❂✡★✱✲✳✴✵✶✷✸✹✺✻✼❄❅❆❇❈❉❊☹☺☻웃♥유♥❤❥❣❦❧♡۵웃유ღ♋♂♀☿⚥♪♫♩♬♭♮♯°øⒶ☮✌☪⚔✡☭✯❢❣☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼#$()*+0123456789?@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñÑªº¿¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°√ⁿ²]/", " ", $tag );
	$tag=preg_replace("/http/i", "", $tag );
	return $tag;
}
function clean_tags($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_\- ]/", "", $tag );
	$tag=preg_replace("/http/i", "", $tag );
	return $tag;
}
function clean_basic($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_ ]/", "", $tag );
	$tag=preg_replace("/http/i", "", $tag );
	return $tag;
}
function clean_username($tag) {
	$tag=preg_replace("/[^a-zA-Z0-9_]/", "", $tag );
	$tag=preg_replace("/http/i", "", $tag );
	return $tag;
}
function clean_int($tag) {
	$tag=preg_replace("/[^0-9]/", "", $tag );
	return (integer)$tag;
}
function diesoft() {
exit(0);
}

function thbcell_html($model_info) {
	global $movie_join_link,$clean_req,$link_thumb_to_offsite_model_chat,$clean_req,$active_feeds;
	global $current_thumb_index,$p_start,$template,$site_directory,$template,$theme,$checkfeed,$desc_url_max_length,$extra_data;
	$cell = "";
	$site_link = "";
	$chtrm = "";
	$videopagelink = "";
	$model_info = $model_info;
	$thb = $model_info["thumb"];
	$mname = $model_info["username"];
	if(!empty($model_info["display_name"])) {
		$mname = $model_info["display_name"];
	}
	$sponsor = $model_info["sponsor"];
	$poster = $thb;
	if (!empty($model_info["feed_name"])) {
		$feed_name = $model_info["feed_name"];
		//$sponsor = "$feed_name";
		//$site_link = $movie_join_link[$feed_name];
		$videopagelink = $site_directory . "/video/" . $feed_name . "/clip/" . $model_info['zx'] . $theme;
	}
	if( !empty($model_info['media_type']) && $model_info['media_type'] == "video"      ) {
		$model_info['iframe_src'] = "";
	}
	if(!empty($model_info['iframe_src'])) {
		$chtrm = $model_info['iframe_src'];
	}else{$chtrm = "";}
	if (!empty($model_info['site_link'])){
		$site_link = $model_info['site_link'];
	}
	if( !empty($model_info['media_type']) && $model_info['media_type'] == "movies"      ) {
		$chtrm = $model_info['iframe_src'];
	}

	
	$desc_url = !empty($model_info['topic']) ? $model_info['topic'] : "";

	if($desc_url == ""){$desc_url = !empty($model_info['turns_off']) ? $model_info['turns_off'] : "";}
	if($desc_url == ""){$desc_url = !empty($model_info['turns_on']) ? $model_info['turns_on'] : "";}
	if($desc_url == ""){$desc_url = !empty($model_info['biography']) ? $model_info['biography'] : "";}
	if($desc_url == "" && !empty($model_info['tags'])){
				$desc_url = implode(" ",$model_info['tags']);
	}

	/*$desc_url = clean_basic($desc_url);
	$temp_arry = array();
	$temp_arry = explode(" ", $desc_url);
	$desc_url = implode("-", $temp_arry);
	$desc_url = str_replace("--", "-", $desc_url);
	$desc_url = str_replace("-_", "-", $desc_url);
	$desc_url = str_replace("_-", "-", $desc_url);
	$desc_url = str_replace("__", "_", $desc_url);	
	$desc_url = str_replace("--", "-", $desc_url);
	*/
	
	
	$desc_url = strtolower($desc_url);
	$desc_url = str_replace(".com", "", $desc_url);
	$desc_url = clean_basic($desc_url);
	$temp_arry = array();	
	$desc_url = str_replace("_", " ", $desc_url);
	$desc_url = str_replace("  ", " ", $desc_url);
	$desc_url = trim($desc_url);
	$temp_arry = explode(" ", $desc_url);
	$desc_url = implode("-", $temp_arry);
	
	
	
	
	
	
	$desc_url = substr($desc_url, 0, $desc_url_max_length);
	$temp_arry = explode("-",$desc_url);
	array_pop($temp_arry);
	$desc_url = implode("-",$temp_arry);
	
	
	if(!empty($desc_url)){$desc_url = "/" . $desc_url;}
		
	$current_thumb_index++;
	$use_thumbnail_modal = "no";
	if ($use_thumbnail_modal == "yes") {
		include(__DIR__ ."/themes/$template/thumbnail_modal.php");	
	}else {
		include(__DIR__ ."/themes/$template/thumbnail.php");
	}
	if( !empty($model_info['media_type']) && ($model_info['media_type'] == "movies" || $model_info['media_type'] == "video")      ) {
		return $this_video;
	} else	if (in_array($model_info['sponsor'],$link_thumb_to_offsite_model_chat)) {
		return $cell;
	}else{
		return $this_thb;
	}
}

function get_ordinator($npt) {

	if($npt < 0) {return;}

	$number = floor($npt / 100) * 100;
	$ac = $npt % 100;
	$number++;
	$ord_file = "ord_" . $number;
	$ord_file_path = __DIR__ . "/ordinator/" . "$ord_file" . ".txt";
	$this_ord = @file_get_contents($ord_file_path);
	$ordinatorx = explode("\n", $this_ord);
	if($number == 1){
		$ordinatory = $ordinatorx[$npt];
	} else {
		$ordinatory = $ordinatorx[$ac];
	}
	$ordinator = explode(",",$ordinatory);
	return $ordinator;
}


function search_active_feed($info){
	global $words,$clean_req;
	$xxx_phrase_db = array();
	$temp = array();

	if (!empty($clean_req['words'])) {
		$clean_req['words'] = trim($clean_req['words']);
	}	
	
	if (!empty($clean_req['words'])) {
		$words = explode("-", $clean_req['words']);
	} else {
		if (strpos($clean_req['search'], "-") !== false){
				$words = explode("-", $clean_req['search']);
		}else{
				$words = explode(" ", $clean_req['search']);
		}
	}
	$tmx = "";
	foreach($info as $k=>$v) {
		if ($k != "tags"){
			$tmx .= $v;
		}
	}
	if(!empty($info['tags'])){

		foreach($info['tags'] as $t){
			$tmx .= $t;
		}
	}
	$jwords = implode("", $words);
	if(  (count($words) > 10) || (strlen($jwords) > 120)    ){
		echo "ERROR : Search too long"; 
		exit(0);
	}
	foreach($words as $wd){

		if (!empty($wd)){
			if (stripos($tmx, $wd) !== false) {return true;}
		}
	}
}

function modelpage($mn) {
	global $site_title,$template,$site_directory,$media_type,$checkfeed,$sponsor_cmp,$all_feeds,$clean_req,$extra_data,$use_sidebar,$sidebar_float,$modelisoffline;
	global $run_test_themes,$allowed_themes,$theme,$mndx,$num_related_models,$page_model,$related_model,$xmlparse,$musername,$this_iframe;
	global $active_feeds,$link_thumb_to_offsite_model_chat;
	global $doingsearch,$cam_site_names,$thumbs_per_page,$total_item_count,$pgn_currentPage;
	$use_sidebar = "no";
	$musername = $mn;
	$extra_data=$extra_data;
	if(!empty($clean_req['db'])){
		 $clean_req['media_type'] = "cams";
		 $feed = $clean_req['db'];
	}	
	if (in_array($feed,$all_feeds)) {
		$aok = 1;
	} else {
		return;
	}			
	//$num_related_models = 6;
	$model_info = array();
	$tags =  array();
	$in_file = __DIR__ . "/feeds/modelndx_". $feed . ".txt";
	$filename = $in_file;
	$handle = fopen($filename, "r");
	if (flock($handle,LOCK_EX)) {
		$modelndx = fread($handle, filesize($filename));
		flock($handle,LOCK_UN);
	} else {
			echo "Error locking file! $in_file";
	}
	fclose($handle);
	$mndx = unserialize($modelndx);
	
	if(isset($mndx[$musername])){

	}else {
		$modelisoffline = "<span class=modelisoffline>This model is on break now. <br>Please try later.</span>";	
	}	
	
	
	
	$in_file = __DIR__ . "/feeds/feed_". $feed . ".txt";
	$filename = $in_file;
	$handle = fopen($filename, "r");
	if (flock($handle,LOCK_EX)) {
		$xmlparse["$feed"] = fread($handle, filesize($filename));
		flock($handle,LOCK_UN);
	} else {
			echo "Error locking file! $in_file";
	}
	fclose($handle);
	
	if(isset($mndx[$musername])){
		parse_feed($feed,'modelpage');
	}
	
	
	if(empty($page_model['username'])){
		$modelisoffline = "<span class=modelisoffline>This model is offline now. <br>Please try later.</span>";
	}
	if (!empty($page_model['sponsor']) && in_array($page_model['sponsor'],$link_thumb_to_offsite_model_chat)) {
		$modelisoffline = "<span class=modelisoffline>This model is offline now or is streaming on another network<br>Use search for model name.</span>";
	}
	
	if (isset($page_model['username'])) {
		$page_title = $page_model['username'];	
		$page_description = $page_model['topic'];
		$page_keywords = "";
		foreach($page_model['tags'] as $v){
			$page_keywords .= $v;
			$page_keywords .= ",";
		}
		$x = strlen($page_keywords);
		$page_keywords = substr($page_keywords,0,$x-1);
	}

	

	include(__DIR__ . "/themes/$template/header.php");	
	include(__DIR__ . "/themes/$template/modelpage.php");		
	include(__DIR__ . "/themes/$template/mid_page.php");
	include(__DIR__ . "/themes/$template/footer.php");
}//modelpage function

function videopage($clip){
	global $template,$site_directory,$site_title,$doingsearch,$clean_req,$all_feeds,$defaultvideopage,$mix_all_video;
	global $run_test_themes,$allowed_themes,$theme,$page_mode,$checkfeed,$use_sidebar,$sidebar_float,$cam_site_names,$thumbs_per_page,$total_item_count,$pgn_currentPage;
	$use_sidebar = "no";
	$tag_array = array();
	$clipout = "";
	if($clean_req['clip'] < 0){ echo "Invalid request 1 "; exit();}
	if($clean_req['clip'] > 9999){ echo "Invalid request 2 "; exit();}
	if(!is_numeric($clean_req['clip']) ){ echo "Invalid request 3 "; exit();}
	if(!empty($clean_req['db'])){
		 $clean_req['media_type'] = "video";
		 $media_type = 'video';
	}	

	if( !empty($clean_req['db']) && in_array($clean_req['db'],$all_feeds) ) { 
			if (!in_array($clean_req['db'], $all_feeds)) {
				$clean_req['db'] = "$defaultvideopage"; //default video page
			}
			if ($clean_req['db'] == "allmovies"){

				foreach($mix_all_video as $vds) {
					$inc_db = "hosted_video/" . $vds  . "_video" . "_hosted.php"; 
					include($inc_db);
				}
				$feed = "allmovies";
			} else {

				$inc_db = "hosted_video/" . $clean_req['db']  . "_video" . "_hosted.php"; 
				include($inc_db);
				$feed = $clean_req['db'];
			}
	} else {

		echo "<center><span class=\"pagenotfound\">Page not found</span></center>";
	}
	$num_related_models = 6;
	$sponsor_nm = $feed;
	include("add_hosted_video.php");
	$model_info = array();
	$sizx = count($xmlmodelsarray); 
	$sizx--;
	if($clean_req['clip'] > $sizx){ echo "Invalid request 4"; exit();}	
	$items = $clip + $num_related_models;
	$ndx = 0;	
	for($x=$clip;$x<=$items;$x++){
		$validclip = false;
		if($ndx == 0){
			$df = explode("|", $xmlmodelsarray[$clip]);
			$sponsor = $df[0];
			$vid = $df[1];
			$poster = $df[2];
			$display_name = cleandisplayname($df[3]);
			$page_title = clean_username($df[3]);
			$sitelink = $df[4];
			$temptags = $df[6];
			$tags = $df[6];
			$validclip = true;

			if (!empty($df[6])) {
				$temptags = $df[6];
				$temptags = strtolower($temptags);
				$temptags = str_replace(".com", "", $temptags);
				$temptags = clean_basic($temptags);
				$temp_arry = array();	
				$temptags = str_replace("_", " ", $temptags);
				$temptags = str_replace("  ", " ", $temptags);
				$temptags = trim($temptags);
				$tag_array = explode(" ", $temptags);

			}
		}else{
			if ($x > $sizx ) {
				if ($clip-$ndx > 0) {
					$clipout = $clip-$ndx;
					$df = explode("|", $xmlmodelsarray[$clipout]);
$sponsor = $df[0];
$model_info['sponsor'] = $sponsor;
					$validclip = true;
				}			
			} else {
				$clipout = $clip+$ndx;
				$df = explode("|", $xmlmodelsarray[$clip+$ndx]);
$sponsor = $df[0];
$model_info['sponsor'] = $sponsor;
				$validclip = true;
			}
		}	
		if ($validclip) {
			$model_info['feed_name'] = $sponsor_nm;
			$model_info['sponsor'] = $sponsor;
			$model_info['iframe_src'] = $sitelink;
			$model_info['username'] = clean_username($df[3]);
			$model_info['media_type'] = "movies";
			$model_info['zx'] = $clipout;		
			$model_info['thumb'] = $df[2];
			$model_info['vid'] = $df[1];
			$model_info['tags'] = array();
			$model_info['tags'] = $tag_array;
			$temptags = $df[6];
			$temptags = strtolower($temptags);
			$temptags = str_replace(".com", "", $temptags);
			$temptags = clean_basic($temptags);
			$temp_arry = array();	
			$temptags = str_replace("_", " ", $temptags);
			$temptags = str_replace("  ", " ", $temptags);
			$temptags = trim($temptags);
			$model_info['topic'] = $temptags;
			if($ndx == 0){
				$page_model = $model_info;
			}else{
				$related_model[] = $model_info;
			}
		}
		$ndx++;	
	}
	
	$page_title = $page_model['username'];	
	$page_description = $page_model['topic'];
	$topic = $page_model['topic'];
	$page_keywords = "";
	foreach($page_model['tags'] as $v){
		$page_keywords .= $v;
		$page_keywords .= ",";
	}
	$x = strlen($page_keywords);
	$page_keywords = substr($page_keywords,0,$x-1);	
	
	

	include(__DIR__ . "/themes/$template/header.php");	
	include(__DIR__ . "/themes/$template/videopage.php");	
	include(__DIR__ . "/themes/$template/mid_page.php");
	include(__DIR__ . "/themes/$template/footer.php");
}

function searchvids() {
	global 	$clean_req,$all_feeds,$defaultvideopage,$media_type,$search_db,$total_item_count,$p_start,$p_end,$allmodel_array,$model_thbcells;		
	$checkfeed = "no feed";
	if (!in_array($clean_req['db'], $all_feeds)) {
		$clean_req['db'] = "$defaultvideopage";
	}
	$sponsor_nm = $clean_req['db'];
	$clean_req['db'] = $clean_req['db'];
	include("add_hosted_video.php");

	$search_dbx = swmatch($xmlmodelsarray);
	$total_item_count = count($search_dbx);
	if($p_end>count($search_dbx)) {
		$p_end = count($search_dbx);
	}
	$t_ndx = 0;
	$npt = count($search_dbx);
	$npt--;
	$ordinator = get_ordinator($npt);
	for($x=$p_start;$x<$p_end;$x++) {
		$rsindx = (int)$ordinator[$x];
		$xmlmodels[] = $search_dbx[$rsindx];
		$trk_rsindx[] = $rsindx;
	$t_ndx++;
	if($t_ndx>9000){echo "overflow!";exit();}
	}
	$zx=0;

	if(empty($xmlmodels)) {
		$total_item_count = 0;
		return;
	}

	foreach($xmlmodels as $value) {
		$model_info = array();
		$df = explode("|", $value);
		$model_info['feed_name'] = $sponsor_nm;
		$model_info['sponsor'] = $df[0];
		$model_info['iframe_src'] = $df[1];
		$model_info['thumb'] = $df[2];
		$model_info['display_name'] = cleandisplayname($df[3]);
		$model_info['username'] = clean_username($df[3]);
		$model_info['site_link'] = $df[4];
		$model_info['topic'] = $df[6];
		$model_info['media_type'] = "video";
		if (count($df) > 7 && !empty($df[8])){ 
			$df[7] = $df[8];
		}
		$model_info['zx'] = $df[7];				
	 	$allmodel_array[] = $model_info;
		$model_thbcells .=  thbcell_html($model_info);
	$zx++;
	}
	//echo $model_thbcells;
	$total_item_count = count($search_dbx);
}

function searchcams() {
	global $checkfeed,$clean_req,$all_feeds,$allmodel_array,$thumbs_per_page;
	global $model_thbcells,$doingsearch,$feed,$active_feeds,$xmlparse,$thumbs_per_page;
	global $xmlparse,$mndx,$musername,$num_related_models,$sponsor_cmp,$page_model,$related_model,$xmlfile,$xmlmodels_names;
	global $p_start,$p_end,$total_item_count,$allowed_genders,$extra_data;
	if (!in_array($clean_req['db'], $all_feeds)) {
		$clean_req['db'] = $default_feed;
	}
	if (is_array($clean_req['db'])) {echo "\n"; exit();}
	$feed = $clean_req['db'];
	$checkfeed = $feed;
	$active_feeds=array($clean_req['db']=>"txt");
	$current_time = time();
	$inc_db = "feeds/feed_" . $clean_req['db'] . ".txt"; 
	$xmlparse[$feed] = @file_get_contents($inc_db);
	if(!empty($clean_req['page']) ){
		$pp=0;
		if(is_numeric($clean_req['page']) && $clean_req['page'] > 0){
			$pp = $clean_req['page'] - 1;
		}
		$p_start = $thumbs_per_page * $pp;
		$p_end=$p_start+$thumbs_per_page;
	}else {
		$p_start=0;
		$p_end=$p_start+$thumbs_per_page;
	}	
	$sponsorx = $feed;
	parse_feed($sponsorx,"searchcams");

}
function parse_feed($sponsorx,$parsemode) {
	global $xmlparse,$mndx,$musername,$num_related_models,$sponsor_cmp,$page_model;
	global $related_model,$xmlfile,$xmlmodels_names,$this_iframe,$total_item_count;
	global $p_start, $p_end,$allowed_genders,$extra_data,$allmodel_array;
	global $mnndx_all,$allcams,$xmlmodels_names_allcams,$xmlmodels_allcams,$search_db;
	global $model_thbcells;

	require(__DIR__ . "/parse_feeds/parse.php");	
}
function writetxtfile($out_file, $filedata) {
	$file = fopen("$out_file","w+");
	if (flock($file,LOCK_EX)) {
		fwrite($file,$filedata);
	  	fflush($file);
	  	flock($file,LOCK_UN);
	} else {
	 	 echo "Error locking file! $out_file";
	}
	fclose($file);	
}
function mult_req($urls) {

	// Initialize multi-curl session
	$mh = curl_multi_init();

	// Array of curl handles for each request
	$handles = array();

	// Create a curl handle for each request
	foreach ($urls as $name => $url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_multi_add_handle($mh, $ch);
		$handles[$name] = $ch;
	}

	// Execute the requests in parallel
	$running = null;
	do {
		curl_multi_exec($mh, $running);
	} while ($running > 0);

	// Get the responses for each request
	$responses = array();
	foreach ($handles as $name => $ch) {
		$responses[$name] = curl_multi_getcontent($ch);
		curl_multi_remove_handle($mh, $ch);
	}

	// Close the curl multi handle
	curl_multi_close($mh);

	return $responses;
}
function camframe() {

	global $clean_req;
	
	$mn = $clean_req['model_name'];
	$stripchat_id = $extra_data['stripchat_id'];
	
$camfrm=<<<CFM
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<style>
	.camdiv2 {display:inline-block;height:80%;max-width:48%;text-align:center;margin-right:auto;margin-left:auto;vertical-align:top;}
	.chatdiv2{display:inline-block;height:80%;max-width:48%;text-align:center;margin-right:auto;margin-left:auto;vertical-align:top;}
	.camdivcont {max-height:900px;}
	@media(max-width:500px) {
		.camdiv2 {display:block;max-width:80%;margin-right:auto;margin-left:auto;}
		.chatdiv2{display:block;max-width:80%;margin-right:auto;margin-left:auto;}
	}
</style>


<div class=camdivcont style="text-align:center;">
	<div class="camdiv2" id="player-container"></div>
	<div class="chatdiv2" id="chat-container"></div>
</div> 

 <!-- first of all, download script itself, id attribute is important -->
  <script
    id="SCChatScript"
    type="text/javascript"
    src="https://creative.rmhfrtnd.com/widgets/Chat/lib.js"
  ></script>


  <!-- finally, run the chat instance -->
  <script type="text/javascript">
    // 1. create chat instance

    const chat = new StripchatChat({
      modelName: "$mn",
      userId: "$stripchat_id",
      // ...any other Chat creative params
    });


    // 2. mount it on prepared container

    chat.mount(document.getElementById('chat-container')).then((app) => {
      // 3. use it

      /*
      app
        .setParams({ modelName: 'ANOTHER_MODEL_NAME' })
        .then(() => {
          // OK
        })
        .catch(() => {
          // Model must be perform private show right now, try later
        });
      */

      // 4. remove it

      // app.destroy();
    })

  </script>
  
   <!-- first of all, download script itself, id attribute is important -->
  <script
    id="SCPlayerScript"
    type="text/javascript"
    src="https://creative.rmhfrtnd.com/widgets/Player/lib.js"
  ></script>

  <!-- then put the container somewhere in your HTML -->
  <div id="player-container"></div>

  <!-- finally, run the player instance -->
  <script type="text/javascript">
    // 1. create player instance

    const player = new StripchatPlayer({
      modelName: "$mn",
      userId: "$stripchat_id",
      strict: 1,
      showModal: 'signup',
      autoplay: 'all',
    });


    // 2. mount it on prepared container

    player.mount(document.getElementById('player-container')).then((app) => {
      // 3. use it

      /*
      app
        .setParams({ modelName: 'ANOTHER_MODEL_NAME' })
        .then(() => {
          // OK
        })
        .catch(() => {
          // Model must be perform private show right now, try later
        });
      */

      // 4. remove it

      // app.destroy();
    })

  </script>

  </body>
  </html>
CFM;

echo $camfrm;
exit(0);

}
?>
