<?php
if ( !defined( 'SMARTY_DIR' ) ) {
	include_once( 'init.php' );
}

if ($_SESSION['AdminId'] > 0) {

	header('location: admin/index.php');
	exit;
}


if ($_SESSION['UserId'] <= 0 && ($_GET['page'] == 'login' || !$_GET) &&  isset($_COOKIE[$config['cookie_prefix'].'osdate_info']) ) {

	$cookie = $_COOKIE[$config['cookie_prefix'].'osdate_info'];

	$_SESSION['txtusername'] = $cookie['username'];

	$_SESSION['txtpassword'] = $cookie['dir'] ;

	$_SESSION['rememberme'] = true;

	list($_SESSION['lookagestart'], $_SESSION['lookageend'])= split(':',$cookie['search_ages']);

	if ($cookie['username'] != "") {

		if ( !$_GET['errid'] ) {
			header("location: midlogin.php");
			exit;
		}
	}
}

if ( isset( $_GET['affid'] ) ) {

	$_SESSION['ReferalId'] = $_GET['affid'];

	if ( getenv( 'HTTP_CLIENT_IP' ) ){
		$userip = getenv( 'HTTP_CLIENT_IP' );
	}
	else if ( getenv( 'HTTP_X_FORWARDED_FOR' ) )	{
		$userip = getenv( 'HTTP_X_FORWARDED_FOR' );
	}
	else {
		$userip = getenv( 'REMOTE_ADDR' );
	}

	$count = $osDB->getOne( "select count(*) FROM ! where ip = ? and ip <> '' and affid = ?", array( AFFILIATE_REFERALS_TABLE, $userip, $_SESSION['ReferalId'] ) );

	if ( $count == 0 ) {
		$osDB->query( "INSERT INTO ! ( affid, userid, ip ) VALUES ( ?, '0', ? )", array( AFFILIATE_REFERALS_TABLE, $_SESSION['ReferalId'], $userip ) );
	}

}

if ($_GET['page'] == 'login' and $_GET['errid'] != '') {

	$t->assign ( 'login_error', get_lang('errormsgs',$_GET['errid']) );
}

if (!isset($_SESSION['lookagestart'])) {
	$_SESSION['lookagestart'] = $config['default_start_agerange'];
	$_SESSION['lookageend'] = $config['default_end_agerange'];
}

if( isset( $_GET['page'] ) ) {

	$siteurl = HTTP_METHOD . $_SERVER['SERVER_NAME'] . DOC_ROOT ;

	$psize = getPageSize();

	$t->assign ( 'psize',  $psize );

	$pageno = (int)$_REQUEST['pageno'];

	if( $pageno == 0 ) $pageno = 1;

	$upr = ($pageno * $psize )- $psize;

	$cpage = $pageno;

	$data = array();

	switch ($_GET['page']) {

		case 'stories':

			$temp =& $osDB->getAll( 'SELECT * FROM ! order by date desc', array( STORIES_TABLE ) );

			$reccnt = count($temp);

			$pages = ceil( $reccnt / $psize );

			if( $pages > 1 ) {
				$sql .= ' limit '.$upr.','.$psize;
				if ( $cpage > 1 ) {

					$prev = $cpage - 1;

					$t->assign( 'prev', $prev );

				}

				if ( $cpage < $pages ) {

					$next = $cpage + 1;

					$t->assign ( 'next', $next );

				}
				$temp = array_slice($temp,$upr,$psize);

			}

			$t->assign ( 'cpage', $cpage );

			$t->assign ( 'pages',  $pages );

			$t->assign ( 'reccount',  $reccount );

			foreach( $temp as $index => $row ) {

				$row['username'] = $osDB->getOne( 'SELECT username FROM ! where id = ?', array( USER_TABLE, $row[sender] ) );
				$row['text'] = stripslashes($row['text']);
				$arrtext = explode( ' ', $row[text], $config['length_story'] + 1 );
				$arrtext[ $config['length_story'] ] = '';
				$row['text'] = trim( implode( ' ', $arrtext ) ) . '...';
				$row['date'] = date( get_lang('DISPLAY_DATE_FORMAT'), $row[date] );

				$data []= $row;
			}
			$t->assign( 'lang', $lang );
			$t->assign ( 'data', $data );
			unset($data, $temp, $row);
			$t->assign('rendered_page', $t->fetch('allstories.tpl') );
			break;

		case 'allnews':

			$temp =& $osDB->getAll( 'SELECT * FROM ! order by date desc', array( NEWS_TABLE ) );

			$reccnt = count($temp);

			$pages = ceil( $reccnt / $psize );

			if( $pages > 1 ) {
				$sql .= ' limit '.$upr.','.$psize;
				if ( $cpage > 1 ) {

					$prev = $cpage - 1;

					$t->assign( 'prev', $prev );

				}

				if ( $cpage < $pages ) {

					$next = $cpage + 1;

					$t->assign ( 'next', $next );

				}
				$temp = array_slice($temp,$upr, $psize);
			}

			$t->assign ( 'cpage', $cpage );

			$t->assign ( 'pages',  $pages );

			$t->assign ( 'reccount',  $reccount );

			foreach( $temp as $index => $row ) {
				$row['date'] = date( get_lang('DISPLAY_DATE_FORMAT'), $row[date] );
				$arrtext = explode( ' ', stripslashes($row['text']), $config['length_story'] + 1);
				$arrtext[ $config['length_story'] ] = '';
				$row['text'] = trim(implode( ' ', $arrtext)) . '...';

				$data []= $row;
			}
			$t->assign( 'lang', $lang );

			$t->assign ( 'data', $data );
			unset($data, $temp, $row);
			$t->assign('rendered_page', $t->fetch('allnews.tpl') );
			break;

		case 'articles':

			$temp =& $osDB->getAll( 'SELECT * FROM ! order by dat desc', array( ARTICLES_TABLE ) );

			$reccnt = count($temp);
			$pages = ceil( $reccnt / $psize );
			if( $pages > 1 ) {
				if ( $cpage > 1 ) {

					$prev = $cpage - 1;

					$t->assign( 'prev', $prev );

				}

				if ( $cpage < $pages ) {

					$next = $cpage + 1;

					$t->assign ( 'next', $next );

				}
				$temp = array_slice($temp,$upr,$psize);
			}

			$t->assign ( 'cpage', $cpage );

			$t->assign ( 'pages',  $pages );

			$t->assign ( 'reccount',  $reccount );

			foreach( $temp as $index => $row ) {

				$row['dat'] = date( get_lang('DISPLAY_DATE_FORMAT'), $row['dat'] );
				$arrtext = explode( ' ', stripslashes($row['text']), $config['length_story'] + 1 );
				$arrtext[$config['length_story']] = '';
				$row['text'] = trim(implode( ' ', $arrtext)) . '...';

				$data []= $row;
			}
			$t->assign( 'lang', $lang );

			$t->assign ( 'data', $data );

			unset ($temp, $data, $row);

			$t->assign('rendered_page', $t->fetch('allarticles.tpl') );
			break;

		case 'showstory':

			$temp =& $osDB->getAll( 'SELECT * FROM ! where storyid = ?', array( STORIES_TABLE, $_GET['storyid'] ) );

			foreach( $temp as $index => $row ) {
				$row['username'] = $osDB->getOne( 'SELECT username FROM ! where id = ?', array( USER_TABLE, $row[sender] ) );

				$row['date'] = date( get_lang('DISPLAY_DATE_FORMAT'), $row[date] );
				$row['text'] = stripslashes($row['text']);

				$data []= $row;
			}
			$t->assign( 'lang', $lang );

			$t->assign ( 'data', $data );
			unset($data, $temp, $row);
			$t->assign('rendered_page', $t->fetch('fullstory.tpl') );
			break;

		case 'shownews':

			$temp =& $osDB->getAll( 'SELECT * FROM ! where newsid = ?', array( NEWS_TABLE, $_GET['newsid'] ) );

			foreach( $temp as $index => $row ) {
				$row['date'] = date(get_lang('DISPLAY_DATE_FORMAT'), $row[date] );
				$row['text'] = stripslashes($row['text']);
				$data []= $row;
			}
			$t->assign( 'lang', $lang );

			$t->assign ( 'data', $data );
			unset($data, $temp, $row);
			$t->assign('rendered_page', $t->fetch('fullnews.tpl') );
			break;

		case 'showarticle':
			$temp =& $osDB->getAll( 'SELECT * FROM ! where articleid = ?', array( ARTICLES_TABLE, $_GET['articleid'] ) );

			foreach( $temp as $index => $row ) {
				$row['dat'] = date( get_lang('DISPLAY_DATE_FORMAT'), $row[dat] );
				$row['text'] = stripslashes($row['text']);
				$data []= $row;
			}
			$t->assign( 'lang', $lang );

			$t->assign ( 'data', $data );
			unset($data, $temp, $row);
			$t->assign('rendered_page', $t->fetch('fullarticle.tpl') );
			break;

		case 'login':

			$t->assign('rendered_page', $t->fetch('login.tpl') );
			break;

		default:

			$row =& $osDB->getRow( 'SELECT * FROM ! where pagekey = ?', array( PAGES_TABLE, $_GET['page'] ) );

			if ( $row ) {
				$row['pagetext'] = str_replace('[Your Company]', $config['site_title'],stripslashes(stripslashes($row['pagetext'])));
				$index++;
			}
			$row['pagetext'] = str_replace("#CONTACTUS#",$siteurl.'feedback.php',$row['pagetext']);

			$row['pagetext'] = str_replace("#CANCEL#",$siteurl.'cancel.php',$row['pagetext']);
			$t->assign( 'lang', $lang );

			$t->assign ( 'data', $row );
			unset($row);
			$t->assign('rendered_page', $t->fetch('page.tpl') );
	}
}

if ( strlen( $_SERVER['QUERY_STRING'] ) <= 0 or $_SERVER['QUERY_STRING'] == 'affid='.$_GET['affid'] || $_SERVER['QUERY_STRING'] == 'lang='.$_GET['lang'] or(( $_GET['errid'] == NOT_YET_APPROVED or $_GET['errid'] == NOT_ACTIVE ) && $_SESSION['UserId'] > 0 ) ){

	$last_users = $config['no_last_new_users'];

	$list_newmembers_since_days = $config['list_newmembers_since_days'];

	if ($list_newmembers_since_days == '') $list_newmembers_since_days=0;

	$list_newmembers_since = strtotime("-$list_newmembers_since_days day",time());

	/* Modify the newest profile condition to be from last visit time if user is logged in */

	if ( $last_users > 0 ) {

		$newUsers =& $osDB->getAll( "SELECT *, floor((to_days(curdate())-to_days(birth_date))/365.25)  as age  FROM ! WHERE status in (?, ?)  and regdate >= ? ORDER BY regdate DESC LIMIT 0, $last_users", array( USER_TABLE , get_lang('status_enum','active'), 'active', $list_newmembers_since) );

		$list = array();

		foreach ($newUsers as $row) {

			/* Get countryname and statename */
			$row['statename'] = getStateName( $row['country'], $row['state_province']  );
			$row['countryname'] = getCountryName($row['country'] ) ;
			$list[] = $row;
		}

		$t->assign( 'users', $list );
		unset($newUsers, $list, $row);
	}

	if ($config['list_newmembers'] > 0) {
		/* Get list of latest 10 userid */

		$newUsersList =& $osDB->getAll( "SELECT id, username, allow_viewonline FROM ! WHERE status in (?, ?)  and regdate >= ? ORDER BY regdate DESC LIMIT 0,!", array( USER_TABLE, get_lang('status_enum','active'), 'active', $list_newmembers_since,$config['list_newmembers'] ));

		if (count($newUsersList) > 0) {
			$t->assign('newUsersList',$newUsersList);
		}
		unset($newUsersList);
	}

	if ($config['show_featured_profiles'] > 0 ) {

		$xid = ($_SESSION['UserId'] > 0)?$_SESSION['UserId']:'0';

		$list =& $osDB->getAll('select id, userid from ! where ? between start_date and end_date and req_exposures > exposures  and userid <> ? order by rand() limit 0, ! ', array( FEATURED_PROFILES_TABLE, time(), $xid,  $config['show_featured_profiles'] ) );

		$featured_profiles = array();

		foreach ($list as $usr) {

			$row =& $osDB->getRow('select *, floor((to_days(curdate())-to_days(birth_date))/365.25)  as age from ! where id = ? and status=?', array( USER_TABLE, $usr['userid'],'active' ) );

			if ($row){
				/* Get countryname and statename */
				$row['statename'] = getStateName( $row['country'], $row['state_province'] ) ;
				$row['countryname'] = getCountryName($row['country'] ) ;
				$featured_profiles[] = $row;
				$osDB->query('update ! set exposures = exposures + 1 where id = ?', array( FEATURED_PROFILES_TABLE, $usr['id'] ) );
			}
		}
		$t->assign('featured_profiles', $featured_profiles);
		unset($list, $featured_profiles, $row);

	}

	if ($_SESSION['UserId'] > 0 ) {

		/* Get some stats */

		$viewswinks_since_days = ($config['last_viewswinks_since']=='')?0:$config['last_viewswinks_since'];

		$viewswinks_since = strtotime("-$viewswinks_since_days day",time());

		if ($viewswinks_since > $_SESSION['lastvisit']) $viewswinks_since = $_SESSION['lastvisit'];

		if ($viewswinks_since < $_SESSION['regdate']) $viewswinks_since=$_SESSION['regdate'];

		$sql = 'select count(*) from ! where userid = ? and act_time >= ? and act = ?';

		$t->assign('profile_views', $osDB->getOne($sql, array( VIEWS_WINKS_TABLE, $_SESSION['UserId'], $viewswinks_since, 'V' ) ) );

		$t->assign('winks', $osDB->getOne($sql, array( VIEWS_WINKS_TABLE, $_SESSION['UserId'], $viewswinks_since, 'W' ) ) );

		$t->assign('new_messages', $osDB->getOne('select count(*) from ! where owner=? and recipientid = ? and flagread = 0 and folder = ?', array( MAILBOX_TABLE, $_SESSION['UserId'], $_SESSION['UserId'], 'inbox' ) ) );


		$usr = $osDB->getRow('select usr.levelend, usr.pictures_cnt, mem.name from ! usr, ! mem  where usr.id = ? and mem.roleid = usr.level', array(USER_TABLE, MEMBERSHIP_TABLE, $_SESSION['UserId']) );

		$levelend = $usr['levelend'];

		$end_date = strftime($lang['DATE_FORMAT'],$levelend);

		$t->assign('curlevel', $usr['name']);

		$diff=$levelend - (time()+0);

		$bal_days = round($diff/86400,0);

		if ($bal_days == -0) $bal_days=0;

		$t->assign('bal_days', $bal_days );

		$t->assign('end_date', $end_date );

		$t->assign('viewswinks_since', strftime($lang['DATE_FORMAT'],$viewswinks_since));

	}

	$t->assign('rendered_page', $t->fetch('homepage.tpl') );
}

if ($_GET['errid'] != '') {

	$t->assign('errid_message', get_lang('errormsgs',$_GET['errid']) );

	$_GET['errid_message'] = urlencode(get_lang('errormsgs',$_GET['errid']));
}

$lang['DATE_FORMAT'] = get_lang('DATE_FORMAT');

$t->assign('lang', $lang);

$t->display( 'index.tpl' );

exit();
?>