<?php
/* 
	Appointment: Просмотр страницы пользователей
	File: profile.php 
 
*/
if(!defined('MOZG'))
	die('Hacking attempt!');

if($ajax == 'yes')
	NoAjaxQuery();

$user_id = $user_info['user_id'];

if($logged){
	$id = intval($_GET['id']);
	$cache_folder = 'user_'.$id;

	//Читаем кеш
	$row = unserialize(mozg_cache($cache_folder.'/profile_'.$id));

	//Проверяем на наличие кеша, если нету то выводи из БД и создаём его 
	if(!$row){
		$row = $db->super_query("SELECT user_id, name_lastname, country_city, birthday, city, country, avatar, friends_num, following_num, wall_num, albums_num, last_visit, videos_num, privacy, gender, profile_delete, profile_baned_date, xfields, cover_image, cover_position FROM `".PREFIX."_users` WHERE user_id = '{$id}'");
		if($row){
			mozg_create_folder_cache($cache_folder);
			mozg_create_cache($cache_folder.'/profile_'.$id, serialize($row));
		}
		$row_online['last_visit'] = $row['last_visit'];
	} else 
		$row_online = $db->super_query("SELECT last_visit FROM `".PREFIX."_users` WHERE user_id = '{$id}'");

	//Если есть такой, юзер то продолжаем выполнение скрипта
	if($row){
		//Если удалена
		if($row['profile_delete']){
			$metatags['title'] = $row['name_lastname'];
			$user_speedbar = $row['name_lastname'];
			$tpl->load_template("profile_delete_all.tpl");
			$user_name_lastname_exp = explode(' ', $row['name_lastname']);
			$tpl->set('{name}', $user_name_lastname_exp[0]);
			$tpl->set('{lastname}', $user_name_lastname_exp[1]);
			$tpl->compile('content');
		//Если заблокирована
		} elseif($row['profile_baned_date'] >= $server_time OR $row['profile_baned_date'] == '0'){
			$metatags['title'] = $row['name_lastname'];
			$user_speedbar = $row['name_lastname'];
			$tpl->load_template("profile_baned_all.tpl");
			$user_name_lastname_exp = explode(' ', $row['name_lastname']);
			$tpl->set('{name}', $user_name_lastname_exp[0]);
			$tpl->set('{lastname}', $user_name_lastname_exp[1]);
			$tpl->compile('content');
		//Если все хорошо, то выводим дальше
		} else {
			$CheckBlackList = CheckBlackList($id);
			
			$privacy = xfieldsdataload($row['privacy']);
			
			$metatags['title'] = $row['name_lastname'];
			
			$user_name_lastname_exp = explode(' ', $row['name_lastname']);
			$country_city_exp = explode('|', $row['country_city']);

			//################### Друзья ###################//
			if($row['friends_num']){
				$sql_friends = $db->super_query("SELECT SQL_CALC_FOUND_ROWS tb1.friend_id, tb2.name_lastname, avatar FROM `".PREFIX."_friends` tb1, `".PREFIX."_users` tb2 WHERE tb1.user_id = '{$id}' AND tb1.friend_id = tb2.user_id  AND following = 0 ORDER by rand() DESC LIMIT 0, 6", 1);
				$tpl->load_template('profile_friends.tpl');
				foreach($sql_friends as $row_friends){
					$friend_info = explode(' ', $row_friends['name_lastname']);
					$tpl->set('{user-id}', $row_friends['friend_id']);
					$tpl->set('{name}', $friend_info[0]);
					$tpl->set('{last-name}', $friend_info[1]);
					if($row_friends['avatar'])
						$tpl->set('{ava}', $config['home_url'].'uploads/users/'.$row_friends['friend_id'].'/50_'.$row_friends['avatar']);
					else
						$tpl->set('{ava}', '{theme}/style/img//no_ava_50.png');
					$tpl->compile('all_friends');
				}
			}
			
			//################### Видеозаписи ###################//
			if($row['videos_num']){	
				//Настройки приватности
				if($user_id == $id)
					$sql_privacy = "";
				elseif($check_friend){
					$sql_privacy = "AND video_privacy regexp '[[:<:]](1|2)[[:>:]]'";
					$cache_pref_videos = "_friends";
				} else {
					$sql_privacy = "AND video_privacy = 1";
					$cache_pref_videos = "_all";
				}
				
				//Если страницу смотрит другой юзер, то считаем кол-во видео
				if($user_id != $id){
					$video_cnt = $db->super_query("SELECT COUNT(*) AS cnt FROM `".PREFIX."_videos` WHERE owner_user_id = '{$id}' {$sql_privacy}", false, "user_{$id}/videos_num{$cache_pref_videos}");
					$row['videos_num'] = $video_cnt['cnt'];
				}
					
				$sql_videos = $db->super_query("SELECT SQL_CALC_FOUND_ROWS id, title, add_date, comm_num, photo FROM `".PREFIX."_videos` WHERE owner_user_id = '{$id}' {$sql_privacy} ORDER by `add_date` DESC LIMIT 0, 2", 1, "user_{$id}/page_videos_user{$cache_pref_videos}");
				
				$tpl->load_template('profile_video.tpl');
				foreach($sql_videos as $row_videos){
					$tpl->set('{photo}', $row_videos['photo']);
					$tpl->set('{id}', $row_videos['id']);
					$tpl->set('{user-id}', $id);
					$tpl->set('{title}', stripslashes($row_videos['title']));
					$tpl->set('{comm-num}', $row_videos['comm_num'].' '.gram_record($row_videos['comm_num'], 'comments'));
					megaDate(strtotime($row_videos['add_date']), '');
					$tpl->compile('videos');
				}
			}

			//################### Загрузка стены ###################//
			if($row['wall_num'])
				include ENGINE_DIR.'/modules/wall.php';
			
			//################### Загрузка самого профиля ###################//
			$tpl->load_template('profile.tpl');

			$tpl->set('{user-id}', $row['user_id']);
			$tpl->set('{name}', $user_name_lastname_exp[0]);
			$tpl->set('{lastname}', $user_name_lastname_exp[1]);
			$author_info = explode(' ', $row['name_lastname']);
			$tpl->set('{gram-name}', gramatikName($author_info[0]));
			
			// FOLLOWERS
			$row_followers = $db->super_query("SELECT followers_num FROM `".PREFIX."_users` WHERE user_id = '{$id}'");
			if($row_followers['followers_num']){
				$tpl->set('{followers-num}', $row_followers['followers_num']);
			} else {
				$tpl->set('{followers-num}', '0');
			}
			$tpl->set('{friends-num}', $row['friends_num']); 
			$tpl->set('{online-friends-num}', $online_friends['cnt']);
			$tpl->set('{following-num}', $row['following_num']);
			$tpl->set('{videos-num}', $row['videos_num']);
			if($row['friends_num']){
				$tpl->set('{friends-right-num}', $row['friends_num'].' '.gram_record($row['friends_num'], 'friends'));
			} else {
				$tpl->set('{friends-right-num}', gram_record($row['friends_num'], 'friends'));
			}
			if($row['videos_num']){
				$tpl->set('{videos-right-num}', $row['videos_num'].' '.gram_record($row['videos_num'], 'videos')); 
			} else {
				$tpl->set('{videos-right-num}', gram_record($row['videos_num'], 'videos')); 
			}
			
			//Аватарка
			if($row['avatar']){
				$tpl->set('{avatar}', $config['home_url'].'uploads/users/'.$row['user_id'].'/120_'.$row['avatar']);
				$tpl->set('{mini-avatar}', $config['home_url'].'uploads/users/'.$row['user_id'].'/50_'.$row['avatar']);
				$tpl->set('{display-avatar}', 'style="display:block;"');
				$tpl->set('{display-avatar-no}', 'style="display:none;"');
				$tpl->set('{large-ava}', $row['avatar']);
			} else {
				$tpl->set('{avatar}', '/templates/Default/style/img/no_ava_200.png');
				$tpl->set('{mini-avatar}', '/templates/Default/style/img/no_ava_50.png');
				$tpl->set('{display-avatar}', 'style="display:none;"');
				$tpl->set('{display-avatar-no}', 'style="display:block;"');
				$tpl->set('{large-ava}', '/templates/Default/style/img/no_ava_500.png');
			}
			
			//Обложка
			if($row['cover_image']){
				
				$imgIsinfo = getimagesize(ROOT_DIR."/uploads/users/{$id}/{$row['cover_image']}");
				
				$tpl->set('{cover_image}', "/uploads/users/{$id}/{$row['cover_image']}");
				$tpl->set('{cover_height}', $imgIsinfo[1]);
				$tpl->set('{cover_uploaded}', 'style="display:none"');
				$tpl->set('cover_no_uploaded', 'style="display:block"');
				$tpl->set('{cover_change}', 'style="display:block"');
				$tpl->set('{cover_upload_button}', 'style="display:none"');
				$tpl->set('{cover_position}', 'style="top:-'.$row['cover_position'].'px;position:relative"');
				$tpl->set('{cover_pos}', $row['cover_position']);
				$tpl->set('[cover]', '');
				$tpl->set('[/cover]', '');

			} else {
				
				$tpl->set('{cover_image}', '');
				$tpl->set('{cover_height}', '');
				$tpl->set('{cover_uploaded}', 'style="display:none"');
				$tpl->set('{cover_no_uploaded}', 'style="display:none"');
				$tpl->set('{cover_change}', 'style="display:none"');
				$tpl->set('{cover_upload_button}', 'style="display:block"');
				$tpl->set('[cover]', '');
				$tpl->set('[/cover]', '');
				
			}
			
			//Страна и город
			$tpl->set('{country}', $country_city_exp[0]);
			$tpl->set('{country-id}', $row['country']);
			$tpl->set('{city}', $country_city_exp[1]);
			$tpl->set('{city-id}', $row['city']);
			
			if($row['city'] AND $row['country']){
				$tpl->set('[not-all-city]','');
				$tpl->set('[/not-all-city]','');
			} else 
				$tpl->set_block("'\\[not-all-city\\](.*?)\\[/not-all-city\\]'si","");
				
			if($row['country']){
				$tpl->set('[not-all-country]','');
				$tpl->set('[/not-all-country]','');
			} else 
				$tpl->set_block("'\\[not-all-country\\](.*?)\\[/not-all-country\\]'si","");	
			
			//День рождение
			$birthday = explode('-', $row['birthday']);
			$row['day'] = $birthday[2];
			$row['month'] = $birthday[1];
			$row['year'] = $birthday[0];
			
			if($row['day'] > 0 && $row['day'] <= 31 && $row['month'] > 0 && $row['month'] < 13){
				$tpl->set('[not-all-birthday]', '');
				$tpl->set('[/not-all-birthday]', '');
				
				if($row['day'] && $row['month'] && $row['year'] > 1929 && $row['year'] < 2012)
					$tpl->set('{birth-day}', langdate('j F Y', strtotime($row['year'].'-'.$row['month'].'-'.$row['day'])));
				else
					$tpl->set('{birth-day}', langdate('j F', strtotime($row['year'].'-'.$row['month'].'-'.$row['day'])));
			} else {
				$tpl->set_block("'\\[not-all-birthday\\](.*?)\\[/not-all-birthday\\]'si","");
			}
			
			 //################### Фотографии ################//
			 $photo_cnt = $db->super_query("SELECT COUNT(*) AS cnt FROM `".PREFIX."_photos` WHERE user_id = '{$id}' ", false);
			 if ($photo_cnt['cnt']){
				 $sql_photos_view = $db->super_query("SELECT * FROM `".PREFIX."_photos` WHERE user_id = '{$id}' ORDER BY id DESC LIMIT 3",1);
				 if($sql_photos_view){
					 foreach($sql_photos_view as $row_view_photos){
						 $photos_view_albums .= "<a onclick=\"Photo.Show(this.href); return false\" href=\"/photo{$row_view_photos['user_id']}_{$row_view_photos['id']}_{$row_view_photos['album_id']}\"><img style=\"margin-right:5px;\" src=\"/uploads/users/{$row_view_photos['user_id']}/albums/{$row_view_photos['album_id']}/180_{$row_view_photos['photo_name']}\" width=\"116\" ></a>";
					}
				} 
				$tpl->set('{photos}', $photos_view_albums); 
				$tpl->set('[photos]', '');
				$tpl->set('[/photos]', '');
				$tpl->set('{photos-num}', $photo_cnt['cnt']);
				$tpl->set('{photos-right-num}', $photo_cnt['cnt'].' '.gram_record($photo_cnt['cnt'], 'photos')); 
			} else {
				$photos_view_albums = '<br /><div class="info_center">No uploaded photos</div><br /><br />';
				$tpl->set('{photos}', $photos_view_albums); 
				$tpl->set('{photos-num}', '0');  
				 if($photo_cnt['cnt']){
					 $tpl->set('{photos-right-num}', $photo_cnt['cnt'].' '.gram_record($photo_cnt['cnt'], 'photos')); 
				 } else {
					 $tpl->set('{photos-right-num}', gram_record($photo_cnt['cnt'], 'photos')); 
				 }
			}
				
			//Делаем проверки на существования запрашиваемого юзера у себя в друзьяз, заклаках, в подписка, делаем всё это если страницу смотрет другой человек
			if($user_id != $id){
			
				//Проверка естьли запрашиваемый юзер в друзьях у юзера который смотрит стр
				if($check_friend){
					$tpl->set('[yes-friends]', '');
					$tpl->set('[/yes-friends]', '');
					$tpl->set_block("'\\[no-friends\\](.*?)\\[/no-friends\\]'si","");
				} else {
					$tpl->set('[no-friends]', '');
					$tpl->set('[/no-friends]', '');
					$tpl->set_block("'\\[yes-friends\\](.*?)\\[/yes-friends\\]'si","");
				}
				
				//Проверка естьли запрашиваемый юзер в закладках у юзера который смотрит стр
				$check_fave = $db->super_query("SELECT user_id FROM `".PREFIX."_fave` WHERE user_id = '{$user_info['user_id']}' AND fave_id = '{$id}'");
				if($check_fave){
					$tpl->set('[yes-favourites]', '');
					$tpl->set('[/yes-favourites]', '');
					$tpl->set_block("'\\[no-favourites\\](.*?)\\[/no-favourites\\]'si","");
				} else {
					$tpl->set('[no-favourites]', '');
					$tpl->set('[/no-favourites]', '');
					$tpl->set_block("'\\[yes-favourites\\](.*?)\\[/yes-favourites\\]'si","");
				}

				//Проверка естьли запрашиваемый юзер в подписках у юзера который смотрит стр
				$check_subscr = $db->super_query("SELECT user_id FROM `".PREFIX."_friends` WHERE user_id = '{$user_info['user_id']}' AND friend_id = '{$id}' AND following = 1");
				if($check_subscr){
					$tpl->set('[yes-following]', '');
					$tpl->set('[/yes-following]', '');
					$tpl->set_block("'\\[no-following\\](.*?)\\[/no-following\\]'si","");
				} else {
					$tpl->set('[no-following]', '');
					$tpl->set('[/no-following]', '');
					$tpl->set_block("'\\[yes-following\\](.*?)\\[/yes-following\\]'si","");
				}
				
				//Проверка естьли запрашиваемый юзер в черном списке
				$MyCheckBlackList = MyCheckBlackList($id);
				if($MyCheckBlackList){
					$tpl->set('[yes-blacklist]', '');
					$tpl->set('[/yes-blacklist]', '');
					$tpl->set_block("'\\[no-blacklist\\](.*?)\\[/no-blacklist\\]'si","");
				} else {
					$tpl->set('[no-blacklist]', '');
					$tpl->set('[/no-blacklist]', '');
					$tpl->set_block("'\\[yes-blacklist\\](.*?)\\[/yes-blacklist\\]'si","");
				}
				
			}
			
			//Если есть друзья то выводим
			if($row['friends_num']){
				$tpl->set('[friends]', '');
				$tpl->set('[/friends]', '');
				$tpl->set('{friends}', $tpl->result['friends']);
			} else
				$tpl->set_block("'\\[friends\\](.*?)\\[/friends\\]'si","");
			
			//Если есть видео то выводим
			if($row['videos_num'] AND $config['video_mod'] == 'yes'){
				$tpl->set('[videos]', '');
				$tpl->set('[/videos]', '');
				$tpl->set('{videos}', $tpl->result['videos']);
			} else
				$tpl->set('{videos}', '<br /><div class="info_center">No uploaded videos</div><br />');

			//Если есть друзья, то выводим
			if($row['friends_num']){
				$tpl->set('{friends}', $tpl->result['all_friends']);
			} else
				$tpl->set('{friends}', $tpl->result['all_friends']);
			
			//Если человек пришел после реги, то открываем ему окно загрузи фотографии
			if(intval($_GET['finish'])){
				$tpl->set('[finish-signup]', '');
				$tpl->set('[/finish-signup]', '');
			} else
				$tpl->set_block("'\\[finish-signup\\](.*?)\\[/finish-signup\\]'si","");
				
			//Показ скрытых текста только для владельца страницы
			if($user_info['user_id'] == $row['user_id']){
				$tpl->set('[owner]', '');
				$tpl->set('[/owner]', '');
				$tpl->set_block("'\\[not-owner\\](.*?)\\[/not-owner\\]'si","");
			} else {
				$tpl->set('[not-owner]', '');
				$tpl->set('[/not-owner]', '');
				$tpl->set_block("'\\[owner\\](.*?)\\[/owner\\]'si","");
			}
			
			//Стена
			$tpl->set('{records}', $tpl->result['wall']);

			if($user_id != $id){
				if($privacy['val_wall1'] == 3 OR $privacy['val_wall1'] == 2 AND !$check_friend){
					$cnt_rec = $db->super_query("SELECT COUNT(*) AS cnt FROM `".PREFIX."_wall` WHERE for_user_id = '{$id}' AND author_user_id = '{$id}' AND fast_comm_id = 0");
					$row['wall_num'] = $cnt_rec['cnt'];
				}
			}
			
			$row['wall_num'] = $row['wall_num'] ? $row['wall_num'] : '';
			if($row['wall_num'] > 10){
				$tpl->set('[wall-link]', '');
				$tpl->set('[/wall-link]', '');
			} else
				$tpl->set_block("'\\[wall-link\\](.*?)\\[/wall-link\\]'si","");
		
			if($row['wall_num'])
				$tpl->set('{posts-num}', $row['wall_num']);
			else {
				$tpl->set('{posts-num}', '0');
			}
			
			if($row['wall_num'])
				$tpl->set('{no-records}', 'style="display:none;"');
			else {
				$tpl->set('{no-records}', 'style="display:block";');
			}
			
			//Приватность сообщений
			if($privacy['val_msg'] == 1 OR $privacy['val_msg'] == 2 AND $check_friend){
				$tpl->set('[privacy-msg]', '');
				$tpl->set('[/privacy-msg]', '');
			} else
				$tpl->set_block("'\\[privacy-msg\\](.*?)\\[/privacy-msg\\]'si","");

			//Приватность стены
			if($privacy['val_wall1'] == 1 OR $privacy['val_wall1'] == 2 AND $check_friend OR $user_id == $id){
				$tpl->set('[privacy-wall]', '');
				$tpl->set('[/privacy-wall]', '');
			} else
				$tpl->set_block("'\\[privacy-wall\\](.*?)\\[/privacy-wall\\]'si","");
				
			if($privacy['val_wall2'] == 1 OR $privacy['val_wall2'] == 2 AND $check_friend OR $user_id == $id){
				$tpl->set('[privacy-wall]', '');
				$tpl->set('[/privacy-wall]', '');
			} else
				$tpl->set_block("'\\[privacy-wall\\](.*?)\\[/privacy-wall\\]'si","");

			//Приватность информации
			if($privacy['val_info'] == 1 OR $privacy['val_info'] == 2 AND $check_friend OR $user_id == $id){
				$tpl->set('[privacy-info]', '');
				$tpl->set('[/privacy-info]', '');
			} else
				$tpl->set_block("'\\[privacy-info\\](.*?)\\[/privacy-info\\]'si","");
			
			//ЧС
			if(!$CheckBlackList){
				$tpl->set('[blacklist]', '');
				$tpl->set('[/blacklist]', '');
				$tpl->set_block("'\\[not-blacklist\\](.*?)\\[/not-blacklist\\]'si","");
			} else {
				$tpl->set('[not-blacklist]', '');
				$tpl->set('[/not-blacklist]', '');
				$tpl->set_block("'\\[blacklist\\](.*?)\\[/blacklist\\]'si","");
			}

			//################### Обработка дополнительных полей ###################//
			$xfieldsdata = xfieldsdataload($row['xfields']);
			$xfields = profileload();
				
			foreach($xfields as $value){

				$preg_safe_name = preg_quote($value[0], "'");

				if(empty($xfieldsdata[$value[0]])){

					$tpl->copy_template = preg_replace("'\\[xfgiven_{$preg_safe_name}\\](.*?)\\[/xfgiven_{$preg_safe_name}\\]'is", "", $tpl->copy_template);

				} else {

					$tpl->copy_template = str_replace("[xfgiven_{$preg_safe_name}]", "", $tpl->copy_template);
					$tpl->copy_template = str_replace("[/xfgiven_{$preg_safe_name}]", "", $tpl->copy_template);

				}

				$tpl->copy_template = preg_replace( "'\\[xfvalue_{$preg_safe_name}\\]'i", stripslashes($xfieldsdata[$value[0]]), $tpl->copy_template);

			}
	
			$tpl->compile('content');
	
		}
	} else {
		msgbox('', $lang['no_upage'], 'info');
	}
	
	$tpl->clear();
	$db->free();
} else {
	msgbox('', $lang['not_logged'], 'info');
}
?>