<?php
/**
* @author:  Bunzia Alexander <nifus@mail.ru> <http://www.weblancer.net/users/nifus/>
* @copyright: Copyright (c) 2010, Bunzia Alexander
* @version: 1.0
* @license: http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/


class users_profile{

	private $error = false;
	private $act = '';
	
	function __construct(){
	global $MAIN_PAGE;
		define('M_PATH',MAIN_SOURCE_PATH.'/modules/'.$MAIN_PAGE -> dirname() );
		define('M_URL',MAIN_SOURCE_URL.'/modules/'.$MAIN_PAGE -> dirname() );
		include_once(M_PATH.'/inc/url.php');
		include_once(MAIN_PATH.'/tmp/meta/users.php');
		include_once(MAIN_PATH.'/source/inc/class.html.php');
		include_once(M_PATH.'/inc/class.users.php');
		if ( !empty($_REQUEST['act']) ){
			$this -> act = $_REQUEST['act'];
		}
		
		include_once(MAIN_SOURCE_PATH.'/ext/ajax/JsHttpRequest.php');
		new JsHttpRequest($MAIN_PAGE -> charset());
		$this -> act = !empty($_REQUEST['act']) ? $_REQUEST['act'] : $this -> act;
		$GLOBALS['_RESULT']['id_request'] = !empty($_REQUEST['id_request']) ? $_REQUEST['id_request'] : 0;
		
	}
	
	
	public function get(){
	global $MAIN_PAGE;
		$func = $this -> act;
		if ( !method_exists($this ,$func) ){
			sys_error(ERROR_404);
		}
		$MAIN_PAGE -> set_key($func);
		return  $this -> $func();
	}
	
  /**
  * профайл
  *
  */
  private function profile(){	
    $u = users::load_id($_GET['uid']);
    if ( false===$u ){
      sys_error(ERROR_404);
    }
    $t = new PHPTAL();
    $t -> setSnippet( 'users','profile');
    
    $t -> name = $u -> name();
    $t -> avatar_src = $u -> avatar_src();
    $t -> points = 12;//$u -> points();
    $t -> uid = $u -> id();
      //  свой профайл
    $t -> is_own = ($_GET['uid']==MAIN_USER) ? 1 : 0;
   
      // подключаем библиотеку для загрузки изображений
    upload_img::include_files();
        
    return $t -> execute();
  }	
  

	/**
  * Форма авторизации пользователя на сайте
  *
 */
  private function login_form($error=''){	
  
    $t = new PHPTAL();
    $t -> setSnippet( 'users','login_form');
    $t -> error = $error;

    return $t -> execute();
  } 
  
   /**
  * обработка формы авторизации
  *
  */
	private function login(){		
	global $MAIN_USER,$MAIN_PAGE;
		//sys_block_disable();
		Header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); //Дата в прошлом 
    Header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 
    Header("Pragma: no-cache"); // HTTP/1.1 
    Header("Last-Modified: ".gmdate("D, d M Y H:i:s")."GMT");
		if ( empty($MAIN_USER) ){
			$MAIN_USER = users::auth();
		}
	  
		if (  $MAIN_USER -> group()!=3 ){
			sys_redirect( MAIN_URL );	
		}
		
		$u = self::inc_login_site($_POST['auth_login'],$_POST['auth_password'],1,$_POST['auth_email']);

		if ( false===$u ){
		  $MAIN_PAGE -> set_title( 2, $MAIN_PAGE -> meta_title( $this -> act ) );
		  return $this -> login_form(M_USERS_ERROR_LOGIN);
    }else{
      sys_redirect( MAIN_URL );	
    }

  }
 
  /**
  * выход
  *
  */
  private function logout(){	
    Header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); //Дата в прошлом 
    Header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 
    Header("Pragma: no-cache"); // HTTP/1.1 
    Header("Last-Modified: ".gmdate("D, d M Y H:i:s")."GMT");
    sys_block_disable();
		users::logout();
		sys_redirect( MAIN_URL );	
		exit();
  }	
  
   
 	/**
  * Форма восстановления пароля пользователя на сайте
  *
 */
  private function forget_form($e=''){	
  global $MAIN_PAGE;
    $t = new PHPTAL();
    $t -> setSnippet( 'users','users_forget_form');
    $t -> error = $e;
    $t -> end = 0;
    $MAIN_PAGE -> set_title( 2, $MAIN_PAGE -> meta_title( $this -> act ) );    
    return $t -> execute();
  }  
  
  
 	/**
  * Высылаем на запрос
  *
 */
  private function forget_request($error=''){	
  global $MAIN_PAGE;
    
    $u = users::load_email($_POST['forget_email']);
    if ( false===$u){
      return $this -> forget_form('Пользователь не найден');
    }
     
    include_once(MAIN_SOURCE_PATH.'/inc/class.mail.php');
	  $m =  mail::load('forget_pass');
	  if ( false===$m ){
	    sys_error(ERROR_500);
	  }
	  
	  $m -> set('MAIN_URL',MAIN_URL );
	  $m -> set('u_name',  $u -> name()  );
	  $m -> set('forget_url', sys_url(URL_USERS_FORGET_END, $u -> id(),$u-> act_code() ) );
	  $m -> send_mail(  $u -> email() ); 
      
    $t = new PHPTAL();
    $t -> setSnippet( 'users','users_forget_form');
    $t -> end = 1;
    $t -> error = false;
    $MAIN_PAGE -> set_title( 2, $MAIN_PAGE -> meta_title( 'forget_form' ) );    
    return $t -> execute();
  }    
  
  /**
  * меняем пароль и высылаем его на почту.
  *
  */
  private function  forget_end(){
  global $MAIN_PAGE;
    $MAIN_PAGE -> set_title( 2, $MAIN_PAGE -> meta_title( 'forget_form' ) );
     $t = new PHPTAL();
     $t -> setSnippet( 'users','users_forget_end');
      
     $u = new usersQuery('u');
     if ( false=== $u -> where_id($_GET['id'])  ){
  
       $t -> msg =  M_USERS_ERROR_LINK;
       return $t -> execute();
     }
     
     if ( false=== $u -> where_actcode($_GET['code'])  ){
       
       $t -> msg =  M_USERS_ERROR_LINK;
       return $t -> execute();
     }
     
     //$u -> set_debug(1);
     $u -> get('u_id',false);
     if ( !$u -> get_count_rows() ){
       $t -> msg =  M_USERS_ERROR_LINK;
       return $t -> execute();
     }
     list($u_id) = $u -> row();
      //  загружаем пользователя
     $u = users::load_id($u_id);
     $new_pass = sys_str_rand(10);
     $u -> set('u_pass',$new_pass);
     $u -> set('u_act_code',sys_str_rand(5));
     $u -> update();
    
     include_once(MAIN_SOURCE_PATH.'/inc/class.mail.php');
	   $m =  mail::load('new_pass');
	   if ( false===$m ){
	    sys_error(ERROR_500);
	   }
	   $m -> set('name',  $u -> name()  );
	   $m -> set('login', $u -> login() );
	   $m -> set('pass',$new_pass);
	   $m -> set('MAIN_URL',MAIN_URL);
	   
	   $m -> send_mail(  $u -> email() );
     
 
 
    $t -> msg = 'Мы сгенерировали для вас новый пароль. Он выслан вам на E-mail.';
    //$t -> error = 'Новый пароль выслан вам на e-mail';
     return $t -> execute();
  }
  
  /**
  * Выводит ajax окно для ввода логина/пароля
  *
  */
  private function ajax_login_form(){	
    sys_block_disable();
    $t = new PHPTAL();
    $t -> setSnippet( 'users','ajax_login_form');
    echo '<?xml version="1.0" encoding="UTF-8"?><body><title>'.M_USERS_LOGIN_TITLE.'</title><content><![CDATA['.$t -> execute().']]></content></body>';
		exit();
  }
  
  /**
  * обработка формы авторизации
  *
  */
  private function ajax_auth(){	
  global $MAIN_USER;
		sys_block_disable();
		if ( empty($MAIN_USER) ){
			$MAIN_USER = users::auth();
		}
		if (  $MAIN_USER -> group()!=3 ){
			sys_redirect( MAIN_URL );	
		}
		$u = self::inc_login_site($_POST['auth_login'],$_POST['auth_password'],$_POST['auth_save'],$_POST['auth_email']);
		if ( false===$u ){
		  echo M_USERS_ERROR_LOGIN;
    }
    exit();
  } 
  
  /**
  * обработка формы редактирования профиля
  *
  */
  private function ajax_edit(){	
  global $MAIN_USER;
		sys_block_disable();
		$q = new usersQuery('q');
		if ( false===$q -> where_id($_GET['id']) ){
      sys_error(ERROR_404);
    }
		$q -> get('*');
		$row = $q -> row();
		if ( $row['u_id']!=MAIN_USER ){
		  sys_error(ERROR_403);
		}
		
		$a = new upload_img('image');
		$a -> set_max_size( 5000000 );
		$a -> set_crop(82,72);
		$a -> set_file($row['u_avatar']);
		$a -> set_path( 'users/ava');
		$a -> set_base( MAIN_URL.'/media/users/ava');
		$row['upl_img'] = $a -> get('img',1,'form[u_avatar]'); 
		  
	  $t = new PHPTAL();
    $t -> setSnippet( 'users','ajax_edit_profile');
    $t -> row = $row;
    
    $GLOBALS['_RESULT']['content'] =  $t -> execute();
		$GLOBALS['_RESULT']['title'] = M_USERS_PROFILE_TITLE;
	
    exit();
  } 
  
  /**
  * Сохраняем изменённый профиль
  *
  */
  private function ajax_save(){	
  global $MAIN_USER;
		sys_block_disable();
		$u = users::load_id(MAIN_USER);
		//$u -> set_debug(1);
		if ( false===$u ){
		  sys_error(ERROR_403);
		}
		if ( $u -> active()==0 ){
		  sys_error(ERROR_403);
		}
		//var_dump( $_POST['form']);
		try{
	    $u -> set('u_name',$_POST['form']['u_name']);
	    $u -> set('u_avatar',$_POST['form']['u_avatar']);
	    $u -> set('u_pass',$_POST['form']['u_pass']);
	    $u -> set('u_pass_re',$_POST['form']['u_pass_re']);
	    $u -> update();
	 }catch(Exception $e){
		  echo  $e -> getMessage();
		  exit();
		}
    exit();
  } 
  

  

  
  
   private function ajax_forget(){
	  sys_block_disable();
	  $t = new PHPTAL();
    $t -> setSnippet( 'users','ajax_forget_form');
    $t -> forget_send = false;
    $GLOBALS['_RESULT']['content'] =  $t -> execute();
		$GLOBALS['_RESULT']['title'] = M_USERS_FORGET_TITLE;
    exit();
		
  }
  
   private function  ajax_forget_send(){
    sys_block_disable();
   
     $u = new usersQuery('u');
     if ( false=== $u -> where_email($_POST['forget_email'])  ){
        echo M_USERS_ERROR_EMAIL;
        exit(); 
     }
     $u -> get(' u_id,u_act_code as forget_url',false);
     list($u_id,$forget_url) = $u -> row();
     
     
     include_once(MAIN_SOURCE_PATH.'/inc/class.mail.php');
	   $m =  mail::load('forget_pass');
	   $m -> set('forget_url',$forget_url);
	   $m -> send_mail($_POST['forget_email'] );
	    
	   $t = new PHPTAL();
     $t -> setSnippet( 'users','ajax_forget_form');
     $t -> forget_send = true;
     $GLOBALS['_RESULT']['msg'] =  $t -> execute();
		 
     exit();
  }
  

 
 
  
  private function inc_login_site($l,$p,$save,$email=''){
  
    if ( empty($l) ){
		  $u = users::load_email($email);
		}else{
		  $u = users::load_login($l);
		}
		if ( $u===false ){
			return false;
		}
		if ( $u -> pass()!=users::make_pass($p) ){
			return false;
		}
    if ( $u -> get('u_active')==0 ){
      return false;
    }
		$u -> user_session($save);
		return $u;
	}
	
	

	
				

} //  end class
?>
