<?php
/**
* User profile page management (general, description, self-portrait, desired partner criteria, multimedia album, rating, tags...)
*
*
* @package DatingPro
* @subpackage User Mode
**/
include_once "./include/config.php";
include_once "./include/config_index.php";
include_once "./common.php";
include_once "./include/class.lang.php";
include_once "./include/class.percent.php";
include_once "./include/class.images.php";
include_once "./include/class.news.php";
include_once "./include/functions_index.php";
include_once "./include/functions_auth.php";
include_once "./include/functions_users.php";
include_once "./include/class.phpmailer.php";
include_once "./include/functions_mail.php";

include_once('./include/getid3/getid3.php');
include_once('./include/class.utf8.php');

$from_uploadify = (isset($_REQUEST['from_uploadify'])) ? intval($_REQUEST['from_uploadify']) : 0;
if($from_uploadify){
	$session_name = (isset($_REQUEST['session_name']) && $_REQUEST['session_name']) ? $_REQUEST['session_name'] : '';
	if($session_name == session_name()){
		$session_id = (isset($_REQUEST['session_id']) && $_REQUEST['session_id']) ? $_REQUEST['session_id'] : '';
		session_id($session_id);
		session_start();
	}
}
$user = auth_index_user();
RefreshAccount($user);
$smarty->assign("sub_menu_num", '2');
$smarty->assign("group_adult_allow", CheckAdultAllow());

if ($user[4] == 1) {
	echo "<script>location.href='" . $config["site_root"] . "/admin/index.php'</script>";
}

if(!$user[0])	////// if user not registered
	header("location: ".seo("index", 1));

/*if(!$user[8])	////// if user status = 0
	header("location: ".seo("account", 1));*/

IsFileAllowed($user[0], GetRightModulePath(__FILE__));

$PHPmailer = new PHPMailer();

$multi_lang = new MultiLang($config, $dbconn);
///// default multilanguage field for select
$field_name = $multi_lang->DefaultFieldName();

$profile_percent2 = new PercentNew($config, $dbconn, $user[0]);
GetBirthdays($user);
if ($settings["use_horoscope_feature"]) GetHoroscopeList();
///// check ins messages if user not guest
if($user[3] != 1){
	GetAlertsMessage();
	SetModuleStatistic(GetRightModulePath(__FILE__));
}

$smarty->assign("myprofile_label", 1);

GoogleAnalytics($config["google_analytics_activate"], $config["manual_tracker_activate"]);
GetPhoneUser();

$sel = isset($_POST["sel"]) ? $_POST["sel"] : (isset($_GET["sel"]) ? $_GET["sel"] : "");
$act = isset($_GET["act"]) ? $_GET["act"] : "";
$edit = isset($_GET["edit"]) ? 1 : 0;
if ($sel == "4"){
    $smarty->assign("my_left_menu", LeftNavigation("profile", $lang["left_menu"]["uploads"]));
}else{
    $smarty->assign("my_left_menu", LeftNavigation("profile", $lang["left_menu"]["overview"]));
    }
switch($sel){
	case "1": ShowAll(1); break;
	case "2": ListProfile(2,$act); break;
	case "3": ListProfile(3,$act); break;
	case "4": ListProfile(4,$act); break;
	case "5": ListProfile(5,$act); break;
	case "6": ListProfile(6,$act); break;

	case "edit_1": EditProfile(1); break;
	case "edit_2": EditProfile(2); break;
	case "edit_3": EditProfile(3); break;
	case "edit_4": EditProfile(4); break;
	case "edit_5": EditProfile(5); break;
	case "edit_6": EditProfile(6); break;
	case "edit_7": EditProfile(7); break;
	case "edit_8": EditProfile(8); break;

	case "save_1": SaveProfile(1); break;
	case "save_2": SaveProfile(2); break;
	case "save_3": SaveProfile(3); break;
	case "save_4": SaveProfile(4); break;
	case "save_5": SaveProfile(5); break;
	case "save_6": SaveProfile(6); break;
	case "save_7": SaveProfile(7); break;
	case "save_8": SaveProfile(8); break;
	case "save_9": SaveProfile(9); break;

	case "upload_del":	UploadDelete(); break;
	case "upload_view":	UploadView(); break;
	case "ajax_image":	UploadView('ajax'); break;

	case "addtag": 		AddTag(); break;
	case "deltag": 		DeleteTag(); break;

	case "couple": 		AcceptCouple(); break;

	case "save_album":		SaveAlbum(); break;
	case "del_album":		DeleteAlbum(); break;
	case "get_album_form":	ShowAlbumForm(); break;
	case "edit_album_form": ShowAlbumForm('edit'); break;
	case "get_item_form":	ShowItemForm(''); break;
	case "edit_item_form":	ShowItemForm('edit'); break;

	case 'crop' :				CropPhoto($_REQUEST["photo_crop"]); break;
	case 'save_crop' :			SaveCropPhoto($_REQUEST["photo_path"]); break;
	
	case 'vote' :				VotePhoto(); break;
	case 'start_play':			StartAudioPlaying(); break;
	case 'start_slide':			StartSlideShow(); break;
	case 'start_video':			StartVideoPlaying(); break;
	case 'change_photo_par':    ChangePhotoPar();  break;
	case 'set_comment':			SetComment(); break;
	case 'get_comments':		GetComments();  break;
	case 'add_owner_comment':	AddOwnerComment(); break;
	case 'delete_owner_comment': DeleteOwnerComment(); break;
	case 'set_description_photo':SetDescriptionPhoto();  break;
    case 'delete_upload_comment': DeleteUploadComment(); break;
    case "kiss":  		$res = SendKiss(); ListProfile(5,"",$res["err"]); break;
	
	case "make_main": MakeMainPhoto(); break;
	
	default:
        if($edit) ListProfile(1); 
        else ListProfile(5); 
		break;
}

function AddOwnerComment(){
	global $dbconn, $user, $smarty, $config, $lang;
	
	$ret = PostComment(intval($user[0]), $_POST["message"]);
	if($ret != ""){
		echo "error";
		exit;
	}
	
	VotingTable($user[0], "", 1, "myprofile");
	$smarty->assign("button", $lang["button"]);
	$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_comment.tpl");
}

function DeleteOwnerComment(){
	global $dbconn, $user;
	$id = intval($_POST["comment_id"]);
	if($id == 0){
		echo "ERROR";
		exit;
	}
	$strSQL = "SELECT id_user FROM ".USER_COMMENT_TABLE." WHERE id='{$id}';";
	$rs = $dbconn->Execute($strSQL);
	$id_owner = intval($rs->fields[0]);
	if($id_owner == 0 || $id_owner != $user[0]){
		echo "ERROR";
		exit;
	}
	$strSQL = "DELETE FROM ".USER_COMMENT_TABLE." WHERE id='{$id}';";
	$dbconn->Execute($strSQL);
}

function DeleteUploadComment(){
    global $dbconn, $user;
    
    $id = intval($_POST["comment_id"]);
	if($id == 0){
		echo "ERROR";
		exit;
	}
	$strSQL = "SELECT id_user FROM ".USER_UPLOAD_COMMENTS_TABLE." WHERE id_comment='{$id}';";
	$rs = $dbconn->Execute($strSQL);
	$id_owner = intval($rs->fields[0]);
	if($id_owner == 0 || $id_owner != $user[0]){
		echo "ERROR";
		exit;
	}
	$strSQL = "DELETE FROM ".USER_UPLOAD_COMMENTS_TABLE." WHERE id_comment='{$id}';";
	$dbconn->Execute($strSQL);
    
}

function ShowAll($act, $standalone = 1){
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $profile_percent2, $charset, $lang_code, $lang_file;
	$file_name = seo('myprofile', 1);

	$id = $user[0];
	Banners(GetRightModulePath(__FILE__));
	IndexHomePage();
	LeftMenu();
	$smarty->assign("active_user_info", GetActiveUserInfo($user));
	GeneralTable();

	$strSQL = "SELECT couple FROM ".USERS_TABLE. " WHERE id='{$user[0]}';";
	$rs = $dbconn->Execute($strSQL);
	$couple = $rs->fields[0];

	$menu[1] = $file_name."?sel=1";
	$menu[2] = $file_name."?sel=2";
	$menu[3] = $file_name."?sel=3";
	$menu[4] = $file_name."?sel=4";
	$menu[5] = $file_name."?sel=5";
	$menu[6] = $file_name."?sel=6";
	$menu['blog'] = seo("blog", 1);
	$menu['account'] = seo("account", 1);
	$menu['lift_up'] = seo('payment', 1).'?sel=service&service=lift_up';
	$menu['edit'] = seo('payment', 1).'?sel=service&service=lift_up';
	$menu['edit_profile'] = seo("registration", 1);
	$menu['edit_profile'] .= '?sel=1';

	$links["edit_link_1"] = $file_name."?sel=edit_1";
	$links["edit_link_2"] = $file_name."?sel=edit_2";
	$links["edit_link_3"] = $file_name."?sel=edit_3";
	$links["edit_link_4"] = $file_name."?sel=edit_4";
	$links["edit_link_5"] = $file_name."?sel=edit_5";
	$links["edit_link_6"] = $file_name."?sel=edit_6";
	$links["edit_link_7"] = $file_name."?sel=edit_7";
	$links["edit_link_8"] = $file_name."?sel=edit_8";

	$smarty->assign("links", $links);
	$smarty->assign("menu", $menu);

	$smarty->assign("header", $lang["profile"]);
	$smarty->assign("button", $lang["button"]);
    if(isset($lang["alt"])){
		$smarty->assign("alt", $lang["alt"]);
    }
	$smarty->assign("script", "location");
	///////////////////

	$category = array();

	$strSQL = "SELECT id, name_for_lang, type, is_system, mandatory, position_text, elem_html, category, page_position, couple, tbl, val, page FROM ".ELEMENTS." WHERE page > 0 AND page_position > 0 ORDER BY page, page_position;";
	$rs = $dbconn->Execute($strSQL);
	$elements = array();
	if($rs->fields[0] != ""){
		$i = 0;
		while(!$rs->EOF){
			$elements[$i]["id"] = $rs->fields[0];
			$elements[$i]["name_for_lang"] = $rs->fields[1];
			$elements[$i]["type"] = $rs->fields[2];
			$elements[$i]["is_system"] = intval($rs->fields[3]);
			$elements[$i]["mandatory"] = intval($rs->fields[4]);
			$elements[$i]["position_text"] = $rs->fields[5];
			$elements[$i]["elem_html"] = $rs->fields[6];
			$elements[$i]["category"] = $rs->fields[7];
			if(!in_array($rs->fields[7], $category))
			$category[] = $rs->fields[7];
			$elements[$i]["page_position"] = $rs->fields[8];
			if($couple)
			$elements[$i]["couple"] = $rs->fields[9];
			else
			$elements[$i]["couple"] = 0;
			$elements[$i]["tbl"] = $rs->fields[10];
			$elements[$i]["val"] = $rs->fields[11];
			$elements[$i]["page"] = $rs->fields[12];
			$rs->MoveNext();
			$i++;
		}
	}

	foreach($category as $key => $value){ // Р С—РЎР‚Р ВµР С•Р В±РЎР‚Р В°Р В·РЎС“Р ВµР С� smarty Р С”Р С•Р Т‘ Р Р† РЎРЊР В»Р ВµР С�Р ВµР Р…РЎвЂљР В°РЎвЂ¦ Р Р† html
		switch($value){
			case "personal":
				PersonalTable();
				break; // --------------

			case "description":
				DescriptionTable();
				$cat[$value] = "data_2";
				break;
			case "personality":
				MyPersonalityTable();
				$cat[$value] = "data_4";
				break;

			case "portrait":
				MyPortraitTable();
				$cat[$value] = "data_5";
				break;

			case "interests":
				MyInterestsTable();
				$cat[$value] = "data_6";
				break;

			case "partner_criteria":
				MyCriteriaTable();
				$cat[$value] = "data_7";
				break;

			case "partner_interests":
				HisInterestsTable();
				$cat[$value] = "data_8";
				break;

			case "custom":
				CustomTable();
				$cat[$value] = "custom";
				break;
		}
	}

    $lang = $smarty->_tpl_vars["lang"];
    $lang = array_merge_recursive_simple($lang, GetLangContent("registration", $config['path_lang'].$lang_file[0], true));

    $smarty->assign("lang", $lang);
    $elements = GetViewForElements($elements, $cat, $couple);

	foreach ($elements as $key => $row) {
		$pages[$elements[$key]['page']] = "";
		$couples[$key] = $elements[$key]['couple'];
		if(!isset($uniq_page[$elements[$key]['page']]))
		$uniq_page[$elements[$key]['page']]["page"] = $elements[$key]['page'];
		$page[$key]  = $elements[$key]['page'];
		$page_position[$key] = $elements[$key]['page_position'];
	}
	$uniq_page[0]["percent"] = $profile_percent2->GetSectionPercent(0);
	foreach($uniq_page as $key => $value){
		if (isset($value["page"])){
			$uniq_page[$key]["percent"] = $profile_percent2->GetSectionPercent($value["page"]);
		}
	}
	$smarty->assign("percent", $uniq_page);

	array_multisort($page, SORT_ASC, $couples, SORT_ASC, $page_position, SORT_ASC, $elements);
	unset($page, $page_position, $pages);

	$form['page'] = 1;
	$smarty->assign("form", $form);
	$smarty->assign("active_user_info", GetActiveUserInfo($user));
	$smarty->assign("elements", $elements);

	header('Content-type: text/html; charset='.$charset);
	$smarty->assign("template_root", $config["index_theme_path"]);
	$smarty->assign("template_css_root", $config["index_theme_css_path"]);
	$smarty->assign("template_images_root", $config["index_theme_images_path"]);
    if($standalone){
		$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_view_new.tpl"); ///////////
	}
}

function recurr_strip_lang($in, $gl_out, &$out){
	foreach($in as $key=>$value){
		$tmp = $gl_out."[\"".$key."\"]";
		if(is_array($value)){
			recurr_strip_lang($value, $tmp, $out);
		}
		else{
			$out .= $tmp."='".stripslashes($value)."';\n";
		}
	}
}

function ListProfile($page=1, $act="", $err="", $sub_par="", $action="", $data=""){
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $profile_percent2, $charset, $default_left, $settings, $servers;
        $file_name = seo('myprofile', 1);
	if (isset($_REQUEST['first']) && $_REQUEST['first'] == 1) {
		$smarty -> assign('first',1);
	}

	cleanMailbox();

	//refresh percent
	$strSQL = "SELECT COUNT(DISTINCT(page)) FROM ".USER_PERCENT_TABLE." WHERE id_user='".$user[0]."'";
	$res = $dbconn -> Execute($strSQL);
	$percent_page = $res->fields[0];
	$strSQL = "SELECT COUNT(DISTINCT(page)) FROM ".ELEMENTS." WHERE name_for_lang!='_empty_field'";
	$res = $dbconn -> Execute($strSQL);
	$element_page = $res->fields[0];
	if ($element_page > $percent_page) {
		for($i=1;$i<$element_page;$i++){
			$profile_percent2->SetSectionPercent($i, $profile_percent2->CulcSectionPercent($i));
			$profile_percent2->RefreshAllPercent();
		}
	}
	//refresh percent
	
	////// if user status = 0
	if (!$user[8]) {
		$account_homepage["err"] = $lang["users"]["alert_header_status"];
		$strSQL = "select confirm from " . USERS_TABLE . " where id = '" . $user[0] . "'";
		$rs = $dbconn->Execute($strSQL);
		if (!$rs->fields[0]) {
			$form["err"] .= "<br>" . $lang["users"]["alert_header_confirm"];
			$smarty->assign("confirm_err", "1");
		}
		$smarty->assign("account_homepage", $account_homepage);
	}
	
	$id = $user[0];
	$smarty->assign('current_user_id', $id);
	if($config["use_default_smiles"]==1 ){
		$smarty->assign("smiles", $config["smiles"]);
	}else{
		$strSQL = "SELECT value, file, preg FROM ".SMILES."";
		$rs = $dbconn->Execute($strSQL);
		$smile = array();
		$i = 0;
			while(!$rs->EOF){
				$smile[$i]["value"] = $rs->fields[0];
				$smile[$i]["file"] = $rs->fields[1];
				$smile[$i]["preg"] = $rs->fields[2];
				$i++;
				$rs->MoveNext();
			}
		$smarty->assign("smiles", $smile);
	}
	$smarty->assign("use_default_smiles", $config["use_default_smiles"]);
	if ($act=="") {
		Banners(GetRightModulePath(__FILE__));
		IndexHomePage();	
		LeftMenu();
		$smarty->assign("active_user_info", GetActiveUserInfo($user));
		GeneralTable();
	}
	if ( isset($config['use_pilot_module_organizer']) && ( $config['use_pilot_module_organizer']==1 ) ) {
		$strSQL = "SELECT COUNT(*) FROM ".ORG_USER_LAYOUTS_TABLE." WHERE id_user='{$user[0]}' AND theme='{$config['color_theme']}';";
		$rs = $dbconn->Execute($strSQL);
		if ($rs->fields[0] > 0) {
			$file_name_1 = $config["index_theme_path"].$config['index_theme_css_path']."/users/color_def_".intval($user[0]).".css";
			if(file_exists($config["site_path"]."/".$file_name_1)){
				$smarty->assign("style", $file_name_1);
			}
		}		
		$strSQL = " SELECT id, area_1, area_2, area_3, area_4, area_5, area_6, area_7, area_8, area_9, area_10, area_11
				FROM " . ORG_USER_HOME_OPTIONS_TABLE . "
				WHERE id_user='" . $user[0] . "' AND theme='" . $config["color_theme"] . "'";
		$rs = $dbconn->Execute($strSQL);
		if ($rs->fields[0] > 0) {
			$org_home[0] = ($rs->fields[1] == 1) ? 'true' : 'false';	//Main profile block
			$org_home[1] = ($rs->fields[2] == 1) ? 'true' : 'false';	//ShoutBox
			$org_home[2] = ($rs->fields[3] == 1) ? 'true' : 'false';	//Account info
			$org_home[3] = ($rs->fields[4] == 1) ? 'true' : 'false';	//Carousel
			$org_home[4] = ($rs->fields[5] == 1) ? 'true' : 'false';	//Top members
			$org_home[5] = ($rs->fields[6] == 1) ? 'true' : 'false';	//News
			$org_home[6] = ($rs->fields[7] == 1) ? 'true' : 'false';	//Wall
			$org_home[7] = ($rs->fields[8] == 1) ? 'true' : 'false';	//General Description
			$org_home[8] = ($rs->fields[9] == 1) ? 'true' : 'false';	//Multimedia Gallery
			$org_home[9] = ($rs->fields[10] == 1) ? 'true' : 'false';	//Birthday
			$org_home[10] = ($rs->fields[11] == 1) ? 'true' : 'false';	//Horoscope
			
			if ($org_home[6] == 'false' && $act == "ajax") $page = $page;
			if ($org_home[6] == 'false' && $act != "ajax") $page = 1;
			if ($org_home[7] == 'false' && $org_home[6] == 'false') $page = 4;				
			if ($org_home[7] == 'false' && $org_home[6] == 'true' && $act == "ajax") $page = $page;
		} else {//				0		1		2		3		4		5		6		7		8		9		10		11
			$org_home = array('true', 'true', 'true', 'true', 'true', 'true', 'true', 'true', 'true', 'true', 'true', 'true');
		}		
		$smarty->assign("org_home", $org_home);
		$smarty->assign("hide", 1);
	}
	
	switch($page){
		case 1:
            ShowAll(1, 0);
			break;
		case 3:
			break;
		case 4:
			if ($sub_par=='') {
				if (isset($_GET["sub"])) {
					$sub_par = intval($_GET["sub"]);
				}
			}
			UploadTable($sub_par, $action, $data, $user[0]);
		case 5:
			VotingTable($id, 0, 0, "myprofile");
			TagsTable();
			
			include_once "./include/class.wall_events.php";
			$events = new WallEvents($user, $config, $settings, $dbconn, $lang, $servers);
			$events_arr = $events->GetUserEvents('my_wall');
			if(isset($events_arr['events'])){
				include_once "./include/class.comments.php";
				$comments = new Comments($user, $config, $settings, $dbconn, $smarty);
				foreach($events_arr['events'] as &$event_obj){
					if($event_obj['gid'] == 'wall'){
						$event_obj['comments_count'] = $comments->get_comments_count('wall', $event_obj['id']);
					}
				}
			}
			$smarty->assign('events', $events_arr);
			break;
	}
	if (isset($_REQUEST['profile_info_changed'])) {
		$strSQL = "SELECT profile_bad FROM " . USER_FACEBOOK_CONNECT . " WHERE id_user='" . $user[0] . "'";
		$profile_bad = $dbconn->GetOne($strSQL);
		if ($profile_bad) {
			$profile_bad_arr = explode(',', $profile_bad);
			$changed_fields_str = "";
			foreach($lang["sharing_tools"] as &$val){
				$val = str_replace('[provider]', 'Facebook', $val);
			}
			$lang['sharing_tools']['proile_bad_notice2'] = str_replace("[link]", $config['server']."/".seo('registration')."?sel=1&edit=1", $lang['sharing_tools']['proile_bad_notice2']);
			$smarty->assign("lang_sharing_tools", $lang['sharing_tools']);
			
			foreach ($profile_bad_arr as $val) {
				$changed_fields_str .= $lang["sharing_tools"]["proile_bad_" . $val] . "<br>";
			}
			$smarty->assign("changed_fields_str", $changed_fields_str);
			$smarty->assign("connector_gid", 'fb');
		}
	}
	if (isset($_REQUEST['vk_profile_info_changed'])) {
		$strSQL = "SELECT profile_bad FROM " . USER_VKONTAKTE_CONNECT . " WHERE id_user='" . $user[0] . "'";
		$profile_bad = $dbconn->GetOne($strSQL);
		if ($profile_bad) {
			$profile_bad_arr = explode(',', $profile_bad);
			$changed_fields_str = "<ul style='list-style: disc inside;'>";
			foreach($lang["sharing_tools"] as &$lang_val){
				$lang_val = str_replace('[provider]', 'Vkontakte', $lang_val);
			}
			$lang['sharing_tools']['proile_bad_notice2'] = str_replace("[link]", $config['server']."/".seo('registration')."?sel=1&edit=1", $lang['sharing_tools']['proile_bad_notice2']);
			$smarty->assign("lang_sharing_tools", $lang['sharing_tools']);

			foreach ($profile_bad_arr as $val) {
				$changed_fields_str .= "<li>" . $lang["sharing_tools"]["proile_bad_" . $val] . "</li>";
			}
			$changed_fields_str .= "</ul>";
			$smarty->assign("changed_fields_str", $changed_fields_str);
			$smarty->assign("connector_gid", 'vk');
		}
	}

	$form["page"] = intval($page);
	$form["err"] = $err;

	$menu[1] = $file_name."?sel=1";
	$menu[2] = $file_name."?sel=2";
	$menu[3] = $file_name."?sel=3";
	$menu[4] = $file_name."?sel=4";
	$menu[5] = $file_name."?sel=5";
	$menu[6] = $file_name."?sel=6";
	$menu['blog'] = seo("blog", 1);
	$menu['account'] = seo("account", 1);
	$menu['lift_up'] = seo('payment', 1).'?sel=service&service=lift_up';
	$menu['edit'] = seo('myprofile',1);
	$menu['edit_profile'] = seo("registration", 1);
	$menu['edit_profile'] .= '?sel=1&edit=1';

	$links["edit_link_1"] = $file_name."?sel=edit_1";
	$links["edit_link_2"] = $file_name."?sel=edit_2";
	$links["edit_link_3"] = $file_name."?sel=edit_3";
	$links["edit_link_4"] = $file_name."?sel=edit_4";
	$links["edit_link_5"] = $file_name."?sel=edit_5";
	$links["edit_link_6"] = $file_name."?sel=edit_6";
	$links["edit_link_7"] = $file_name."?sel=edit_7";
	$links["edit_link_8"] = $file_name."?sel=edit_8";
	$smarty->assign("links", $links);
	$smarty->assign("menu", $menu);
	$smarty->assign("form", $form);
	$smarty->assign("header", $lang["profile"]);
	$smarty->assign("button", $lang["button"]);
	$smarty->assign("script", "location");
	if (isset($data['sel']) && $data['sel']=="save_9"){ 
		$smarty->assign("save_9", "1"); 
		$smarty->assign("upload_type", $data['upload_type']); 
		$smarty->assign("id_item", $data["id_album"]);
		$smarty->assign("id_subitem", $data["id_subitem_new"]);
	}

	//Waiting for activation 
	$strSQL = "SELECT confirm, status FROM ".USERS_TABLE." WHERE id = ".$user[0];
	if ($rs = $dbconn->Execute($strSQL)){
		if ($rs->fields[0] == 0 || $rs->fields[1] == 0){
			$smarty->assign("wait_activate", 1);
		}
	}
	
	//// matches
	$strSQL = "	SELECT a.id, a.login, a.fname, a.sname, a.gender, a.date_birthday, uu.upload_path, uu.id as id_photo, a.id_country, a.id_city, a.id_region
				FROM " . USERS_TABLE . " a, " . USER_TOPTEN_TABLE . " b, 
				 ".USER_UPLOAD_TABLE." uu
				WHERE a.id=b.id_user AND a.status='1' AND uu.id=a.icon_path ORDER BY RAND() LIMIT 1";

	$rs = $dbconn->Execute($strSQL);
	$row = $rs->GetRowAssoc(false);
	$top_users["name"] = chooseUserName($row["login"], $row["fname"]." ".$row["sname"]) ;
	$top_users["age"] = AgeFromBDate($row["date_birthday"]);
	$top_users["link"] = seo("viewprofile", 1)."?id=" . $row["id"] . "&sel=5";
	$icon_path = $row["upload_path"] ? "thumb_".$row["upload_path"] : $settings['photos_default'];
	$icon_image = (strlen($row["upload_path"])) ? 1 : 0;
	//$dir = GetPath($row["id"], $settings["photos_folder"]);
	$dir = GetImagePath($row["id"], $row["id_photo"], $settings["photos_folder"]);
	if ($icon_path != $settings['photos_default'])
		$top_users["icon_path"] = $dir.$icon_path;
	else
		$top_users["icon_path"] = $config["server"].$config["index_theme_path"].$config["index_theme_images_path"] . "/" . $icon_path;
	$top_users["country"] = $dbconn->GetOne("SELECT name FROM " . COUNTRY_SPR_TABLE . " WHERE id='" . intval($row["id_country"]) . "'");
	$top_users["region"] = $dbconn->GetOne("SELECT name FROM " . REGION_SPR_TABLE . " WHERE id='" . intval($row["id_region"]) . "'");
	$top_users["city"] = $dbconn->GetOne("SELECT name FROM " . CITY_SPR_TABLE . " WHERE id='" . intval($row["id_city"]) . "'");

	$_LANG_NEED_ID["country"][] = intval($row["id_country"]);
	$_LANG_NEED_ID["region"][] = intval($row["id_region"]);
	$_LANG_NEED_ID["city"][] = intval($row["id_city"]);
	$smarty->assign("top_users", $top_users);
	
    $breadcrumbs = new BreadCrumbs();
    if ($page == "4")
        $breadcrumbs_file = "myprofile_album";
    elseif ($page == "1")
        $breadcrumbs_file = "myprofile_description";
    else
        $breadcrumbs_file = "myprofile";
    $breadcrumbs_page = $breadcrumbs->SetBreadCrumbs($breadcrumbs_file);
    if ($breadcrumbs_page)
        $smarty->assign("breadcrumbs_page", $breadcrumbs_page);
    
	$smarty->assign("left_news", HomepageNews());
	
	if ($act=="") {
		$uploads = getAllUploades();
	    $smarty->assign("uploades_icon", $uploads);	
		$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_table.tpl");
	} else {	    
		header('Content-type: text/html; charset='.$charset);

		$smarty->assign("template_root", $config["index_theme_path"]);
		$smarty->assign("template_css_root", $config["index_theme_css_path"]);
		$smarty->assign("template_images_root", $config["index_theme_images_path"]);
		$smarty->assign("settings", $settings);
  		$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_view.tpl");
	}
	exit;
}

/// --------------- Edit Profile Forms -------------------//
function EditProfile($num, $err=""){
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $multi_lang, $field_name, $profile_percent2;

	Banners(GetRightModulePath(__FILE__));
	LeftMenu();
	IndexHomePage();
	$id = $user[0];
	///// user info
	$file_name = seo('myprofile', 1);
	$smarty->assign("active_user_info", GetActiveUserInfo($user));
	
	if($num == '1'){
		$form = PersonalForm($multi_lang, $field_name);
		$form["menu"] = $file_name."?sel=1";
		$form["header"] = $lang["subsection"]["personal_info"];
	}elseif($num=='2'){
		$form = DescriptionForm($multi_lang, $field_name);
		$form["menu"] = $file_name."?sel=1";
		$form["header"] = $lang["subsection"]["description"];
	}elseif($num=='3'){
		$form = AnnonceForm($multi_lang, $field_name);
		$form["menu"] = $file_name."?sel=1";
		$form["header"] = $lang["subsection"]["notice"];
	}elseif($num=='4'){
		$form = MyPersonalityForm($multi_lang, $field_name);
		$form["menu"] = $file_name."?sel=2";
		$form["header"] = $lang["subsection"]["personal"];
	}elseif($num=='5'){
		$form = MyPortraitForm($multi_lang, $field_name);
		$form["menu"] = $file_name."?sel=2";
		$form["header"] = $lang["subsection"]["portreit"];
	}elseif($num=='6'){
		$form = MyInterestsForm($multi_lang, $field_name);
		$form["menu"] = $file_name."?sel=2";
		$form["header"] = $lang["subsection"]["interest"]." ( ".$lang["interests_opt"][1]." / ".$lang["interests_opt"][2]." / ".$lang["interests_opt"][3]." )";
	}elseif($num=='7'){
		$form = MyCriteriaForm($multi_lang, $field_name);
		$form["menu"] = $file_name."?sel=3";
		$form["header"] = $lang["subsection"]["criteria"];
	}elseif($num=='8'){
		$form = HisInterestsForm($multi_lang, $field_name);
		$form["menu"] = $file_name."?sel=3";
		$form["header"] = $lang["subsection"]["match_interest"]." ( ".$lang["interests_opt"][1]." / ".$lang["interests_opt"][2]." / ".$lang["interests_opt"][3]." )";
	}
	if (isset($_REQUEST["profile_bad"])){
		$bads = explode(',',$_REQUEST["profile_bad"]);
		foreach ($bads as $profile_error){
			$err = $lang["openid"]["err"][$profile_error].$err;
		}
	}
	$form["err"] = $err;
	$form["num"] = $num;
	$form["action"] = $file_name;
	$smarty->assign("form", $form);

	$smarty->assign("header", $lang["profile"]);
	$smarty->assign("alt", $lang["alt"]);
	$smarty->assign("script", "location");
	$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_edit.tpl");
}

/// --------------- Save Profile -------------------//
function SaveProfile($num){
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $multi_lang, $field_name, $profile_percent2, $IMG_TYPE_ARRAY, $AUDIO_TYPE_ARRAY, $VIDEO_TYPE_ARRAY, $from_uploadify;
	$id = intval($user[0]);
	$data = $_POST;
	$act = $sub_par = "";
	if($num == '1'){
		$err = SavePersonalForm($profile_percent2, $data);
		$page = 1;
	}elseif($num=='2'){
		$info = $_POST["info"];	$spr = $_POST["spr"];
		$err = SaveDescriptionForm($profile_percent2, $data, $spr, $info);
		if (intval($_POST["pair"]) == 1) {
			$info = $_POST["info_2"];	$spr = $_POST["spr_2"];
			$err = SaveDescriptionPairForm($profile_percent2, $data, $spr, $info);
		}
		$page = 1;
	}elseif($num=='3'){
		$err = SaveAnnonceForm($profile_percent2, $data);
		$page = 1;
	}elseif($num=='4'){
		$personal = $_POST["personal"]; $spr = $_POST["p_spr"];
		$err = SaveMyPersonalityForm($profile_percent2, $data, $spr, $personal);
		if (intval($_POST["pair"]) == 1) {
			$personal = $_POST["personal_2"]; $spr = $_POST["p_spr_2"];
			$err = SaveMyPersonalityPairForm($profile_percent2, $data, $spr, $personal);
		}
		$page = 1;
	}elseif($num=='5'){
		$portrait = $_POST["portrait"]; $spr = $_POST["port_spr"];
		$err = SaveMyPortraitForm($profile_percent2, $data, $spr, $portrait);
		$page = 1;
	}elseif($num=='6'){
		$interests = $_POST["interests"]; $spr = $_POST["int_spr"];
		$err = SaveMyInterestsForm($profile_percent2, $data, $spr, $interests);
		$page = 1;
	}elseif($num=='7'){
		$spr = $_POST["spr"]; $info = $_POST["info"];
		$err = SaveMyCriteriaForm($profile_percent2, $data, $spr, $info);
		$page = 3;
	}elseif($num=='8'){
		$interests = $_POST["interests"]; $spr = $_POST["int_spr"];
		$err = SaveHisInterestsForm($profile_percent2, $data, $spr, $interests);
		$page = 3;
	}elseif($num=='9'){
		$upload = $_FILES["upload"];
        $upload_allow = $_POST["upload_allow"];
        $upload_type = $_POST["upload_type"];
        $id_file = isset($_POST["id_file"]) ? $_POST["id_file"] : '';
		$data = $_POST;
		$data['id_album'] = isset($data['id_album']) ? intval($data['id_album']) : 0;
		$data['is_gallary'] = isset($data['is_gallary']) ? intval($data['is_gallary']) : 0;
		$data['categories'] = isset($data['categories']) ? intval($data['categories']) : 0;

		switch ($data['upload_type']) {
			case 'f':
				$sub_par = 8;
				break;
			case 'a':
				$sub_par = 9;
				break;
			case 'v':
				$sub_par = 10;
				break;
			case 'icon':
				$sub_par = 8;
				break;
			default:
				$sub_par = 8;
				break;
		}

		$err = '';
		$user_comment = stripn(FormFilter($_POST["user_comment"]));
		$upload_title = utf8_substr(stripn(FormFilter($_POST["upload_title"])), 0, 50);
		if(BadWordsCont($user_comment, 6)){
			$err = BadWordsCont($user_comment, 6);
		}elseif(check_filter($user_comment)){
			$err = $lang["err"]["info_finding_1"];
		}elseif(BadWordsCont($upload_title, 6)){
			$err = BadWordsCont($upload_title, 6);
		}elseif(check_filter($upload_title)){
			$err = $lang["err"]["info_finding_1"];
		}
		if(!$err){
			if($id_file && 'upload' == $data['type_use'] && !$upload["size"]){		//upload comments change
				$strSQL = "SELECT id_album FROM ".USER_UPLOAD_TABLE." WHERE id_user='".$id."' and id='".$id_file."'";
				$rs = $dbconn->Execute($strSQL);
				$data['old_id_album'] = $rs->fields[0];

				if ($data['id_album'] != $data['old_id_album']) {
					//check for new album limit
					$strSQL = "SELECT COUNT(*) FROM ".USER_UPLOAD_TABLE." WHERE id_album ='".$data['id_album']."' AND upload_type='".$data['upload_type']."'";
					$rs = $dbconn->Execute($strSQL);
					switch ($data['upload_type']) {
						case "f":
							$limit = GetItemLimit("photo_per_album");
							break;
						case "a":
							$limit = GetItemLimit("audio_per_album");
							break;
						case "v":
							$limit = GetItemLimit("video_per_album");
							break;
					}
					if ($rs->fields[0] >= $limit && $rs->fields[0] != 0) {
						$err = str_replace("[link]", $config['server']."/".seo('payment'), $lang['err']['cant_change_album_limit']);
						$data['id_album'] = $data['old_id_album'];
					}
					$limit_str = ",id_album='".$data['id_album']."'";
				}
				$dbconn->Execute("UPDATE ".USER_UPLOAD_TABLE." SET allow='".$upload_allow."', title='{$upload_title}', user_comment='".addslashes($user_comment)."',
									is_gallary='".$data['is_gallary']."', id_gallery='".$data['categories']."', id_servers='".$config['server_id']."'
									".$limit_str."
									WHERE id_user='".$id."' AND id='".$id_file."' ");
			} else {
				switch ($upload_type) {
					case "f":
						$limit = GetItemLimit("photo_per_album");
						break;
					case "a":
						$limit = GetItemLimit("audio_per_album");
						break;
					case "v":
						$limit = GetItemLimit("video_per_album");
						break;
				}
				$strSQL = "SELECT COUNT(*), max(id) FROM ".USER_UPLOAD_TABLE." WHERE id_user='".$user[0]."' AND id_album='".$data["id_album"]."' AND upload_type='".$data['upload_type']."'";
				$rs = $dbconn->Execute($strSQL);
				if ($rs->fields[0] >= $limit && $rs->fields[0] != 0 && $limit != 0) {
					$lang["err"]["item_limit"] = str_replace("[link]", $config['server']."/".seo('payment'), $lang["err"]["item_limit"]);
					$err = $lang["err"]["item_limit"];
				} else {
					$data["id_subitem_new"] = $rs->fields[1] + 1;
					if (!empty($data['type_use']) && 'link' != $data['type_use']) {
						$err = SaveUploadForm($data, $upload, $upload_type, $upload_allow, $id_file, $user_comment, '', '', $data['id_album'], $data['is_gallary'], $data['categories'], $from_uploadify, $upload_title);
					} elseif (!$err) {
						$err = SaveVideoLink($user[0], $data['link'], $user_comment, $upload_allow, $data['id_album'], $data['is_gallary'], $data['categories'], $upload_title);
					}
				}
			}
		}
		
		$page = 4; $act = 5;
		
		if($from_uploadify){
			$result['status'] = $err ? 'error' : 'success';
			$result['msg'] = $err ? $err : $lang['err']['uploaded'];
			exit(json_encode($result));
		}
		
		if($err) {
			ListProfile(4, '', $err, $sub_par, $act, $data);
			return;
		}
	}
	if($err){
		EditProfile($num, $err);
	}else{
		ListProfile($page, '', '', $sub_par, $act, $data);
	}
	return;
}

// ---------------------------- Table Functions -------------------------------- //
function GeneralTable(){
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $multi_lang, $field_name, $profile_percent2, $settings;

	$id = $user[0];
	//$dir = GetPath($id, $settings["photos_folder"]);
	if (isset($settings["use_pilot_module_webrecorder"]) && $settings["use_pilot_module_webrecorder"]) {
		$data["webrecorder_recorder"] = $config["site_root"]."/webrecorder/wr.php?type=recorder&user=".$id;
	}

	$images_obj = new Images($dbconn, $lang);

	///// icon
	$strSQL = "select a.icon_path, a.icon_path_temp, s.site_path, s.server
				from ".USERS_TABLE." a
				left join ".SERVERS_TABLE." s on s.id_servers=a.id_servers
				where a.id='".$id."' ";	
	$rs = $dbconn->Execute($strSQL);
	//Р ВµРЎРѓР В»Р С‘ Р Р…Р ВµРЎвЂљРЎС“ Р В·Р Р…Р В°РЎвЂЎР ВµР Р…Р С‘РЎРЏ Р Р† temp_icon
	if ($rs->fields[1] == 0)
		$icon_path_id = "icon_path";
	else
		$icon_path_id = "icon_path_temp";

	
	$strSQL = "SELECT uu.id, uu.upload_path, s.site_path, s.server 
				FROM ".USER_UPLOAD_TABLE." uu 
				LEFT JOIN ".USERS_TABLE." u ON u.".$icon_path_id."=uu.id
				LEFT JOIN ".SERVERS_TABLE." s ON s.id_servers=uu.id_servers 
				WHERE u.id='".$id."'";
	$rs = $dbconn->Execute($strSQL);
	$row = $rs->GetRowAssoc(false);

	$site_path = $row["site_path"];
    $server = $row["server"];
	if ($row["id"] != '')
		$dir = GetImagePath($id, $row["id"], $settings["photos_folder"]);
	else
		$dir = GetPath($id, $settings["photos_folder"],0,0,1);
	$icon_path = ($row["upload_path"] != "") ? "big_thumb_".$row["upload_path"]: $settings["photos_default"];
	if($icon_path){
		if ($icon_path != $settings["photos_default"]){
			$data["icon_path"] = $dir.$icon_path;
		}else{
			if(is_file($config['site_path'].$config["index_theme_path"].$config["index_theme_images_path"]."/big_".$icon_path)){
				$data["icon_path"] = $config['server'].$config["index_theme_path"].$config["index_theme_images_path"]."/big_".$icon_path;
			}else{
				$data["icon_path"] = $config['server'].$config["index_theme_path"].$config["index_theme_images_path"]."/".$icon_path;
			}
		}
		$icon_count = 1;
	} else {
		$icon_count = 0;
	}

	$i=0;
	$rs = $dbconn->Execute("SELECT uu.id, uu.upload_path, uu.allow, uu.upload_type, s.site_path, s.server, uu.id_album, uu.is_adult 
		FROM ".USER_UPLOAD_TABLE." uu LEFT JOIN ".SERVERS_TABLE." s ON s.id_servers=uu.id_servers 
		WHERE uu.id_user='".$id."' order by uu.upload_type");
	while(!$rs->EOF){
		$row = $rs->GetRowAssoc(false);
		$db_upload[$row["upload_type"]][$i]["id"] = $row["id"];
		$db_upload[$row["upload_type"]][$i]["file_path"] = $row["upload_path"];
		$db_upload[$row["upload_type"]][$i]["site_path"] = $row["site_path"];
		$db_upload[$row["upload_type"]][$i]["server"] = $row["server"];
		$db_upload[$row["upload_type"]][$i]["id_album"] = $row["id_album"];
		$rs->MoveNext(); $i++;
	}

	$i = 0;
	if(isset($db_upload["f"]) && count($db_upload["f"])){
		foreach($db_upload["f"] as $key=>$photo){
			if(strlen($photo["file_path"])){
				$data["big_thumb_photo_path"][$i]["path"] =  $dir."big_thumb_".$photo["file_path"];
			}
			if(strlen($photo["file_path"]) ){
				$data["thumb_photo_path"][$i]["path"] =  $dir."thumb_".$photo["file_path"];
			}
			if(strlen($photo["file_path"]) ){
				$data["main_thumb_photo_path"][$i]["id"] =  $photo["id"];
				$data["main_thumb_photo_path"][$i]["path"] =  $dir."main_thumb_".$photo["file_path"];
				$data["main_thumb_photo_path"][$i]["id_album"] = $photo["id_album"];
			}
			if(strlen($photo["file_path"]) ){
				$data["thumb_photo_path"][$i]["path"] =  $dir.$photo["file_path"];
				$data["thumb_photo_path"][$i]["sizes"] = $images_obj->GetResizeParametrsStr($dir.$photo["file_path"]);
			}
			if(strlen($photo["file_path"]) ){
				$i++;		
			}
		}
	}
	//$data["big_photo_count"] = (isset($data["big_thumb_photo_path"])?count($data["big_thumb_photo_path"]):0)+$icon_count;
	$data["big_photo_count"] = (isset($data["big_thumb_photo_path"])?count($data["big_thumb_photo_path"]):0);
	$data["photo_count"] = (isset($db_upload["f"])?count($db_upload["f"]):0)+$icon_count;
	$data["addf_link"]=seo('myprofile', 1)."?sel=4";

	$data["audio_count"] = isset($db_upload["a"])?count($db_upload["a"]):0;
	$data["adda_link"]=seo('myprofile', 1)."?sel=4";

	$data["video_count"] = isset($db_upload["v"])?count($db_upload["v"]):0;
	$data["addv_link"]=seo('myprofile', 1)."?sel=4";

	$data["login"] = $user[5];
	$data["print_link"] = seo("viewprofile", 1)."?login=".$data["login"]."&sel=print";

	$strSQL = "Select a.login, a.fname, a.sname, b.name as country, a.visible,
		c.name as city,
		k.name as region,
		a.date_birthday as birthday, a.gender, e.".$field_name." as subtype
	from ".USERS_TABLE." a
	left join ".COUNTRY_SPR_TABLE." b on b.id=a.id_country
	left join ".CITY_SPR_TABLE." c on c.id=a.id_city
	left join ".REGION_SPR_TABLE." k on k.id=a.id_region

	left join ".USERTYPES_SPR_TABLE." d on d.id=a.user_subtype
	left join ".REFERENCE_LANG_TABLE." e on e.table_key='".$multi_lang->TableKey(USERTYPES_SPR_VALUE_TABLE)."' AND e.id_reference=d.id

	where a.id='".$id."'";
	$rs = $dbconn->Execute($strSQL);
	$row = $rs->GetRowAssoc(false);
	$data["login"] = $row["login"];
	$data["status"] = $row["visible"];
	$data["name"] = chooseUserName($row["login"], $row["fname"]." ".$row["sname"]) ;
	$data["country"] = stripslashes($row["country"]);
	$data["region"] = stripslashes($row["region"]);
	$data["city"] = stripslashes($row["city"]);
	$data["age"] = AgeFromBDate($row["birthday"]);
	$data["gender"] = $row["subtype"];

	//// profile complition
	$data["complete"] = $profile_percent2->GetAllPercent();
	
	/*$place = GetUserRatingPlace($user[0]);
	if ($place != null) {
		$data['place'] = $place;
	}*/
	
	if (isset($settings["use_pilot_module_webrecorder"]) && $settings["use_pilot_module_webrecorder"]) {
		$rs = $dbconn->Execute("select count(*) from ".UP_RECORDER_RECORDS_TABLE." where id_user='".$id."' and status='approved'");
		if($rs->fields[0]>0) {
			$data["webrecorder_player"] = $config["site_root"]."/webrecorder/wr.php?type=player&amp;user=".$id;
			$rs = $dbconn->Execute("select value from ".UP_RECORDER_SETTINGS_TABLE." where name = 'videosize'");
			$settings["videosize"] = $rs->fields[0];
			$data["webrecorder_width"] = 180;
			$data["webrecorder_height"] = 280;
			if( $settings["videosize"] > 1 ) {
				$data["webrecorder_width"] = ($settings["videosize"] == 2) ? 340 : 660;
				$data["webrecorder_height"] = ($settings["videosize"] == 2) ? 400 : 640;
			}
		}
	}
	$status = intval($data['status']) ? "hide" : "public";

	$data["info_switch"] = $lang["account"]["info_".$status];
	$data["info_switch_comment"] = $lang["account"]["info_".$status."_comment"];

	$data["switch_link"] = $config["site_root"]."/".seo("account")."?sel=visible_change";
	$data["modify_link"] = $config["site_root"]."/".seo("account")."?sel=passw";
    $data["modify_profile_link"] = $config["site_root"]."/".seo("registration")."?sel=1&edit=1";
	$data["delete_link"] = $config["site_root"]."/".seo("account")."?sel=delete";


	$smarty->assign("settings", $settings);
	$smarty->assign("data", $data);
	return;
}

function UploadDelete(){
	global $smarty, $dbconn, $config, $config_admin, $lang, $user;

	$id_file = $_REQUEST["id_file"];
	$type_upload = $_REQUEST["type_upload"];
	$ajax = $_REQUEST["ajax"];

	//delete from gallary
	// id  id_user  id_album  upload_path  upload_type  allow  file_type  status  is_gallary
	$strSQL = " SELECT upload_path FROM ".USER_UPLOAD_TABLE." WHERE id='".$id_file."' AND is_gallary='1' ";
	$rs = $dbconn->Execute($strSQL);
	if ($rs->fields[0]) {
		$dbconn->Execute(" DELETE FROM ".GALLARY_TABLE." WHERE id_user='".$user[0]."' AND file_path='".$rs->fields[0]."'  ");
	}

	$data['id_album'] = DeleteUploadedFiles($type_upload, $id_file);
	$page= 4; $act = 7;
	switch ($type_upload) {
		case 'f':
			$sub_par = 8;
			break;
		case 'a':
			$sub_par = 9;
			break;
		case 'v':
			$sub_par = 10;
			break;
		case 'icon':
			$sub_par = 8;
			break;
		default:
			$sub_par = 8;
			break;
	}
	
	if (!$ajax){
		ListProfile(4, '', '', $sub_par, $act, $data);
	}
	return;
}

function UploadView($par=''){
	global $smarty, $dbconn, $config, $config_admin, $lang, $user, $config_index, $settings;
	IndexHomePage();
	$id = intval($user[0]);
	$id_file = intval($_GET["id_file"]);
	
	if ($par == '') {
		//	0			1			2				3				4			5
		$rs = $dbconn->Execute("Select a.upload_path, b.login, a.upload_type, a.user_comment, a.id_album, s.site_path, s.server from ".USER_UPLOAD_TABLE." a left join ".USERS_TABLE." b on a.id_user = b.id left join ".SERVERS_TABLE." s on s.id_servers=a.id_servers where a.id='".$id_file."'");
		$data["upload_type"] = $rs->fields[2];
		$data["user_comment"] = stripslashes($rs->fields[3]);
		$data["file_name"] = $rs->fields[0];
		$data["id_album"] = $rs->fields[4];
		$site_path = $rs -> fields[5];
		$server = $rs -> fields[6];
		switch($data["upload_type"]){
			case "f":
				$folder = $settings["photos_folder"];
				//$dir = GetPath($id, $folder);
				$strSQL = " SELECT DISTINCT uu.id, uu.upload_path, uu.user_comment, s.site_path, s.server
							FROM ".USER_UPLOAD_TABLE." uu
							LEFT JOIN ".SERVERS_TABLE." s ON s.id_servers=uu.id_servers
							WHERE uu.id_album='".$data["id_album"]."' AND uu.id_user='".$user[0]."'
                            GROUP BY uu.id
                            ORDER BY uu.id ";
				$rs = $dbconn->Execute($strSQL);
				$i = 0;
				while (!$rs->EOF) {
					$site_path_1 = $rs -> fields[3];
					$server_1 = $rs -> fields[4];
					
					$data['photos'][$i]['id'] = $rs->fields[0];
					if ($rs->fields[1] == $data["file_name"]) {
						$data['photos'][$i]["sel"] = 1;
					}
					$dir = GetImagePath($id, $rs->fields[0], $settings["photos_folder"]);
					$data['photos'][$i]['user_comment'] = $rs->fields[2];
					$data['photos'][$i]["thumb_file"] = $dir."thumb_".$rs->fields[1];
					$data['photos'][$i]["file"] = $dir.$rs->fields[1];
					$data['photos'][$i]["sizes"] = getimagesize($dir.$rs->fields[1]);
					$rs->MoveNext();
					$i++;
				}
				$sizes = getimagesize($dir."thumb_".$data["file_name"]);
				$smarty->assign("sizes", $sizes);

				break;
			case "a":		$folder = $settings["audio_folder"];	break;
			case "v":
				$folder = $settings["video_folder"];
				//$dir = GetPath($id, $folder);
				$dir = GetImagePath($id, $data["file_name"], $folder);
				if ($settings["use_ffmpeg"] == 1) {
					$flv_name = explode('.', $data["file_name"]);
					$is_flv = 1;
					$smarty->assign("is_flv", 1);
				}

				break;
		}
		if (isset($is_flv) && ($is_flv==1)) {
			$data["file_path"] = $dir.$flv_name[0].".mp4";
			$data["image_path"] = $dir.$flv_name[0]."1.jpg";
		} else {
			$data["file_path"] = $dir.$data["file_name"];
		}
		$smarty->assign("data", $data);
		$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_upload_view.tpl");
	} elseif ($par=='ajax') {
		$folder = $settings["photos_folder"];
		//$dir = GetPath($id, $folder);
		$strSQL = " SELECT uu.id, uu.upload_path, uu.user_comment, s.site_path, s.server
					FROM ".USER_UPLOAD_TABLE." uu
					LEFT JOIN ".SERVERS_TABLE." s ON s.id_servers=uu.id_servers
					WHERE uu.id='".$id_file."' AND uu.id_user='".$user[0]."' ";
		$rs = $dbconn->Execute($strSQL);
		$site_path = $rs -> fields[3];
		$server = $rs -> fields[4];
		$id_photo = $rs->fields[0];
		$dir = GetImagePath($id, $rs->fields[0], $folder);
		$photo = $dir.$rs->fields[1];
		$user_comment = stripslashes($rs->fields[2]);
		echo "
				<table cellpadding=\"0\" cellspacing=\"0\" align=\"center\">
				<tr>
					<td><img border=1 bordercolor=1 src=\"".$photo."\" alt=\"\"></td>
				</tr>
				<tr>
					<td align=\"center\">".$user_comment."</td>
				</tr>
				</table>
		";
	}
	exit;
}

function DeleteAlbum(){
	global $smarty, $dbconn, $config, $lang, $user, $settings;
	$id_album = intval($_GET["id_album"]);
	$_sub = intval($_GET["sub"]);
	if ($id_album < 1) {
		ListProfile(4, "", "", $_sub);
		return;
	}
	$strSQL = " SELECT id, album_type FROM ".USER_ALBUMS." WHERE id='".$id_album."' AND id_user='".$user[0]."' ";
	$rs = $dbconn->Execute($strSQL);
	if ($rs->fields[0]) {
		$album_type = $rs->fields[1];
		switch ($album_type) {
			case 'f':
				$file_folder = $settings['photos_folder'];
				break;
			case 'a':
				$file_folder = $settings['audio_folder'];
				break;
			case 'v':
				$file_folder = $settings['video_folder'];
				break;
			default:
				$file_folder = $settings['photos_folder'];
				break;
		}
		//$dir = GetPath($user[0], $file_folder);
		//id  id_user  upload_path  upload_type  allow  file_type  status  user_comment  id_album
		$strSQL = " SELECT DISTINCT uu.id, uu.upload_path, s.site_path
					FROM ".USER_UPLOAD_TABLE." uu
					LEFT JOIN ".SERVERS_TABLE." s ON s.id_servers=uu.id_servers
					WHERE uu.id_album='".$id_album."' AND uu.id_user='".$user[0]."' AND uu.upload_type='".$album_type."' ";
		$rs = $dbconn->Execute($strSQL);
		if ($rs->fields[0]>0) {
			while (!$rs->EOF) {
				$dir = GetImagePath($user[0], $rs->fields[0], $file_folder);
				$site_path = $rs -> fields[2];
				@unlink($dir.$rs->fields[1]);
				@unlink($dir."thumb_".$rs->fields[1]);
				$rs->MoveNext();
			}
			$dbconn->Execute("DELETE FROM ".USER_UPLOAD_TABLE." WHERE id_album='".$id_album."' AND id_user='".$user[0]."' AND upload_type='".$album_type."' ");
		}
		$dbconn->Execute("DELETE FROM ".USER_ALBUMS." WHERE id='".$id_album."' AND id_user='".$user[0]."' ");
	}
    $_GET["id_album"] = 0;
	$err = $lang["err"]["album_deleted"];
	ListProfile(4, "", $err, $_sub, 7);
	return;
}

function SaveAlbum() {				//save\edit albums
	global $smarty, $dbconn, $config, $lang, $user;

	$data = $_REQUEST;

	if (isset($data["edit_album"]) && ($data["edit_album"]==1)) {
		$act = 3;
	} else {
		$act = 2;
	}
	switch ($data["album_type"]) {
		case "f":
			$_type = 'f'; $_sub = 8;
			$limit = GetItemLimit("photo_album_count");
			break;
		case "a":
			$_type = 'a'; $_sub = 9;
			$limit = GetItemLimit("audio_album_count");
			break;
		case "v":
			$_type = 'v'; $_sub = 10;
			$limit = GetItemLimit("video_album_count");
			break;
		default:
			$_type = 'f'; $_sub = 8;
			$limit = GetItemLimit("photo_album_count");
			break;
	}
	if (strip_tags(trim($data["album_title"]))=='') {
		$err = $lang["errors"]["empty_fields"];
		$smarty->assign('not_show_error', 1);
		ListProfile(4, "", $err, $_sub, $act, $data);
		return;
	}
	if (BadWordsCont(strip_tags($data["album_title"]), 6)) {
		$err = $lang["err"]["badword_finding_6_1"];
		$smarty->assign('not_show_error', 1);
		ListProfile(4, "", $err, $_sub, 7, $data);
		return;
	}
	if (check_filter(strip_tags($data["album_title"]))) {
		$err = $lang["err"]["info_finding_1"];
		$smarty->assign('not_show_error', 1);
		ListProfile(4, "", $err, $_sub, $act, $data);
		return;
	}
	if (BadWordsCont(strip_tags($data["album_description"]), 6)) {
		$err = $lang["err"]["badword_finding_6_2"];
		$smarty->assign('not_show_error', 1);
		ListProfile(4, "", $err, $_sub, 7, $data);
		return;
	}
	if (check_filter(strip_tags($data["album_description"]))) {
		$err = $lang["err"]["info_finding_1"];
		$smarty->assign('not_show_error', 1);
		ListProfile(4, "", $err, $_sub, $act, $data);
		return;
	}

	if ($data["edit_album"] == 1) {
		$strSQL = " UPDATE ".USER_ALBUMS." SET title='".addslashes(strip_tags(trim($data["album_title"])))."',
						description='".addslashes(strip_tags(trim($data["album_description"])))."', allow='".intval($data["album_upload_allow"])."'
					WHERE id='".intval($data["id_album"])."' AND id_user='".$user[0]."' AND album_type='".$_type."' ";
		$dbconn->Execute(" UPDATE ".USER_UPLOAD_TABLE." SET allow='".intval($data["album_upload_allow"])."' WHERE id_album='".intval($data["id_album"])."' AND id_user='".$user[0]."'  ");

		$err = $lang["err"]["album_saved"];


	} else {
		$strSQL = " SELECT COUNT(id) FROM ".USER_ALBUMS." WHERE id_user='".$user[0]."' AND album_type='".$_type."' ";
		$rs = $dbconn->Execute($strSQL);
		if (($limit > 0) && ($rs->fields[0]>=$limit)) {
                        $lang["err"]["album_limit"] = str_replace("[link]", $config['server']."/".seo('payment'), $lang["err"]["album_limit"]);
			$err = $lang["err"]["album_limit"];
			$smarty->assign('not_show_error', 1);
			ListProfile(4, "", $err, $_sub);
			return;
		}
		$strSQL = " INSERT INTO ".USER_ALBUMS." (id_user, title, description, album_type, allow, creation_date)
					VALUES ('".$user[0]."', '".addslashes(strip_tags(trim($data["album_title"])))."', '".addslashes(strip_tags(trim($data["album_description"])))."',
					'".$_type."', '".intval($data["album_upload_allow"])."', now() ) ";
		$err = $lang["err"]["album_created"];
	}
	$dbconn->Execute($strSQL);
	ListProfile(4, "", $err, $_sub);

}

function TagsTable() {
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $lang_code, $settings;

	$file_name = seo('myprofile', 1);
	$data = array();

	$use_tags = $settings["use_tags"];
	$smarty->assign("use_tags", $use_tags);

	$strSQL = "Select DISTINCT tag, COUNT(id) as tag_count, id from ".TAGS_TABLE." WHERE id_user = '".$user[0]."' AND (tag_type='profile' OR tag_type='public') group by tag order by tag";
	$rs = $dbconn->Execute($strSQL);
	$i=0;
	while(!$rs->EOF){
		$row = $rs->GetRowAssoc(false);        
		$data["user_tags"][$i]["tag"] = stripslashes($row["tag"]);
		$data["user_tags"][$i]["count"] = $row["tag_count"];
        if ($row["tag_count"] < 2) $data["user_tags"][$i]["size"] = 10;
		if ($row["tag_count"] > 1 && $row["tag_count"] < 6) $data["user_tags"][$i]["size"] = 12;
		if ($row["tag_count"] > 5 && $row["tag_count"] < 11) $data["user_tags"][$i]["size"] = 14;
		if ($row["tag_count"] > 10) $data["user_tags"][$i]["size"] = 16;
		if ($config["use_seo_multilang"] && $config["use_global_seo"]) {
			$data["user_tags"][$i]["searchlink"] = $config["site_root"]."/".$lang_code."/tag/".$data["user_tags"][$i]["tag"];
		} else {
			$data["user_tags"][$i]["searchlink"] = seo("quick_search", 1)."?sel=search_tag&tag=".$data["user_tags"][$i]["tag"];
		}
		$data["user_tags"][$i]["dellink"] = $file_name."?sel=deltag&tag=".$data["user_tags"][$i]["tag"];
		$rs->MoveNext();
		$i++;
	}

	$strSQL = "Select id, tag from ".TAGS_TABLE." where tag_type='profile' and id_user = '".$user[0]."' and id_creator = '".$user[0]."' order by tag";
	$rs = $dbconn->Execute($strSQL);
	$i=0;
	while(!$rs->EOF){
		$row = $rs->GetRowAssoc(false);
		$data["my_tags"][$i]["tag"] = stripslashes($row["tag"]);
		$data["my_tags"][$i]["dellink"] = $file_name."?sel=deltag&tag=".stripslashes($row["tag"]);
		$rs->MoveNext();
		$i++;
	}
	$smarty->append("data_10", $data, true);
	return;
}

function AddTag() {
	global $lang, $config, $config_index, $smarty, $dbconn, $user;

	$tag_arr = explode(" ", $_POST["tag"]);
	foreach ($tag_arr as $key => $value) {
		$err = BadWordsCont(strip_tags($value), 13);
		if ($err) {
			ListProfile(5, '', $err);
			return;
		}
	}
	$tag = addslashes(strip_tags(trim($_POST["tag"])));
	if ($tag) {
		$rs = $dbconn->Execute("select id from ".TAGS_TABLE." where id_creator = '".$user[0]."' and id_user= '".$user[0]."' and tag = '".$tag."'");
		if(!$rs->fields[0]) {
			$strSQL = "INSERT INTO ".TAGS_TABLE." (id_creator, id_user, create_date, tag) VALUES ('".$user[0]."', '".$user[0]."', '".date("Y-m-d H:i:s")."', '".$tag."')";
			$dbconn->Execute($strSQL);
		}
	}

	ListProfile(5);
	return;
}

function DeleteTag() {
	global $lang, $config, $config_index, $smarty, $dbconn, $user;

	$tag = stripslashes($_GET["tag"]);

	$strSQL= "DELETE FROM ".TAGS_TABLE." WHERE id_user = '".$user[0]."' and tag = '".$tag."'";
	$dbconn->Execute($strSQL);

	ListProfile(5);
	return;
}

function AcceptCouple() {
	global $lang, $config, $config_index, $smarty, $dbconn, $user;

	$err = CoupleAction(intval($_GET["id"]), 'accept');

	ListProfile(1,"",$err);
	return;
}

function ShowAlbumForm($par='') {
	global $lang, $config, $config_index, $smarty, $dbconn, $user;
	if (isset($_REQUEST['type']) && ($_REQUEST['type'] == 'f' || $_REQUEST['type'] == 'a' || $_REQUEST['type'] == 'v')) {
		$type = $_REQUEST['type'];
		$smarty->assign("album_type", $type);
	}

	if ($par == 'edit') {
		$data['id_album'] = (isset($_REQUEST['id_item']) && intval($_REQUEST['id_item']) > 0) ? intval($_REQUEST['id_item']) : 0;
		$strSQL = "SELECT id, title, description, allow FROM ".USER_ALBUMS." WHERE id='".$data["id_album"]."' AND id_user='".$user[0]."' AND album_type='".$type."'";
		$rs = $dbconn->Execute($strSQL);
		if ($rs->fields[0] > 0) {
			$data["album_title"] = stripslashes($rs->fields[1]);
			$data["album_description"] = stripslashes($rs->fields[2]);
			$data["album_upload_allow"] = $rs->fields[3];
			$data["edit"] = 1;
			$smarty->assign('data', $data);
		} else {
			echo "<script>$('#mask').hide(); $('.window').hide();</script>";
		}
	} else {
		switch ($type) {
			case "f":
				$limit = GetItemLimit("photo_album_count");
				break;
			case "a":
				$limit = GetItemLimit("audio_album_count");
				break;
			case "v":
				$limit = GetItemLimit("video_album_count");
				break;
		}
		$strSQL = "SELECT COUNT(id) FROM ".USER_ALBUMS." WHERE id_user='".$user[0]."' AND album_type='".$type."'";
		$rs = $dbconn->Execute($strSQL);
		if ( ($limit > 0) && ($rs->fields[0] >= $limit) ) {
                        $lang["err"]["album_limit"] = str_replace("[link]", $config['server']."/".seo('payment'), $lang["err"]["album_limit"]);
			$smarty->assign('limit_err', $lang["err"]["album_limit"]);
		}
	}
	if (isset($_REQUEST['err'])) {
		$smarty->assign('form_err', $_REQUEST['err']);
	}
	$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_album_form.tpl");
}

function ShowItemForm($par='') {
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $settings;
	
    if (isset($_REQUEST['type']) && ($_REQUEST['type'] == 'f' || $_REQUEST['type'] == 'a' || $_REQUEST['type'] == 'v')) {
		$data['type'] = $_REQUEST['type'];
        $smarty->assign("album_type", $data['type']);
		switch ($data['type']) {
			case 'f':
				$data['type_str'] = 'photo';
				break;
			case 'a':
				$data['type_str'] = 'audio';
				break;
			case 'v':
				$data['type_str'] = 'video';
				break;
			default;
				$data['type_str'] = 'photo';
				break;
		}
	} else {
		echo "<script>$('#mask').hide(); $('.window').hide();</script>";
	}
	$data['form_sub_page'] = (isset($_REQUEST['form_sub_page']) && intval($_REQUEST['form_sub_page']) > 0) ? intval($_REQUEST['form_sub_page']) : 8;
	$data['id_album'] = (isset($_REQUEST['id_item']) && intval($_REQUEST['id_item']) > 0) ? intval($_REQUEST['id_item']) : 0;
	$data['id_subitem'] = (isset($_REQUEST['id_subitem']) && intval($_REQUEST['id_subitem']) > 0) ? intval($_REQUEST['id_subitem']) : 0;
	if ($par == 'edit') {
		$data['header'] = $lang["users"]["edit_".$data['type_str']];
		$data['comment_title'] = $lang["profile"]["comment_".$data['type_str']];

		//$dir = GetPath($user[0], $settings["photos_folder"]);
		$strSQL = "SELECT a.id, a.id_album, a.upload_path, a.is_gallary, a.id_gallery, a.user_comment, b.server, b.site_path, a.allow, a.views, a.gallery_rate, a.title
					FROM ".USER_UPLOAD_TABLE." a LEFT JOIN ".SERVERS_TABLE." b ON b.id_servers=a.id_servers
					WHERE a.id='".$data['id_subitem']."' AND a.id_user='".$user[0]."' AND a.id_album='".$data["id_album"]."' AND a.upload_type='".$data['type']."'";
		$rs = $dbconn->Execute($strSQL);
		if ($rs->fields[0] > 0) {
			$dir = GetImagePath($user[0], $rs->fields[0], $settings["photos_folder"]);
			$data['photo']['id'] = $rs->fields[0];
			$data['photo']['id_album'] = $rs->fields[1];
			$data['photo']['upload_path'] = $rs->fields[2];
			$data['photo']['is_gallary'] = $rs->fields[3];
			$data['photo']['id_gallery'] = $rs->fields[4];
			$data['photo']['upload_title'] = addslashes($rs->fields[11]);
			$data['photo']['user_comment'] = addslashes($rs->fields[5]);
			$data['photo']['site_server'] = $rs->fields[6];
			$data['photo']['site_path'] = $rs->fields[7];
			$data['photo']['url_image'] = $dir.$data['photo']['upload_path'];
			$data['photo']['imagesize'] = getimagesize($dir.$data['photo']['upload_path']);
			$data['photo']['allow'] = $rs->fields[8];
			$data['photo']['views'] = $rs->fields[9];
			$data['photo']['rate'] = round($rs->fields[10],2);
			
			//$data["photo"]["crop_link"] = $config["site_root"]."/include/imagecrop/index.php?imageName=".$data['photo']['upload_path'];
			$data["photo"]["crop_link"] = $config["site_root"]."/include/crop.php?image_id=".$data['photo']['id'];

			$strSQL = "SELECT id, title FROM ".USER_ALBUMS." WHERE id_user='".$user[0]."' AND album_type='".$data['type']."'";
			$rs = $dbconn->Execute($strSQL);
			$i = 0;
			while (!$rs->EOF) {
				$data['albums'][$i]["id"] = $rs->fields[0];
				if ($data['albums'][$i]["id"] == $data['photo']['id_album']) {
					$data['albums'][$i]["sel"] = 1;
				} else {
					$data['albums'][$i]["sel"] = 0;
				}
				$data['albums'][$i]["name"] = $rs->fields[1];
				$rs->MoveNext();
				$i++;
			}

			
			$strSQL = "SELECT gc.id as id, rls.lang_".$config["default_lang"]." as name FROM ".GALLERY_CATEGORIES_TABLE." gc LEFT JOIN ".REFERENCE_LANG_TABLE." rls on gc.id = rls.id_reference WHERE table_key = 22 ORDER BY name";

			$rs = $dbconn->Execute($strSQL);
			$i = 0;
			while (!$rs->EOF) {
				$data['categories'][$i]["id"] = $rs->fields[0];
				if ($data['photo']['is_gallary'] != 0 && $data['categories'][$i]["id"] == $data['photo']['id_gallery']) {
					$data['categories'][$i]["sel"] = 1;
				} else {
					$data['categories'][$i]["sel"] = 0;
				}
				$data['categories'][$i]["name"] = $rs->fields[1];
				$rs->MoveNext();
				$i++;
			}
			$data['par'] = 'edit';
			$smarty->assign('data_9', $data);
		} else {
			echo "<script>$('#mask').hide(); $('.window').hide();</script>";
		}
	} else {
		$data['header'] = $lang["users"]["add_".$data['type_str']];
		$data['comment_title'] = $lang["profile"]["comment_".$data['type_str']];

		switch ($data['type']) {
			case "f":
				$limit = GetItemLimit("photo_per_album");
				$smarty->assign("template_root", $config["index_theme_path"]);
				$uploadify_opts['max_size'] = round($settings["photo_max_size"]/1024);
				$uploadify_opts['file_types'] = '*.jpeg; *.jpg; *.gif; *.tiff; *.png';
				$uploadify_opts['swf'] = $config['server'].$config["index_theme_path"].'/js/uploadify/uploadify.swf';
				$uploadify_opts['album_type'] = $data['type'];
				$uploadify_opts['id_album'] = $data['id_album'];
				$uploadify_opts['session_name'] = session_name();
				$uploadify_opts['session_id'] = session_id();
				$smarty->assign('uploadify_opts',json_encode($uploadify_opts));
				$smarty->assign('use_uploadify',1);
				break;
			case "a":
				$limit = GetItemLimit("audio_per_album");
				break;
			case "v":
				if(!isset($VIDEO_EXT_ARRAY)) {
					include_once dirname(__FILE__) . './include/config_admin.php';
				}
				$unit = array('b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb');
				$i = floor(log($settings['video_max_size'], 1024));
				$data['video_max_size'] = round($settings['video_max_size'] / pow(1024, $i), 2) . '&nbsp;' . $unit[$i];
				$data['video_allowed_exts'] = implode(',&nbsp;', $VIDEO_EXT_ARRAY);
				$limit = GetItemLimit("video_per_album");
				break;
		}
		$data['categories'] = GetGalleryCategories();
		$smarty->assign('data_9', $data);
		$strSQL = "SELECT COUNT(*) FROM ".USER_UPLOAD_TABLE." WHERE id_user='".$user[0]."' AND id_album='".$data["id_album"]."' AND upload_type='".$data['type']."'";
		$rs = $dbconn->Execute($strSQL);
		if (($limit > 0) && ($rs->fields[0] >= $limit)) {
			$lang["err"]["item_limit"] = str_replace("[link]", $config['server']."/".seo('payment'), $lang["err"]["item_limit"]);
			$smarty->assign('limit_err', $lang["err"]["item_limit"]);
		}
	}
	if (isset($_REQUEST['err'])) {
		$smarty->assign('form_err', $_REQUEST['err']);
	}
	$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_item_form.tpl");
}

function StartSlideShow() {
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $settings;
	
	$file_name = seo('myprofile', 1);
	
	$data['id_album'] = (isset($_REQUEST['id_item']) && intval($_REQUEST['id_item']) > 0) ? intval($_REQUEST['id_item']) : 0;
	$data['id_subitem'] = (isset($_REQUEST['id_subitem']) && intval($_REQUEST['id_subitem']) > 0) ? intval($_REQUEST['id_subitem']) : 0;
	$data['type'] = (isset($_REQUEST['type']) && ($_REQUEST['type'] == 'f' || $_REQUEST['type'] == 'a' || $_REQUEST['type'] == 'v')) ? $_REQUEST['type'] : 'f';
	
	$icons = GetSiteSettings("icons_folder");
	$i = 0;

	//get main photo
	$strSQL_temp = "SELECT icon_path_temp FROM ".USERS_TABLE." WHERE id=".$user[0];
	$res_temp = $dbconn->Execute($strSQL_temp);
	if ($res_temp->fields[0] != 0) $icon_id = "icon_path_temp";
	else $icon_id = "icon_path";
	
	$strSQL = "SELECT uu.id FROM ".USER_UPLOAD_TABLE." uu 
				LEFT JOIN ".USERS_TABLE." u ON uu.id=u.".$icon_id."
				WHERE u.id=".$user[0];
	$res = $dbconn -> Execute($strSQL);
	$main_photo = $res->fields[0];
	$smarty->assign('id_main_photo', $main_photo);
	
	if(isset($_REQUEST['all_images'])) {	    
       $strSQL = "
				(SELECT 0, u.big_icon_path as upload_path, '',  '',  b.server, b.site_path,  '', '',''
                FROM ".USERS_TABLE." u
                LEFT JOIN ".SERVERS_TABLE." b ON b.id_servers=u.id_servers 
                WHERE u.id='".$user[0]."')
                UNION
                 (SELECT a.id, a.upload_path, a.user_comment, a.id_servers, b.server, b.site_path, alb.title, a.allow, a.id_album
				FROM ".USER_UPLOAD_TABLE." a LEFT JOIN ".SERVERS_TABLE." b ON b.id_servers=a.id_servers 
				LEFT JOIN ".USER_ALBUMS." alb ON a.id_album = alb.id AND alb.album_type='f'
				WHERE a.id_user='".$user[0]."' AND a.upload_type='f'
				ORDER BY a.id) ";
		$smarty->assign('view_all', true);
	}
	else {	
		$strSQL = "SELECT a.id, a.upload_path, a.user_comment, b.server, b.site_path, alb.title, a.allow, 
					COUNT(c.id) as photo_count, alb.id as id_album, a.id_gallery, a.is_gallary
					FROM ".USER_UPLOAD_TABLE." a 
					LEFT JOIN ".SERVERS_TABLE." b ON b.id_servers=a.id_servers
					LEFT JOIN ".USER_ALBUMS." alb ON a.id_album = alb.id AND alb.album_type='".$data['type']."'
					LEFT JOIN ".USER_UPLOAD_TABLE." c ON a.id_album = c.id_album
					WHERE a.id_user='".$user[0]."' AND a.id_album='".$data["id_album"]."' AND a.upload_type='".$data['type']."'
					GROUP BY a.id ORDER BY a.id";
	}
	$rs = $dbconn->Execute($strSQL);
	if (isset($rs)) {
		//$dir = GetPath($user[0], $settings["photos_folder"]);
		while (!$rs->EOF) {
			$row = $rs->GetRowAssoc(false);
			if(isset($_REQUEST['all_images']))
			{  
			    $data['photos'][$i]['id'] = $row[0];
			    if (str_replace("big_thumb_", "", $row["upload_path"]) == str_replace("big_thumb_", "", $_REQUEST['img'])) $data['num_selected'] = $i;
			}
			else
			{
			     $data['photos'][$i]['id'] = $row["id"];
				if ($row['id'] == $data['id_subitem']) {
					$data['num_selected'] = $i;
				}
			}
			$data['photos'][$i]['upload_path'] = $row['upload_path'];
			$data['photos'][$i]['user_comment'] = stripslashes($row['user_comment']);			
			$data['photos'][$i]['site_path'] = $row['site_path'];
			$data['photos'][$i]['site_server'] = $row['server'];
			$dir = GetImagePath($user[0], $data['photos'][$i]['id'], $settings["photos_folder"]);
			if($data['photos'][$i]['id']) 
				$data['photos'][$i]['url_image'] = $dir.$data['photos'][$i]['upload_path'];
			else
			  $data['photos'][$i]['url_image'] = $data['photos'][$i]['site_server'].$config["index_theme_path"].$config["index_theme_images_path"]."/".$data['photos'][$i]['upload_path'];
			$data['photos'][$i]['imagesize'] = getimagesize($dir.$data['photos'][$i]['upload_path']);
			$data['photos'][$i]['title'] = $row{'title'};
			$data['photos'][$i]['allow'] = $row['allow'];
			
			$data['photos'][$i]['is_gallary'] = $row['is_gallary'];            
			$data['photos'][$i]['album_id'] = $row['id_album'];
			$data['photos'][$i]['gallery_name'] = GetGalleryCategoriyById($row['id_gallery']);
			$data['photos'][$i]["main_photo"] = $file_name."?sel=make_main&id_file=".$data['photos'][$i]['id']."&type_upload=".$data['type'];
			//$data['type'] = ($main_photo == $data['photos'][$i]['id']) ? "icon" : 'f';
			$data['photos'][$i]["del_link"] = $file_name."?sel=upload_del&id_file=".$data['photos'][$i]['id']."&type_upload=".$data['type'];
			$data['photos'][$i]["crop_link"] = $config["site_root"]."/include/crop.php?image_id=".$data['photos'][$i]['id'];
			$data['photos'][$i]["crop_click"] = 'launchWindow(\''.$data['photos'][$i]["crop_link"].'\',\'\','.($data['photos'][$i]['imagesize'][0]<300 ? 600 : $data['photos'][$i]['imagesize'][0]+300).', 600, true)';
			$rs->MoveNext();
			$i++;
		}
       $data['count_photos'] = $i;
     
		$strSQL = "SELECT ua.id, ua.title 
			FROM ".USER_ALBUMS." ua
			WHERE ua.id_user='".$user[0]."' AND ua.album_type='".$data['type']."' GROUP BY ua.id";
		$rs = $dbconn->Execute($strSQL);
		$i = 0;
		while (!$rs->EOF) {
			$data['albums'][$i]["id"] = $rs->fields[0];
			if ($data['albums'][$i]["id"] == $data['photo']['id_album']) {
				$data['albums'][$i]["sel"] = 1;
			} else {
				$data['albums'][$i]["sel"] = 0;
			}
			$data['albums'][$i]["name"] = $rs->fields[1];
			$rs->MoveNext();
			$i++;
		}
		
		$data['categories'] = GetGalleryCategories();
		
		$strSQL_rat = " SELECT uu.id_user, gr.estimation
					FROM ".USER_UPLOAD_TABLE." uu
					LEFT JOIN ".GALLERY_RATING_TABLE." gr ON gr.id_upload=uu.id AND gr.id_user='".$user[0]."'
					WHERE uu.id='".$data['id_subitem']."' AND gr.id_upload='".$data['id_subitem']."'";
		$rs_rat = $dbconn->Execute($strSQL_rat);
		if ($rs_rat->fields[0] == $user[0] || ($rs_rat->fields[1]>0 && $rs_rat->fields[1] == "NULL")) {
			$form["no_rating"] = 1;
		}else {
			$form["no_rating"] = 0;
			$_arr = range(1,10);
			$smarty->assign("vote_arr", $_arr);
		}
		$form['vote_icon_1_path'] = $config['server'].$config["index_theme_path"].$config["index_theme_images_path"]."/vote_icon_1.gif";
		$form['vote_icon_0_path'] = $config['server'].$config["index_theme_path"].$config["index_theme_images_path"]."/vote_icon_0.gif";
		$smarty->assign("can_edit", 1);
			if($config["use_default_smiles"]==1 ){
		$smarty->assign("smiles", $config["smiles"]);
			}else{
			$strSQL = "SELECT value, file, preg FROM ".SMILES."";
			$rs = $dbconn->Execute($strSQL);
			$smile = array();
			$i = 0;
				while(!$rs->EOF){
					$smile[$i]["value"] = $rs->fields[0];
					$smile[$i]["file"] = $rs->fields[1];
					$smile[$i]["preg"] = $rs->fields[2];
					$i++;
					$rs->MoveNext();
				}
			$smarty->assign("smiles", $smile);
			}
			$smarty->assign("use_default_smiles", $config["use_default_smiles"]);
		$smarty->assign('smiles_path',$config['server'].$config["index_theme_path"]);
		$smarty->assign("header", $lang["homepage"]);
		$smarty->assign("report_abuse", $lang["abuse"]);
		$smarty->assign("general_lang", $lang["general"]);
		$smarty->assign("form", $form);
		$smarty->assign("abuse_link", array('id_user'=>$user[0], 'id_item'=>$data['id_subitem'], 'item_type'=>$data['type'], 'abuse_types_msg'=>$config_index['abuse_types_msg']));
		if (!isset($data['num_selected'])){ $data['num_selected'] = 0; }
		$smarty->assign('data_9', $data);
		$smarty->assign('gallery_height',$settings["subscrimage_max_height"]);
		$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_photo_slide_table.tpl");
	} else {
		echo "<script>$('#mask').hide(); $('.window').hide();</script>";
	}
}

function StartAudioPlaying() {
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $settings;

	//$dir = GetPath($user[0], $settings['audio_folder']);
	$data['id_album'] = (isset($_REQUEST['id_item']) && intval($_REQUEST['id_item']) > 0) ? intval($_REQUEST['id_item']) : 0;
	$data['id_subitem'] = (isset($_REQUEST['id_subitem']) && intval($_REQUEST['id_subitem']) > 0) ? intval($_REQUEST['id_subitem']) : 0;
	$data['type'] = (isset($_REQUEST['type']) && ($_REQUEST['type'] == 'f' || $_REQUEST['type'] == 'a' || $_REQUEST['type'] == 'v')) ? $_REQUEST['type'] : 'a';

	$strSQL = "SELECT a.id, a.upload_path, a.user_comment, a.id_servers, b.server, b.site_path, d.song_name, d.song_author, d.song_length
	FROM ".USER_UPLOAD_TABLE." a
	LEFT JOIN ".SERVERS_TABLE." b ON b.id_servers=a.id_servers
	LEFT JOIN ".AUDIO_FILES_INFO_TABLE." d ON d.id_file=a.id
	WHERE a.id='".$data['id_subitem']."' AND a.id_user='".$user[0]."' AND a.id_album='".$data["id_album"]."' AND a.upload_type='".$data['type']."'
	";
	$rs = $dbconn->Execute($strSQL);
	if ($rs->fields[0] > 0) {
		$i = 0; 
		$dir = GetImagePath($user[0], $rs->fields[0], $settings["audio_folder"]);
		$data['audio']['id'] = $rs->fields[0];
		$data['audio']['upload_path'] = $rs->fields[1];
		$data['audio']['user_comment'] = stripslashes($rs->fields[2]);
		$data['audio']['user_comment'] = ($data['audio']['user_comment'] != '') ? $lang["users"]["comment"]."&nbsp;:&nbsp;".$data['audio']['user_comment'] : "";
		$data['audio']['site_path'] = $rs->fields[5];
		$data['audio']['site_server'] = $rs->fields[4];
		$data['audio']['song_name'] = strlen($rs->fields[6]) > 0 ? $rs->fields[6] : $lang['profile']['unknown'];
		$data['audio']['song_author'] = strlen($rs->fields[7]) > 0 ? $rs->fields[7] : $lang['profile']['unknown'];
		$data['audio']['song_length'] = $rs->fields[8];
		$data['audio']['url_audio'] = $dir.$data['audio']['upload_path'];
		$smarty->assign('data_9', $data);
		$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_audio_view_table.tpl");
	} else {
		echo "<script>$('#mask').hide(); $('.window').hide();</script>";
	}

}

function StartVideoPlaying() {
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $settings;

	$data = array();
	//$dir = GetPath($user[0], $settings['video_folder']);
	$data['id_album'] = (isset($_REQUEST['id_item']) && intval($_REQUEST['id_item']) > 0) ? intval($_REQUEST['id_item']) : 0;
	$data['id_subitem'] = (isset($_REQUEST['id_subitem']) && intval($_REQUEST['id_subitem']) > 0) ? intval($_REQUEST['id_subitem']) : 0;
	$data['type'] = (isset($_REQUEST['type']) && ($_REQUEST['type'] == 'f' || $_REQUEST['type'] == 'a' || $_REQUEST['type'] == 'v')) ? $_REQUEST['type'] : 'v';
	
	$strSQL = "SELECT a.id, a.upload_path, a.user_comment, a.id_servers, b.server, b.site_path, a.file_type, a.title upload_title
		FROM ".USER_UPLOAD_TABLE." a
		LEFT JOIN ".SERVERS_TABLE." b ON b.id_servers=a.id_servers
		WHERE a.id='".$data['id_subitem']."' AND a.id_user='".$user[0]."' AND a.id_album='".$data["id_album"]."' AND a.upload_type='".$data['type']."'";
	$rs = $dbconn->Execute($strSQL);
	if ($rs->fields[0] > 0) {
		$i = 0; 

		$data['video']['id'] = $rs->fields[0];
		$data['video']['upload_title'] = $rs->fields[7];
		$data['video']['upload_path'] = $rs->fields[1];
		$data['video']['user_comment'] = stripslashes($rs->fields[2]);
		$data['video']['site_path'] = $rs->fields[5];
		$data['video']['site_server'] = $rs->fields[4];
		

		$data['video']['type'] = $rs->fields[6];
		
		// if we have video file
		if ($data['video']['type'] != 'embed') {
			$dir = GetImagePath($user[0], $rs->fields[0], $settings["video_folder"]);
			if ($settings["use_ffmpeg"] == 1) {
				$flv_name = explode('.', $data['video']['upload_path']);
				$is_flv = 1;
			}
			if (isset($is_flv) && ($is_flv==1)) {
				if (fopen($dir.$flv_name[0].".mp4", 'r')) {
					$data['video']['url_video'] = $dir.$flv_name[0].".mp4";
					$data['video']['url_image'] = $dir.$flv_name[0]."1.jpg";
					$is_flv = 1;
					$smarty->assign("is_flv", 1);
				} else {
					$data['video']['url_video'] = $dir.$rs->fields[1];
				}
			}
			$data['video']['url_video'] = $dir.$data['video']['upload_path'];
		} else {
			$data['video']['url_video'] = 
				str_replace('%width%', 520, 
				str_replace('%height%', 390, $data['video']['upload_path']));
		}
		
		$smarty->assign("can_edit", 1);
		$smarty->assign('data_9', $data);
		
		$smarty->display(TrimSlash($config["index_theme_path"]) . "/myprofile_video_view_table.tpl");
	} else {
		echo "<script>$('#mask').hide(); $('.window').hide();</script>";
	}

}
function getAllUploades($page = 1, $limit = 10){
	global $dbconn, $user, $settings;
    
	$sql = "SELECT COUNT(*) FROM ".USER_UPLOAD_TABLE." WHERE upload_type = 'f' && id_user=".$user[0];
	
	//$dir = GetPath($user[0], $settings["photos_folder"]);
	$rs  = $dbconn->Execute($sql);
	$result['count'] = $rs->fields[0];
	
	$page = ((int)$page>1)?(int)$page:1;
	$sql = "SELECT `upload_path`, id FROM ".USER_UPLOAD_TABLE." WHERE upload_type = 'f' &&id_user=".$user[0]." ORDER BY `id` DESC LIMIT ".($page-1)*$limit.",".$limit;
	$rs  = $dbconn->Execute($sql);
	$path = GetSiteSettings('photos_folder');
	if($rs->fields[0])
	while(!$rs->EOF){
		$dir = GetImagePath($user[0], $rs->fields[0], $settings["photos_folder"]);
		$result['images'][] = $dir.'big_thumb_'.$rs->fields[1];
		$rs->MoveNext();
	};
	
    return 	$result;
}


function SetComment() {
    global $dbconn, $config, $config_index, $lang, $user;
	
    $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    $type = isset($_REQUEST['type']) ? intval($_REQUEST['type']) : 0;
    $message = isset($_REQUEST['message']) ? strip_tags($_REQUEST['message']) : '';
    $to_user_id = isset($_REQUEST['id_user']) ? intval($_REQUEST['id_user']) : 0;   
    
    $err = "";

	if($to_user_id){
		$strSQL = "SELECT a.id, ig.id_enemy, a.root_user 
					FROM ".USERS_TABLE." a
					LEFT JOIN ".BLACKLIST_TABLE." ig ON ig.id_user=a.id AND ig.id_enemy='".$user[0]."'
					WHERE a.id='".$to_user_id."'";
		$rs = $dbconn->Execute($strSQL);
		$to_id = $rs->fields[0];
		$ignore = $rs->fields[1];
	}else{
		$to_id = $user[0];
		$ignore = 0;
	}

    if($to_id && intval($ignore)==0){
        $user_comment = stripn(FormFilter($message));
        if (BadWordsCont($user_comment, 6)){
			$err = BadWordsCont($user_comment, 6);
		}elseif (check_filter($user_comment)){
			$err = $lang["err"]["info_finding_1"];
		}
        if($config["use_default_smiles"]==1 ){
			$user_comment = AddSmiles($user_comment);
        }else{
			$user_comment = AddMySmiles($user_comment);
        }

        if ($user_comment == "" || $id == 0 || $err != "") {
            echo $err;
        } else {
            $strSQL = "INSERT INTO ".USER_UPLOAD_COMMENTS_TABLE." (id, id_user, comment, date_post) VALUES('".$id."', $user[0], '".$user_comment."', now()) ";
            $dbconn -> Execute($strSQL);
            echo 'send';
        }
    }
   else
       echo $lang["err"]["email_black_list_err"];
}

function VotePhoto() {
	global $lang, $config, $config_index, $smarty, $dbconn, $user;

	$id_category = intval($_REQUEST['id_category']);
	$vote = intval($_REQUEST['vote']);
	$id_upload = intval($_REQUEST['id_upload']);
	$upload_type = (isset($_REQUEST["upload_type"]) && $_REQUEST["upload_type"]!="" && ( $_REQUEST["upload_type"]=="f" || $_REQUEST["upload_type"]=="v" )) ? $_REQUEST["upload_type"] : "f";
	
	$strSQL_1 = " SELECT id FROM ".GALLERY_RATING_TABLE." WHERE id_upload='".$id_upload."' AND id_user = '".$user[0]."'";
	$rs = $dbconn->Execute($strSQL_1);
	
	if ($rs->fields[0] > 0){
		$strSQL = "UPDATE ".GALLERY_RATING_TABLE." SET id_upload = '".$id_upload."', id_user = '".$user[0]."', estimation = '".$vote."', voting_date = now(), upload_type = '".$upload_type."' WHERE id = '".$rs->fields[0]."'";
	}
	else{
		$strSQL = "INSERT INTO ".GALLERY_RATING_TABLE." (id_upload, id_user, estimation, voting_date, upload_type )
					VALUES ('".$id_upload."', '".$user[0]."', '".$vote."', now(), '".$upload_type."') ";
	}
	$rs = $dbconn->Execute($strSQL);

	if ($rs){
		echo "Ok";//$lang["myprofile"]["voice_submitted"];
	}
	else 
		echo "no photo";//$lang["myprofile"]["no_photos"];
}

function GetComments() {
    global $dbconn, $config, $config_index, $lang, $user, $settings, $lang_code, $smarty;
    
    $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    $can_edit = isset($_REQUEST['can_edit']) ? intval($_REQUEST['can_edit']) : 0;
	
	$strSQL="UPDATE ".USER_UPLOAD_TABLE." SET views=views+1 WHERE id = '".$id."' ";
	$res = $dbconn -> Execute($strSQL);	
	
    /*$strSQL = "SELECT COUNT(uu.id_comment)
                FROM ".USER_UPLOAD_COMMENTS_TABLE." uu
                LEFT JOIN ".USERS_TABLE." u ON u.id=uu.id_user
                WHERE uu.id='".$id."'";
    $res = $dbconn -> Execute($strSQL);
    $count_comments = $res -> fields[0];
    $numpage_commments = 5;
    
    $pages_range = 1;
    
	$page = isset($_REQUEST['page']) ? (intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1 ) : 1;
    $count_page = ceil($count_comments/$numpage_commments);//6
    $start_page = $page-$pages_range;
    if ($start_page<1) { $start_page=1; }
    $end_page=$page+$pages_range;

    if ($end_page>$count_page) { $end_page=$count_page; }
	
    $i = 0;
	for ($k=$start_page;$k<=$end_page;$k++) { 
        if ($page == $k) $links[$k]['sel'] = 1;		
        else $links[$k]['sel'] = 0;
		
		$links[$k]['val'] = $k;
        $links[$k]['link'] = $k;	
		
		if($page>1){
			$links[$k]["previous_page"] = 1;
		}
		
		if($page < $end_page){
			$links[$k]["next_page"] = 1;
		}
		
        $i++;
    }

    $lim_min = ($page - 1) * $numpage_commments;
    $lim_max = $numpage_commments;
	
    $limit_str = " ORDER BY uu.date_post DESC LIMIT ".$lim_min.", ".$lim_max;
	//				     	0					1			2		3			4			5			6
    $strSQL = "SELECT uu.id_comment, uu.comment, uu.date_post, u.fname, u.sname, up.upload_path, b.site_path, 
				b.server, u.user_type, u.id, up.id_user, uu.id_user, u.login, up.id, IF(u.icon_path!='0', u.icon_path, u.icon_path_temp) icon_path
                FROM ".USER_UPLOAD_COMMENTS_TABLE." uu
                LEFT JOIN ".USER_UPLOAD_TABLE." up ON up.id=uu.id 
                LEFT JOIN ".USERS_TABLE." u ON u.id=uu.id_user
				LEFT JOIN ".SERVERS_TABLE." b on b.id_servers=u.id_servers
                WHERE uu.id='".$id."'".$limit_str;
    $res = $dbconn -> Execute($strSQL);
    $v = 0;
  
    while (!$res -> EOF) {
        $comments[$v]['id_comment'] = $res -> fields[0];
        $comments[$v]['comment'] = stripslashes($res -> fields[1]);
        $comments[$v]['date_post'] = $res -> fields[2];
        $comments[$v]['name'] = chooseUserName($res -> fields[12], $res -> fields[3]." ".$res -> fields[4]) ;
        $comments[$v]["profile_link"] = seo("viewprofile", 1)."?id=" . $res->fields[9];
        if ($config["use_seo_multilang"] && $config["use_global_seo"])
            $comments[$v]["profile_link"] = $config["server"]."/".$lang_code."/user/".$res -> fields[12];
        else
            $comments[$v]["profile_link"] = seo("viewprofile", 1)."?id=" . $res->fields[9];
        if ($res->fields[10] == $user[0] or $res->fields[11] == $user[0])
            $comments[$v]["del_lang"] = $lang["button"]["delete"];
        else $comments[$v]["del_lang"] = " ";
		
		$site_path = $res -> fields[6];
		$server = $res -> fields[7];
				
		if ($can_edit && $res->fields[9]==$user[0]) {
			$strSQL_icon = "SELECT icon_path_temp FROM ".USERS_TABLE." WHERE id=".$res->fields[9];
			$res_icon = $dbconn -> Execute($strSQL_icon);
			if ($res_icon->fields[0] != 0)
				$strSQL_icon = "SELECT uu.upload_path FROM ".USER_UPLOAD_TABLE." uu LEFT JOIN ".USERS_TABLE." u ON uu.id=u.icon_path_temp WHERE u.id=".$res->fields[9];
			else
				$strSQL_icon = "SELECT uu.upload_path FROM ".USER_UPLOAD_TABLE." uu LEFT JOIN ".USERS_TABLE." u ON uu.id=u.icon_path WHERE u.id=".$res->fields[9];
		}
		else{
			$strSQL_icon = "SELECT uu.upload_path FROM ".USER_UPLOAD_TABLE." uu LEFT JOIN ".USERS_TABLE." u ON uu.id=u.icon_path WHERE u.id=".$res->fields[9];
		}
		$res_icon = $dbconn -> Execute($strSQL_icon);
		$icon_path = $res_icon->fields[0] ? "thumb_".$res_icon->fields[0] : $settings["photos_default"];

		$dir = GetImagePath($res->fields[9], $res->fields[14], $settings["photos_folder"]);
		if($icon_path != $settings["photos_default"] && $dir)
			$comments[$v]['icon_path'] = $dir.$icon_path;
		else
			$comments[$v]['icon_path'] = $config['server'].$config["index_theme_path"].$config["index_theme_images_path"]."/".$icon_path;
			
        $v++;
        $res -> MoveNext();
    }
    if (!isset($comments)) {
        $comments['err'] = $lang["gallary"]["no_comments"];
    }
    $comments['count'] = $v;
    $comments['links'] = $links;
    $comments['page'] = $page;
	$comments['count_page'] = $count_page;
	$comments['of'] = $lang["general"]["of"];
	$comments['showing'] = $lang["general"]["showing"];
	$comments['current_page'] = $page;
	
	$comments['ajax'] = 1;
*/
	$str_temp = "SELECT id_user FROM ".USER_UPLOAD_TABLE." WHERE id='".$id."'";
	$rs = $dbconn->Execute($str_temp);
	if ($rs->fields[0] != $user[0]){
		$strSQL_rat = " SELECT uu.id_user, gr.estimation, gr.id_user
						FROM ".USER_UPLOAD_TABLE." uu
						LEFT JOIN ".GALLERY_RATING_TABLE." gr ON gr.id_upload=uu.id AND gr.id_user='".$user[0]."' AND uu.id_user != '".$user[0]."'
						WHERE uu.id='".$id."' AND gr.id_upload='".$id."'";

		$rs_rat = $dbconn->Execute($strSQL_rat);
		if (($rs_rat->fields[1]>0) || ($rs_rat->fields[0] == $user[0]) || ($rs_rat->fields[1] == "NULL")) {
			$comments['rating'] = 1;
			$comments['vote'] = -1;
		}else {
			$comments['rating'] = 0;
			$comments['vote'] = range(1,10);
		}
	}
	else{
		$comments['rating'] = 1;
		$comments['vote'] = "";
	}
	
	include_once "./include/class.comments.php";
	$comments_obj = new Comments($user, $config, $settings, $dbconn, $smarty);
	$comments_obj->comment_block('photogallery', $id);
	$comments['comments'] = $smarty->fetch(TrimSlash($config["index_theme_path"])."/comment_post_form.tpl");
	
    require_once "./include/class.json.php";
    $json_serv = new Services_JSON();
    if (floatval(phpversion()) >= '5.2'){
		echo json_encode($comments);
    }else{
		echo $json_serv->encode($comments);
    }	
}


function SetDescriptionPhoto(){
	global $dbconn, $config, $config_index, $lang, $user, $settings;	
	$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
	$text = isset($_REQUEST['text']) ? addslashes($_REQUEST['text']) : "";
	
	$text = stripn(FormFilter($text));
	if (BadWordsCont($text, 6))
		$err = BadWordsCont($text, 6);
	elseif (check_filter($text))
		$err = $lang["err"]["info_finding_1"];
    else{
       $strSQL = "UPDATE ".USER_UPLOAD_TABLE." SET user_comment='".$text."' WHERE id='".intval($id)."' AND id_user='".$user[0]."'  ";
	   $rs = $dbconn->Execute($strSQL);
        if ($rs)
        	echo "send";
        else	
        	echo "no_send";
    }
    if($err != ''){
        echo $err;
    }
}

function ChangePhotoPar(){
	global $dbconn, $config, $config_index, $lang, $user, $settings;	
	$id_photo = isset($_REQUEST['id_photo']) ? intval($_REQUEST['id_photo']) : 0;
	$par = isset($_REQUEST['par']) ? addslashes($_REQUEST['par']) : '';
	$new_par = isset($_REQUEST['new_par']) ? addslashes($_REQUEST['new_par']) : '';
	
	if (!$id_photo || !$par) {echo 'error'; exit;}
	
	switch ($par){
		case 'album': 
			$name = 'id_album';
			$strSQL = "SELECT title FROM ".USER_ALBUMS." WHERE id='{$new_par}'";
			$rs = $dbconn->Execute($strSQL);
			$new_name = $rs->fields[0];
			break; 
		case 'perm': 
			$name = 'allow';
			$new_name = $lang['users']['allow_'.$new_par];
			break;
		case 'show_in':
			$name = 'is_gallary';
			$new_name = ($new_par) ? $lang['profile']['show_in_photo_gallery'] : $lang['profile']['show_in_nowhere'];
			break;
		case 'category':
			$name = 'id_gallery';
			$new_name = GetGalleryCategoriyById($new_par);
			break;
	}
	$strSQL = "UPDATE ".USER_UPLOAD_TABLE." SET {$name} = '{$new_par}' WHERE id='{$id_photo}'";
	$rs = $dbconn->Execute($strSQL);
	if ($rs) {
		echo $new_name;
	}
	else echo 'error1';
}

function CropPhoto($photo){
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $settings;
	$smarty->assign("template_root", $config["index_theme_path"]);
	$smarty->assign("photo_crop", $photo);
	$smarty->display(TrimSlash($config["index_theme_path"])."/myprofile_crop.tpl");
}

function SaveCropPhoto($photo){
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $settings;
	$file = "./uploades/photos/tmp.jpeg";
	//$dir = GetPath($user[0], $settings["photos_folder"]);
	$rs=$dbconn->Execute("SELECT id FROM ".USER_UPLOAD_TABLE." WHERE upload_path = '".$photo."'");	
	$dir = GetImagePath($user[0], $rs->fields[0], $settings["photos_folder"]);
	$new_file = $dir.$photo;
	if (!copy ( $file, $new_file)){
		echo "error copy";
	}
	$thumb_upload_path =$dir."thumb_".$photo;
	copy($new_file, $thumb_upload_path);
	$upload_info = getimagesize($thumb_upload_path);

	$images_obj = new Images($dbconn, $lang);

	if (($upload_info[0] <= $settings["thumb_max_width"]) && ($upload_info[1] <= $settings["thumb_max_height"]))
	$resize_res =  $images_obj->ReSizeWithoutCropImage($thumb_upload_path, $settings["thumb_max_width"], $settings["thumb_max_height"], 1);
	else
	$resize_res =  $images_obj->ReSizeImage($thumb_upload_path, $settings["thumb_max_width"], $settings["thumb_max_height"], 1);
	
	//small photo thumb for carousel in user mode (60x60)
	$main_thumb_upload_path = "./uploades/photos/main_thumb_".$photo;
	copy($new_file, $main_thumb_upload_path);
	if (($upload_info[0] <= 60) && ($upload_info[1] <= 60))
	$main_resize_res =  $images_obj->ReSizeWithoutCropImage($main_thumb_upload_path, 60, 60, 1);
	else
	$main_resize_res =  $images_obj->ReSizeImage($main_thumb_upload_path, 60, 60, 1);
	
	//photo thumb for gallery (130x130)
	$thumb_upload_path =$dir."".$data."/gal_thumb_".$new_file_name;
	copy($upload_path, $thumb_upload_path);
	if (($upload_info[0] <= $settings["gal_thumb_max_width"]) && ($upload_info[1] <= $settings["gal_thumb_max_height"]))
		$resize_res =  $images_obj->ReSizeWithoutCropImage($thumb_upload_path, $settings["gal_thumb_max_width"], $settings["gal_thumb_max_height"], 1);
	else
		$resize_res =  $images_obj->ReSizeImage($thumb_upload_path, $settings["gal_thumb_max_width"], $settings["gal_thumb_max_height"], 1);
	
	//photo thumb for gallery (305x305)
	$thumb_upload_path =$dir."".$data."/gal_big_thumb_".$new_file_name;
	copy($upload_path, $thumb_upload_path);
	if (($upload_info[0] <= $settings["gal_big_thumb_max_width"]) && ($upload_info[1] <= $settings["gal_big_thumb_max_height"]))
		$resize_res =  $images_obj->ReSizeWithoutCropImage($thumb_upload_path, $settings["gal_big_thumb_max_width"], $settings["gal_big_thumb_max_height"], 1);
	else
		$resize_res =  $images_obj->ReSizeImage($thumb_upload_path, $settings["gal_big_thumb_max_width"], $settings["gal_big_thumb_max_height"], 1);
	
	//photo thumb for gallery (200x200)
	$thumb_upload_path =$dir."".$data."/big_thumb_".$new_file_name;
	copy($upload_path, $thumb_upload_path);
	if (($upload_info[0] <= $settings["big_thumb_max_width"]) && ($upload_info[1] <= $settings["big_thumb_max_height"]))
	$resize_res =  $images_obj->ReSizeWithoutCropImage($thumb_upload_path, $settings["big_thumb_max_width"], $settings["big_thumb_max_height"], 1);
	else
	$resize_res =  $images_obj->ReSizeImage($thumb_upload_path, $settings["big_thumb_max_width"], $settings["big_thumb_max_height"], 1);
	
	ListProfile($page, '', '', $sub_par, $act, $data);
}

function MakeMainPhoto(){
	global $lang, $config, $config_index, $smarty, $dbconn, $user, $settings;
	$id_file = isset($_REQUEST['id_file']) ? intval($_REQUEST['id_file']) : 0;
	if ($id_file != 0){
		$approved = 1;
		if($settings["use_photo_approve"]){
			$approved = $dbconn->Execute("SELECT status FROM ".USER_UPLOAD_TABLE." WHERE id='{$id_file}' AND id_user='{$user[0]}'")->fields[0];
		}
		if($approved){
			$strSQL = "UPDATE ".USERS_TABLE." SET icon_path='{$id_file}', icon_path_temp='0' WHERE id='{$user[0]}'";
		}else{
			$strSQL = "UPDATE ".USERS_TABLE." SET icon_path_temp='{$id_file}', icon_path='0' WHERE id='{$user[0]}'";
		}
		if ($dbconn->Execute($strSQL))
			echo "ok";
			ListProfile(4);
	}
	else
		echo "error";
}
?>