Current File : /home/users/barii/public_html/finansenl.com.pl/wodki/application/classes/Controller/Auth.php
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Auth extends Controller_Frontend
{
    // te akcje sa dostepne dla wszystkich, nie wymagaja logowania
    //protected $allowed_actions = array('remind', 'login', 'reset', 'activate');
    public $all_actions_allowed = TRUE; 

    public function action_index(){
        $this->request->response = 'hello, world!';
    }

    public function action_logout(){
		
		include("html/fb/src/facebook.php");
		$config = array(
		  'appId' => '421300554675126',
		  'secret' => '68328cc7b8e6a5c6f1761e57b202ac95',
		  'fileUpload' => false, // optional
		  'allowSignedRequest' => true, // optional, but should be set to false for non-canvas apps
		);

		$facebook = new Facebook($config);
		//Cookie::set('fbs_'.$facebook->getAppId(), '', time()-100);
		
		//$facebook->destroySession();
		$redirect = 'auth/unlogin';

		$s = Session::instance();
		$s->delete('relogin_user');
		$s->delete('relogin_licence');
		$s->delete('relogin_setting');
		
		$s->delete('fb_'.$facebook->getAppId().'_user_id');
		
		Cookie::delete('fbm_'.$facebook->getAppId());
		Cookie::delete('fbsr_'.$facebook->getAppId());
		//var_dump($_SESSION);
		//var_dump($_COOKIE);
		//exit;
        Auth::instance()->logout();
		$this->user = NULL;
        Session::instance()->destroy();
		$this->redirect($redirect);
       
    }
	
	public function action_unlogin(){
		echo "Redirect...";
		header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
		header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); 
		
		$this->redirect('auth/unlogin2');
		exit;
	}
	
	public function action_unlogin2(){
		echo "Redirect...";
		header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
		header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); 
		Message::notice(__t('Zostałeś wylogowany, zapraszamy ponownie'));
		$this->redirect('/');
		exit;
	}
	
    public function action_agreement($id = null, $key = null)
    {		
        $redirectURL= '/login';
        if (isset($id) && isset($key)){
            $user   = ORM::factory('address', $id);
       
            try {
                if(Auth::instance()->hash($user->email)===$key ){
					$user->status = 2;
					$user->save();
                    $redirectURL= '/company/preview/'.$user->id;
                }
            }
            catch (Exception $e) {
                Message::error(__t('Link został już wykorzystany.'));
            }
        }
        else {
            Message::error('Błędny link.');
        }
        $this->redirect($redirectURL);
    }	
    
    public function action_activate($c=null, $a=null, $user_name = null, $key = null)
    {		
        $redirectURL= '/Login';
		
		$user_name = $this->request->param('op');
		$key = $this->request->param('op2');
		
        if (isset($user_name) && isset($key)){
			
			$user_name = str_replace("-kropka-",".", str_replace("-malpa-","@", $user_name));
			
            $user   = ORM::factory('User')->where('username','=', $user_name)->find();
            $role   = ORM::factory('Role')->where('name','=','login')->find();
			
            try {
                if(Auth::instance()->hash($user->email)===$key && $user->add('roles', ORM::factory('Role', array('name'=>'login'))) && $user->save()){
                    Auth::instance()->force_login($user->username);
					
                    Message::SUCCESS(__t('Account has been activated and you have been automatically logged in.'));
					
                    $redirectURL= '/account/';
                } else {
					Message::SUCCESS(__t('Wrong link'));
					
                    $redirectURL= '/';
				}
            }
            catch (Exception $e) {
                Message::error(__t('The account has already been activated. Use the login and password provided during registration to login. If you do not know your password, use the reminder option.'));
            }
        }
        else {
            Message::error('Wrong link');
        }
        $this->redirect($redirectURL);
    }
	
	public function action_generate() {
	
	$redirectURL= '/';
		$user_name = !empty( $_GET['u'] ) ? addslashes($_GET['u']) : '';
		$key = !empty( $_GET['e'] ) ? addslashes($_GET['e']) : '';
		//$user_name = $this->request->param('op');
		//$key = $this->request->param('op2');
		
        if (isset($user_name) && isset($key)){
			
			$user_name = str_replace("-kropka-",".", str_replace("-malpa-","@", $user_name));
				
				
				$user = ORM::Factory('User')->where('username','=', $user_name)->find();
				
				 if(Auth::instance()->hash($user->email)===$key ) {
				$password = "";
				
				for( $i=0;$i<8; $i++) {
					$password .= rand(1,9);
				}
		
				$user->password = $password;
				$user->save();
               // $myUser = $rg['user'];
                $title = __t('Przypomnienie danych');
               // $link = 'http://' . Kohana::config('site.domain') . '/auth/reset/' . aurora::uniqueUserLink($myUser->address, $myUser->email);

              //  $username = $myUser->username;
			  $session = Session::instance();
			  $lang_session = $session->get('language');
						$lang = (empty( $lang_session ) ) ? 1 : $lang_session;
						$lang_code = DB::query(Database::SELECT, "SELECT name FROM `languages` WHERE `id` = '$lang'")->execute();
						$lang_code = strtolower($lang_code[0]['name']);
		
                $e_content = View::factory('email/'.$lang_code.'_remind')
                                ->bind('user', $user)
                                ->bind('password', $password);

				aurora::standardEmail($user->email, $title, $e_content);
                $message = __t('Hasło wysłane na Twój email.');
				Message::success(__t('Hasło wysłane na Twój email.'));
				$this->redirect('/');
				
				} else {
				 Message::error('Bad link.');
			$this->redirect('/');
				}
			
			}	 else {
            Message::error('Bad link.');
			$this->redirect('/');
        }
			
    }
	
	
	    public function action_activate_comment($md5hash = null, $id = null)
    {		
        $redirectURL= '/';
        if (isset($md5hash) && isset($id)){
            $user_comment   = ORM::factory('user_comment')->where('id','=', $id)->find();
			if( $user_comment->loaded() ) {
			
				$user_comment->status = 1;
				$user_comment->save();
				
				$user = ORM::Factory('User', $user_comment->user_id);
			
					Message::SUCCESS(__t('Komentarz został aktywowany.'));
					
                    $redirectURL= '/profile/item/'.$user->id.'?layout='.$user->profile_id;
					
			}
			
           
        }
        else {
            Message::error('Błędny link.');
        }
        $this->redirect($redirectURL);
    }
	
    public function action_reset($user_name = null, $key = null)
    {
        if (isset($user_name) && isset($key)){

            $user   = ORM::factory('User')->where('address','=', $user_name)->find();
           
            if(Auth::instance()->hash($user->email)===$key ){

                if ($_POST){
				
				
                    $rg = $this->validResetForm($_POST);
                    $data = $rg['data'];
                    
                    if($rg['status']) {
					
				
                        $user->password =   $data['reset_password'];
                        if ($user->save()){
                            Message::success('Hasło zmienione. Można się zalogować.');
                            $this->redirect('/login');
                        }
                    } else {
					
						$errors = $rg['errors'];
					
					}
                }

                $errors     =   isset ($errors) ? $errors : null;
                $data       =   isset($data) ? $data : array();
                $message    =   isset($message)? $message : null;
                $content    =   'test';

                $this->template->content = View::factory('infosite/reset')
                                            ->set('content', $content)
                                            ->bind('data', $data)
											->bind('user_name', $user_name)
											->bind('key', $key)
                                            ->bind('message',$message)
                                            ->bind('errors', $errors);

            }
        }
	else {
            Message::error('Wrong reset pass link.');
            $this->redirect('/');
        }
        
    }


    public function action_register(){

        if ($_POST){
            $rg = $this->validRegisterForm($_POST);
            $data = $rg['data'];

                if($rg['status']) {
                    // formularz zwalidowany poprawnie
                    $user= ORM::factory('User');
                    $user->username =   $data['register_login'];
                    $user->password =   $data['register_password'];
                    $user->email    =   $data['register_email'];
                    $user->register_date = time();
                    $user->language_id = Kohana::config('site.language_id');
                    $user->user_info = Ac_Misc::get_user_info();

                    if ($user->save()){
                        Ac_Log::instance()->add(-1, $user->id, 7);
                        $title= __t('Witamy w Sprungle');
                        $link = 'http://'.Kohana::config('site.domain').'/auth/activate/'.aurora::uniqueUserLink($data['register_login'], $data['register_email']);
                        
                        // wysalanie maila z linkiem aktywujacym
                        $e_content= View::factory('auth/email/register')
                                ->bind('login',$data['register_login'])
                                ->bind('password',$data['register_password'])
                                ->bind('link', $link)
                                ->bind('title',$title);
                        
                        aurora::standardEmail($data['register_email'], $title, $e_content);
                       
                        $message=   __t('User registered! Check your e-mail for further informations.');
                        unset ($data);
                    }
                }
                else {
                    $errors = $rg['errors'];
                }
            }
           

            $errors     =   isset ($errors) ? $errors : null;
            $data       =   isset($data) ? $data : array();
            $message    =   isset($message)? $message : null;
            $current    =   'Rejestracja';
            $this->template->title = __t('Registration at Sprungle');
            $this->template->content = View::factory('auth/register')
                                            ->bind('current',$current)
                                            ->bind('data', $data)
                                            ->bind('message',$message)
                                            ->bind('errors', $errors);
	}

    public function action_remind() {
        if ($_POST) {
            $rg = $this->validRemindForm($_POST);
            $data = $rg['data'];

            if ($rg['status']) {

                $myUser = $rg['user'];
                $title = __t('Resetowanie hasła w Lejla');
                $link = 'http://' . Kohana::config('site.domain') . '/auth/reset/' . aurora::uniqueUserLink($myUser->username, $myUser->email);

                $username = $myUser->username;
                $e_content = View::factory('auth/email/remind')
                                ->bind('login', $username)
                                ->bind('link', $link)
                                ->bind('title', $title);

                aurora::standardEmail($data['remind_email'], $title, $e_content);
                $message= __t('Your password has been reseted, please check your email.');
                unset ($data);
            } else {
                $errors = $rg['errors'];
            }
        }

        $errors     =   isset($errors) ? $errors : null;
        $data       =   isset($data) ? $data : array();
        $message    =   isset($message) ? $message : null;
        $current    =   'Przypomnij hasło';


        $this->template->title  = __t($current);

        $this->template->content = View::factory('auth/remind')
                        ->bind('data', $data)
                        ->bind('current',$current)
                        ->bind('message', $message)
                        ->bind('errors', $errors);
    }
        
        public function action_login(){

            if ($_POST){
                $rg = $this->validLoginForm($_POST);
                $data = $rg['data'];

                if($rg['status']) {

                    $login = Users::login($data['login_login'], $data['login_password']);
                    if ($login){
                        Message::notice('Zostałeś zalogowany w systemie.');
                        $this->redirect('/');
                    }
                    else {
						$s = ORM::Factory('stat')->where('keyname','=','error_user_login')->find();
						$s->value += 1;
						$s->save();
                        $message= __('Wrong data or account unactive.');
                    }
                   
                }
                else {
                    $errors = $rg['errors'];
                }
            }
            

            $errors     =   isset ($errors) ? $errors : null;
            $data       =   isset($data) ? $data : array();
            $message    =   isset($message)? $message : null;
            $current    =   'login';
            $this->template->title  = __t($current);
            $this->template->content = View::factory('auth/login')
                                            ->bind('data', $data)
                                            ->bind('current',$current)
                                            ->bind('message',$message)
                                            ->bind('errors', $errors);
	}

        protected function validRemindForm(array $data){
            $errors  = array();
            $status = true;
            $user= 0;
            foreach($data as $key => $value) {
                $data[$key] = htmlspecialchars(trim($value));
            }
            if(empty($data['remind_email'])) {
                $errors['remind_email'] = __('fieldRequired');
                $status = false;
            }
            else {
                if(!Validate::email($data['remind_email'])) {
                    $errors['remind_email'] = __('invalidEmail');
                    $status = false;
                }
                else {
                    $user= ORM::factory('User')->where('email','=',$data['remind_email'])->find();
                    if ($user->id > 0){
                        
                        
                    }
                    else {
                        $status = false;
                        $errors['remind_email'] = __('Email not found');
                    }
                }
            }
            return array('status' => $status, 'errors' => $errors, 'data' => $data, 'user'=>$user);
        }

        protected function validRegisterForm(array $data){
            $errors  = array();
            $status = true;
            foreach($data as $key => $value) {
                $data[$key] = htmlspecialchars(trim($value));
            }

            if(empty($data['register_login'])) {
                $errors['register_login'] = __('fieldRequired');
                $status = false;
            }
            else {
                // sprawdzenie czy zawiera znaki zabronione
                $forbiden_chars = array('@', '.');
                foreach($forbiden_chars as $char){
                    if (stripos($data['register_login'], $char)) {
                        $errors['register_login'] = __('notAllowedChars');
                        $status = false;
                    }
                }
                $user= ORM::factory('User')->where('username','=',$data['register_login'])->find();
                if ($user->id > 0){
                    $errors['register_login'] = __('loginUnavailable');
                    $status = false;
                }
            }
            if(empty($data['register_password'])) {
                $errors['register_password'] = __('fieldRequired');
                $status = false;
            }

            if(empty($data['register_email'])) {
                $errors['register_email'] = __('fieldRequired');
                $status = false;
            }
            else {
                if(!Validate::email($data['register_email'])) {
                    $errors['register_email'] = __('invalidEmail');
                    $status = false;
                }
                else {
                    $user= ORM::factory('User')->where('email','=',$data['register_email'])->find();
                    if ($user->id > 0){
                        $errors['register_email'] = __('emailUnavailable');
                        $status = false;
                    }
                }
            }
            return array('status' => $status, 'errors' => $errors, 'data' => $data);
        }

        protected function validLoginForm(array $data){
            $errors  = array();
            $status = true;
            foreach($data as $key => $value) {
                $data[$key] = htmlspecialchars(trim($value));
            }


            if(empty($data['login_login'])) {
                $errors['login_login'] = __('fieldRequired');
                $status = false;
            }
            
            if(empty($data['login_password'])) {
                $errors['login_password'] = __('fieldRequired');
                $status = false;
            }

  
            return array('status' => $status, 'errors' => $errors, 'data' => $data);
        }
        protected function validResetForm(array $data){
            $errors  = array();
            $status = true;
            foreach($data as $key => $value) {
                $data[$key] = htmlspecialchars(trim($value));
            }


            if(empty($data['reset_password'])) {
                $errors['reset_password'] = __('fieldRequired');
                $status = false;
				
            }
            else {
                if(strlen($data['reset_password']) < 6) {
                    $errors['reset_password'] = __('Haslozakrotkie');
                    $status = false;
                } 
            }



            return array('status' => $status, 'errors' => $errors, 'data' => $data);
        }

} // End Welcome