<?php
if( ! defined( 'DATALIFEENGINE' ) ) {die( "Hacking attempt!" );}

include_once SYSTEM_DIR . '/classes/parse.class.php';
$parse = new ParseFilter( );
$parse->safe_mode = true;

//Верефицируем E-Mail
if ( $doaction == 'validating' AND $is_logged ){
    $validating = ( isset( $_REQUEST['id'] ) ) ? strval( $_REQUEST['id'] ) : '';
    $validating = explode( '||', @base64_decode( @rawurldecode( $validating ) ) );
    if ( sizeof( $validating ) != 4 ) die( 'ID not valid!' );

    $validating[0] = intval( $validating[0] );
    $validating[1] = trim( $db->safesql( $parse->process( $validating[1] ) ) );
    $validating[2] = trim( $db->safesql( $parse->process( $validating[2] ) ) );

    if ( md5( md5( md5( $member_id['name'] . $validating[2] . DBHOST . DBNAME . $config['key'] ) ) ) != md5( $validating[3] ) ) die( 'ID not valid!' );

          if ( $member_id['user_id'] == $validating[0] AND $validating[1] == $member_id['email'] )
          {
              $db->query( "UPDATE " . USERPREFIX . "_users set email='{$validating[2]}' WHERE user_id='{$member_id['user_id']}'" );
              $db->query(" UPDATE " .PREFIX. "_subscribe SET email='{$validating[2]}' WHERE user_id='{$member_id['user_id']}'" );
              msgbox( $lang['all_info'], 'E-Mail Активирован!' );
          } else die( 'data not valid!' );
}

//Обновление информации о пользователе
if( $allow_userinfo and $doaction == "adduserinfo" ) {
    $stop = false;
   	$id = intval($_POST['id']);

    if( !$is_logged OR $_POST['dle_allow_hash'] == "" OR $_POST['dle_allow_hash'] != $dle_login_hash OR !$id) {die( "Hacking attempt! User ID not valid" );}
    $row = $db->super_query( "SELECT * FROM " . USERPREFIX . "_users WHERE user_id = '{$id}'" );
    if( !$is_logged or !($member_id['user_id'] == $row['user_id'] or $member_id['user_group'] == 1) ) {$stop = $lang['news_err_13'];
   	} else {
	$parse->allow_url = $user_group[$member_id['user_group']]['allow_url'];
    $parse->allow_image = $user_group[$member_id['user_group']]['allow_image'];
	
	$password1 = $_POST['password1'];
	$password2 = $_POST['password2'];

    if( $_POST['mail_lc'] ) {$mail_lc = 1;} else {$mail_lc = 0;}
    if( $_POST['allow_mail'] ) {$allow_mail = 0;} else {$allow_mail = 1;}
    if( $_POST['repa_off'] ) {$repa_off = 1;} else {$repa_off = 0;}

	$altpass = md5( $_POST['altpass'] );
    $info = $db->safesql( $parse->BB_Parse( $parse->process( $_POST['info'] ), false ) );

    $not_allow_symbol = array ("\x22", "\x60", "\t", '\n', '\r', "\n", "\r", '\\', ",", "/", "¬", "#", ";", ":", "~", "[", "]", "{", "}", ")", "(", "*", "^", "%", "$", "<", ">", "?", "!", '"', "'", " " );
    $email = $db->safesql(trim( str_replace( $not_allow_symbol, '', strip_tags( stripslashes( $_POST['email'] ) ) ) ) );
	
	$fullname = $db->safesql( $parse->process( $_POST['fullname'] ) );
	$land = $db->safesql( $parse->process( $_POST['land'] ) );
    $icq = intval( str_replace("-", "", $_POST['icq'] ) ); if( ! $icq ) $icq = "";
    $skype = $db->safesql( $parse->process( $_POST['skype'] ) );
	
    if ($_POST['allowed_ip']) {$_POST['allowed_ip'] = str_replace( "\r", "", trim( $_POST['allowed_ip'] ) );
        $allowed_ip = str_replace( "\n", "|", $_POST['allowed_ip'] );
      	$temp_array = explode ("|", $allowed_ip);
      	$allowed_ip	= array();
      	if (count($temp_array)) {
      	    foreach ( $temp_array as $value ) {
      		$value1 = str_replace( "*", "0", trim($value) );
      		$value1 = ip2long($value1);
      	    if( $value1 != -1 AND $value1 !== FALSE ) $allowed_ip[] = trim( $value );
      		}}
        if ( count($allowed_ip) ) $allowed_ip = $db->safesql( $parse->process( implode("|", $allowed_ip) ) ); else $allowed_ip = "";
    } else $allowed_ip = "";
	
	if( $user_group[$row['user_group']]['allow_signature'] ) {$signature = $db->safesql( $parse->BB_Parse( $parse->process( $_POST['signature'] ), false ) );
	} else $signature = "";

    //Загружаем аватару
	$image = $_FILES['image']['tmp_name'];
	$image_name = $_FILES['image']['name'];
	$image_size = $_FILES['image']['size'];
	$img_name_arr = explode( ".", $image_name );
    $type = totranslit( end( $img_name_arr ) );
	if( $image_name != "" ) $image_name = totranslit( stripslashes( $img_name_arr[0] ) ) . "." . totranslit( $type );
    if( strpos ( $image_name, "php" ) !== false ) die("Hacking attempt!");
	if( is_uploaded_file( $image ) and ! $stop ) {
		if( intval( $user_group[$member_id['user_group']]['max_foto'] ) > 0 ) {
			if( $image_size < ($config['max_ava_size'] * 1024) ) {
				$allowed_extensions = array ("jpg", "png", "jpe", "jpeg", "gif" );
				if( in_array( $type, $allowed_extensions ) AND $image_name ) {
					include_once SYSTEM_DIR . '/classes/thumb.class.php';
					$res = @move_uploaded_file( $image, ROOT_DIR . "/uploads/fotos/" . $row['user_id'] . "." . $type );
					if( $res ) {
						@chmod( ROOT_DIR . "/uploads/fotos/" . $row['user_id'] . "." . $type, 0666 );
						$thumb = new thumbnail( ROOT_DIR . "/uploads/fotos/" . $row['user_id'] . "." . $type );
						if( $thumb->size_auto( $user_group[$member_id['user_group']]['max_foto'] ) ) {
							$thumb->jpeg_quality( $config['jpeg_quality'] );
							$thumb->save( ROOT_DIR . "/uploads/fotos/foto_" . $row['user_id'] . "." . $type );
						} else {@rename( ROOT_DIR . "/uploads/fotos/" . $row['user_id'] . "." . $type, ROOT_DIR . "/uploads/fotos/foto_" . $row['user_id'] . "." . $type );}
						@chmod( ROOT_DIR . "/uploads/fotos/foto_" . $row['user_id'] . "." . $type, 0666 );
						$foto_name = "foto_" . $row['user_id'] . "." . $type;
						$db->query( "UPDATE " . USERPREFIX . "_users set foto='$foto_name' where user_id = '{$id}'" );
					} else $stop .= $lang['news_err_14'];
				} else $stop .= $lang['news_err_15'];
			} else $stop .= $lang['news_err_16'];
		} else $stop .= $lang['news_err_32'];
		@unlink( ROOT_DIR . "/uploads/fotos/" . $row['user_id'] . "." . $type );
	}if( $_POST['del_foto'] == "yes" AND !$stop) {
		@unlink( ROOT_DIR . "/uploads/fotos/" . $row['foto'] );
		$db->query( "UPDATE " . USERPREFIX . "_users set foto='' WHERE user_id = '{$id}'" );
	}
    
    //Добавлено дополнительное фото
    $image = $_FILES['image1']['tmp_name'];
    $image_name = $_FILES['image1']['name'];
    $image_size = $_FILES['image1']['size'];
	$img_name_arr = explode(".",$image_name);
    $type = totranslit( end( $img_name_arr ) );
    if($image_name != "") $image_name  = totranslit(stripslashes($img_name_arr[0])).".".totranslit($type);
	if (is_uploaded_file($image) AND !$stop) {
		if ($image_size < 2000000) {
		$allowed_extensions = array("jpg", "png", "jpe", "jpeg", "gif");
        if( in_array( $type, $allowed_extensions ) AND $image_name ) {
            include_once SYSTEM_DIR.'/classes/thumb.class.php';
	        $res = @move_uploaded_file($image, ROOT_DIR."/uploads/photos/".$row['user_id'].".".$type);
	        if ($res) {
	            @chmod(ROOT_DIR."/uploads/photos/".$row['user_id'].".".$type, 0666);
	            $thumb=new thumbnail(ROOT_DIR."/uploads/photos/".$row['user_id'].".".$type);
	            if ($thumb->size_auto($config['sauto'])) {$thumb->jpeg_quality($config['jpeg_quality']);
		            $thumb->save(ROOT_DIR."/uploads/photos/foto_".$row['user_id'].".".$type);
                } else {@rename(ROOT_DIR."/uploads/photos/".$row['user_id'].".".$type, ROOT_DIR."/uploads/photos/foto_".$row['user_id'].".".$type);}
	            @chmod(ROOT_DIR."/uploads/photos/foto_".$row['user_id'].".".$type, 0666);
	            $foto_name1= "foto_".$row['user_id'].".".$type;
	$db->query("UPDATE " . USERPREFIX . "_users set photo='$foto_name1' where user_id = '{$id}'" );
	        } else $stop .= $lang['news_err_14'];
	    } else $stop .= $lang['news_err_15'];
	} else $stop .= $lang['news_err_16'];
	@unlink (ROOT_DIR."/uploads/photos/".$row['user_id'].".".$type);
    }if ($_POST['del_foto1'] == "yes" AND !$stop) {
	@unlink (ROOT_DIR."/uploads/photos/".$row['photo']);
	$db->query("UPDATE " . USERPREFIX . "_users set photo='' where user_id = '{$id}'" );
}
//!Добавлено дополнительное фото

	if( strlen( $password1 ) > 0 ) {
		$altpass = md5( $altpass );
		if( $altpass != $member_id['password'] ) {$stop .= $lang['news_err_17'];}
		if( $password1 != $password2 ) {$stop .= $lang['news_err_18'];}
		if( strlen( $password1 ) < 6 ) {$stop .= $lang['news_err_19'];}
        if ($member_id['user_id'] == $row['user_id'] AND $user_group[$member_id['user_group']]['admin_editusers']) {$stop .= $lang['news_err_42'];}
	}
	
    if( empty( $email ) OR strlen( $email ) > 50 OR @count(explode("@", $email)) != 2) {$stop .= $lang['news_err_21'];}
    if ($member_id['user_id'] == $row['user_id'] AND $email != $member_id['email'] AND $user_group[$member_id['user_group']]['admin_editusers']) {$stop .= $lang['news_err_42'];}
	if( intval( $user_group[$member_id['user_group']]['max_info'] ) > 0 and strlen( $info ) > $user_group[$member_id['user_group']]['max_info'] ) {$stop .= $lang['news_err_22'];}
    if (preg_match ("/href|url|http|www|\.ru|\.com|\.net|\.info|\.org/i", $_POST['info'])){$stop .= $lang['news_err_url'];}
	if( intval( $user_group[$member_id['user_group']]['max_signature'] ) > 0 and strlen( $signature ) > $user_group[$member_id['user_group']]['max_signature'] ) {$stop .= $lang['not_allowed_sig'];}
	if( strlen( $fullname ) > 100 ) {$stop .= $lang['news_err_23'];}
	if ( preg_match( "/[\||\'|\<|\>|\"|\!|\]|\?|\$|\@|\/|\\\|\&\~\*\+]/", $fullname ) ) {$stop .= $lang['news_err_35'];}
	if( strlen( $land ) > 100 ) {$stop .= $lang['news_err_24'];}
	if ( preg_match( "/[\||\'|\<|\>|\"|\!|\]|\?|\$|\@|\/|\\\|\&\~\*\+]/", $land ) ) {$stop .= $lang['news_err_36'];}
	if( strlen( $icq ) > 20 ) {$stop .= $lang['news_err_25'];}
    if( strlen( $skype ) > 32 ) {$stop .= 'Слишком длинный логин Skype';}
    if ( preg_match( "/[\||\'|\<|\>|\"|\!|\]|\?|\$|\@|\/|\\\|\&\~\*\+]/", $skype ) ) {$stop .= 'Недопустимые символы в логине Skype';}
	if( $parse->not_allowed_tags ) {$stop .= $lang['news_err_34'];}
	if( $parse->not_allowed_text ) {$stop .= $lang['news_err_38'];}
	
	$db->query( "SELECT name FROM " . USERPREFIX . "_users WHERE email = '$email' AND user_id != '{$id}'" );
	if( $db->num_rows() ) {$stop .= $lang['reg_err_8'];}
	$db->free();
    }
    if( $stop ) {msgbox( $lang['all_err_1'], $stop );
	} else {

    //Проверяем E-Mail, если изменен, то требуем подтверждения
    if ( $email != $member_id['email'] AND $config['registration_type'] ){
                  include_once SYSTEM_DIR . '/classes/mail.class.php';
                  $mail = new dle_mail( $config );
                  $row = $db->super_query( "SELECT template FROM " . PREFIX . "_email where name='reg_mail' LIMIT 0,1" );
                  $row['template'] = stripslashes( $row['template'] );
                  $idlink = rawurlencode( base64_encode( $member_id['user_id'] . '||' . $member_id['email'] . '||' . $email . '||' . md5( md5( $member_id['name'] . $email . DBHOST . DBNAME . $config['key'] ) ) ) );
                  $row['template'] = str_replace( "{%username%}", $member_id['name'], $row['template'] );
                  $row['template'] = str_replace( "{%validationlink%}", $config['http_home_url'] . 'index.php?subaction=userinfo&user=' . urlencode( $member_id['name'] ) . '&doaction=validating&id=' . $idlink, $row['template'] );
                  $row['template'] = str_replace( "{%password%}", 'Засекречен', $row['template'] );
                  $mail->send( $email, $lang['reg_subj'], $row['template'] );

                  if ( $mail->send_error ) msgbox( $lang['all_info'], $mail->smtp_msg );
                  msgbox( $lang['all_info'], 'Что бы изменить E-Mail, его нужно подтвердить' );
                  $email = $member_id['email'];
              }
		
		if( strlen( $password1 ) > 0 ) {
			$password1 = md5( md5( $password1 ) );
			$sql_user = "UPDATE " . USERPREFIX . "_users set fullname='$fullname', mail_lc='$mail_lc', land='$land', icq='$icq', skype='$skype', email='$email', info='$info', signature='$signature', password='$password1', allow_mail='$allow_mail', repa_off='$repa_off', allowed_ip='$allowed_ip' where user_id = '{$id}'";
		} else {$sql_user = "UPDATE " . USERPREFIX . "_users set fullname='$fullname', mail_lc='$mail_lc', land='$land', icq='$icq', skype='$skype', email='$email', info='$info', signature='$signature', allow_mail='$allow_mail', repa_off='$repa_off', allowed_ip='$allowed_ip' where user_id = '{$id}'";}
		$db->query( $sql_user );
		if ( $_POST['subscribe'] ) $db->query( "DELETE FROM " . PREFIX . "_subscribe WHERE user_id = '{$row['user_id']}'" );
	}
}

//####################################################################################################################
//         Просмотр профиля пользователя
//####################################################################################################################
$user_found = FALSE;
if( preg_match( "/[\||\'|\<|\>|\"|\!|\?|\$|\@|\/|\\\|\&\~\*\+]/", $name ) ) die("Not allowed user name!");
$sql_result = $db->query( "SELECT * FROM " . USERPREFIX . "_users where name = '$user'" );
$tpl->load_template( 'userinfo.tpl' );
while ( $row = $db->get_row( $sql_result ) ) {
	$user_found = TRUE;
	if( $row['banned'] == 'yes' ) $user_group[$row['user_group']]['group_name'] = $lang['user_ban'];

    if( $row['allow_mail'] ) {
        if ( !$user_group[$member_id['user_group']]['allow_feed'] AND $row['user_group'] != 1 )$tpl->set( '{email}', $lang['news_mail'], $output );
		else $tpl->set( '{email}', "<a href=\"$PHP_SELF?do=feedback&amp;user=$row[user_id]\">" . $lang['news_mail'] . "</a>" );
	} else {$tpl->set( '{email}', $lang['news_mail'], $output );}

	if ( $user_group[$member_id['user_group']]['allow_pm'] )$tpl->set( '{pm}', "<a href=\"$PHP_SELF?do=pm&amp;doaction=newpm&amp;user=" . $row['user_id'] . "\">" . $lang['news_pmnew'] . "</a>" );
	else $tpl->set( '{pm}', $lang['news_pmnew'], $output );

	if( ! $row['allow_mail'] ) $mailbox = "checked"; else $mailbox = "";
    if( $row['repa_off'] ) $repa_off = "checked"; else $repa_off = "";

    $tpl->set( '{repa_off}', "<input type=\"checkbox\" name=\"repa_off\" value=\"1\" ".$repa_off."> Отключить репутацию");

    if( $row['foto'] and (file_exists( ROOT_DIR . "/uploads/fotos/" . $row['foto'] )) ) $tpl->set( '{foto}', $config['http_home_url'] . "uploads/fotos/" . $row['foto'] );
    else $tpl->set( '{foto}', "{THEME}/images/noavatar.png" );

if ($row['photo'] AND (file_exists(ROOT_DIR."/uploads/photos/".$row['photo']))){
    include_once SYSTEM_DIR.'/classes/thumb.class.php';
    $image = ROOT_DIR."/uploads/photos/".$row['photo'];
    $thumb=new thumbnail($image);
    $thumb->size_auto($config['sauto1']);
    $thumb->save(ROOT_DIR."/uploads/photos/thumb/".$row['photo']);
    @chmod (ROOT_DIR."/uploads/photos/thumb/".$row['photo'], 0666);
    $tpl->set('{photo_thumb}', $config['http_home_url']."uploads/photos/thumb/".$row['photo']);
    }else{$tpl->set('{photo_thumb}', "{THEME}/images/nophoto.png");
    }$tpl->set('{photo}', $config['http_home_url']."uploads/photos/".$row['photo']);
	
	$tpl->set( '{hidemail}', "<input type=\"checkbox\" name=\"allow_mail\" value=\"1\" " . $mailbox . " /> " . $lang['news_noamail'] );
	$tpl->set( '{usertitle}', stripslashes( $row['name'] ) );
	$tpl->set( '{fullname}', stripslashes( $row['fullname'] ) );
	if( $row['icq'] ) $tpl->set( '{icq}', stripslashes( $row['icq'] ) ); else $tpl->set( '{icq}', 'неуказано' );
    if( $row['skype'] ) $tpl->set( '{skype}', stripslashes( $row['skype'] ) ); else $tpl->set( '{skype}', 'неуказано' );
    $tpl->set( '{land}', stripslashes( $row['land'] ) );
	$tpl->set( '{info}', stripslashes( $row['info'] ) );
	$tpl->set( '{editmail}', stripslashes( $row['email'] ) );
	$tpl->set( '{comm_num}', $row['comm_num'] );
	$tpl->set( '{news_num}', $row['news_num'] );

$tbx_up = mksize($row['uploaded']);
$tbx_dw = mksize($row['downloaded']);
$tbx_ratio = ($row['downloaded']>0) ? round($row['uploaded']/$row['downloaded'],2) : 0;
$tpl->set('{tbx_up}', $tbx_up);
$tpl->set('{tbx_dw}', $tbx_dw);
$tpl->set('{tbx_ratio}', $tbx_ratio);

if ( ($row['lastdate'] + $config['user_online']*60) > $_TIME ) $tpl->set('{online}', "<font color=\"green\">Online</font>"); else $tpl->set('{online}', "<font color=\"red\">Offline</font>");
$tpl->set('{code_name}', urlencode($row['name']));

if($row['mail_lc']) $mail_lc = "checked"; else $mail_lc = "";
$tpl->set( '{mail_lc}', "<input type=\"checkbox\" name=\"mail_lc\" value=\"1\" " . $mail_lc . "> Получать уведомление на почту о новых ЛС" );

if( $row['status'] != "" ) {$tpl->set( '{status}', $row['status'] );} else {$tpl->set( '{status}',  $user_group[$row['user_group']]['group_name'] );}
$tpl->set( '{registration}', langdate( "j F Y H:i", $row['reg_date'] ) );
$tpl->set( '{lastdate}', langdate( "j F Y H:i", $row['lastdate'] ) );
$tpl->set('{stag}', stag(reg_date));

    $_IP = $db->safesql( $_SERVER['REMOTE_ADDR'] );

	$tpl->set( '{ip}', $_IP );
	$tpl->set( '{allowed-ip}', stripslashes( str_replace( "|", "\n", $row['allowed_ip'] ) ) );
	$tpl->set( '{editinfo}', $parse->decodeBBCodes( $row['info'], false ) );
	
	if( $user_group[$row['user_group']]['allow_signature'] ) $tpl->set( '{editsignature}', $parse->decodeBBCodes( $row['signature'], false ) );
	else $tpl->set( '{editsignature}', $lang['sig_not_allowed'] );
	
	if( $row['comm_num'] ) {$tpl->set( '{comments}', "<a href=\"$PHP_SELF?do=lastcomments&amp;userid=" . $row['user_id'] . "\">" . $lang['last_comm'] . "</a>" );
	} else {$tpl->set( '{comments}', $lang['last_comm'] );}
	
	if( $row['news_num'] ) {
			$tpl->set( '{news}', "<a href=\"" . $config['http_home_url'] . "user/" . urlencode( $row['name'] ) . "/news/" . "\">" . $lang['all_user_news'] . "</a>" );
	} else {
		$tpl->set( '{news}', $lang['all_user_news'] );
	}
	
	if( $row['signature'] and $user_group[$row['user_group']]['allow_signature'] ) {
		$tpl->set_block( "'\\[signature\\](.*?)\\[/signature\\]'si", "\\1" );
		$tpl->set( '{signature}', stripslashes( $row['signature'] ) );
	} else {
		$tpl->set_block( "'\\[signature\\](.*?)\\[/signature\\]'si", "" );
	}

	@include (SYSTEM_DIR.'/modules/reputation.php');

	if( $is_logged and ($member_id['user_id'] == $row['user_id'] or $member_id['user_group'] == 1) ) {
		$tpl->set( '{edituser}', "[ <a href=\"javascript:ShowOrHide('options')\">" . $lang['news_option'] . "</a> ]" );
	} else $tpl->set( '{edituser}', "" );
	
	if( $is_logged and ($member_id['user_id'] == $row['user_id'] or $member_id['user_group'] == 1) ) {
		$tpl->set( '[not-logged]', "" );
		$tpl->set( '[/not-logged]', "" );
	} else $tpl->set_block( "'\\[not-logged\\](.*?)\\[/not-logged\\]'si", "<!-- profile -->" );

if( $is_logged and ($user_group[$member_id['user_group']]['admin_editusers']) ) {
$tpl->set( '{adminim}', "[ <a href=\"javascript: void(0)\" onclick=\"window.open('/".$config['admin_path']."?mod=editusers&action=edituser&id=".$row['user_id']."', 'windowname1', 'width=600, height=650')\"><font color=red>Управление</font></a> ]");
$tpl->set( '[admin]', "" );
$tpl->set( '[/admin]', "" );
} else {
$tpl->set( '{adminim}', "" );
$tpl->set_block( "'\\[admin\\](.*?)\\[/admin\\]'si", "<!-- profile -->" );
}
	
    $link_profile = $config['http_home_url'] . "user/" . urlencode( $row['name'] ) . "/";
	
	if( $is_logged and ($member_id['user_id'] == $row['user_id'] or $member_id['user_group'] == 1) ) {
		$tpl->copy_template = "<form  method=\"post\" name=\"userinfo\" id=\"userinfo\" enctype=\"multipart/form-data\" action=\"{$link_profile}\">" . $tpl->copy_template . "
		<input type=\"hidden\" name=\"doaction\" value=\"adduserinfo\" />
		<input type=\"hidden\" name=\"id\" value=\"{$row['user_id']}\" />
		<input type=\"hidden\" name=\"dle_allow_hash\" value=\"{$dle_login_hash}\" />
		</form>";
	}$tpl->compile( 'content' );
}

$tpl->clear();
$db->free( $sql_result );

if( $user_found == FALSE ) {
	$allow_active_news = false;
	msgbox( $lang['all_err_1'], $lang['news_err_26'] );
}
?>