<?php
 
    class page{
        
        static $instance , $i;
        public $html , $css , $js , $left_box , $fields , $head , $body, $title, $description , $keywords, $memory_field_valid , $handler;
        
        // Domyslna nazwa grupy pól
        public $form_name = 'default';
        
        // Tryb walidacji
        public $valid_now = false;
        public $db_status = false;
        
        // Walidacja pola
        public $field_valid = array(
            'name' => false, // Domyślna nazwa, NIE WARTOŚĆ PARAMETRU name=""!
            'fname' => false, // Wartość pola name
            'group' => false, // Grupa parametrow batch
            'bname' => false, // Nazwa w tablicy db::$intance->batch
            'value' => false,
            'int' => false,
            'float' => false,
            'esc' => true, // Przed dodaniem wartości do tablicy pól użycie esc()
            'strip_tags' => false, // Usunięcie tagów
            'allowed_tags' => null, // Dozwolone tagi w strip_tags
            'lineBreak' => false, // Monituj o bledzie jesli string jest dluzszy niz okreslona ilosc znakow
            'valid' => true, // Konieczność validacji
            'duplicate' => true, // W danej tabeli może wystąpić więcej niż jeden rekord o takiej wartości pola,
            'duplicate_table' => false, // Tabela do sprawdzenia występowania rekordu,
            'duplicate_error' => '<strong>{name}</strong> already in use', // Tresc bledu duplicate
            'functions' => array(), // (array) Użycie dodatkowych funkcji (Zawsze przed esc() i strip_tags())
            /**
             * array(
             *  'function' => 'NAZWA_FUNKCJI',
             *  'class' => 'NAZWA_KLASY',
             *  'method' => 'NAZWA METODY',
             *  'error' => 'OPIS_BLEDU_DODAWANY_DO_TABLICY_BLEDOW'
             * )
             */
            'empty' => false, // true - Pole może być puste (=null) , false - nie moze byc puste
            'empty_text' => 'Filed <b>{name}</b> is required', // Opis bledu empty
            'null_not_put' => false, // Jeśli pole ma wartość null nie jest dodawane do tablic BATCH
            'min_len' => false, // Minimalna ilość znaków
            'min_len_error' => 'Minimal length of field <b> {name} </b> it <strong> {min_len} </strong> of signs', // Tresc bledu min_len
            'min_len_array_error' => 'You must mark at least {max_len} options for field <b> {name} </b>',
            'min_len_file_error' => 'Market smaller size of the file in field <strong> {name} </strong>',
            'max_len' => false, // Maksymalna ilosc znakow
            'max_len_error' => 'Maximum length of field <b> {name} </b> it <strong> {max_len} </strong> of signs', // Tresc bledu max_len,
            'max_len_array_error' => 'You can mark to a maximum <b> {max_len} </b> of option in field <b> {name} </b>', // Tresc bledu max_len
            'max_len_file_error' => 'Market largeness of the file in field <strong> {name} </strong>',
            'valid_type' => false, // file, array, phone, mobile, email, gg, bank_account, login , clear_name , full_name,  nip, regon, postcode, price
            'valid_error' => false, 
            'special' => false
        );
        
        public function __construct(){
            
            $this -> html = $this->left_box = '';
            $this->memory_field_valid = $this -> field_valid;
            $this -> fields = array();
            $this->handler = 'global'; // Nie uzywany - Patrz plik module/global.php
            
            self::$instance = $this; 
            self::$i = $this; 
            
        }
        
        public function htmlClear(){
            $this -> html = '';
        }
        public function bodyClear(){
            $this -> body = '';
        }
        public function headClear(){
            $this -> head = '';
        }        
        /**
         * 
         */
        public function valid(){
            $this->valid_now = true;
        }
        
        /**
         * 
         */
        public function validOff(){
            $this->valid_now = false;
        }
        
        /**
         * 
         * @param string $value
         * @param bool
         * @return void
         */
        public function val( $html , $update = true ){
            
            if( $update ) $this -> html .= $html;
            else $this -> html = $html;
               
        }
        
        /**
         * Tworzenie dynamicznego pola walidacji
         * @param string $fname
         * @param array $valid
         * 'name' => false, // Domyślna nazwa, NIE WARTOŚĆ PARAMETRU name=""!
         * 'fname' => false, // Wartość pola name
         *  'bname' => false, // Nazwa w tablicy db::$intance->batch
         * 'value' => false,
            * 'esc' => true, // Przed dodaniem wartości do tablicy pól użycie esc()
            * 'strip_tags' => false, // Usunięcie tagów
            * 'allowed_tags' => null, // Dozwolone tagi w strip_tags
            * 'lineBreak' => false, // Monituj o bledzie jesli string jest dluzszy niz okreslona ilosc znakow
            * 'valid' => true, // Konieczność validacji
            * 'duplicate' => true, // W danej tabeli może wystąpić więcej niż jeden rekord o takiej wartości pola
            * 'duplicate_table' => false, // Tabela do sprawdzenia występowania rekordu
            * 'duplicate_error' => '<strong>{name}</strong> jest już w użyciu, wprowadź inną wartość <strong>{name}</strong>', // Tresc bledu duplicate
            * 'functions' => array(), // (array)  (function,class,method,error) Użycie dodatkowych funkcji (Zawsze przed esc() i strip_tags())
            * 'empty' => false, // true - Pole może być puste (=null) , false - nie moze byc puste
            * 'empty_text' => 'Pole <b>{name}</b> jest wymagane', // Opis bledu empty
            * 'null_not_put' => false, // Jeśli pole ma wartośc NULL nie jest dodawane do tablicy BATCH
            * 'min_len' => false, // Minimalna ilość znaków
            * 'max_len' => false, // Maksymalna ilosc znakow
            * 'valid_type' => false // phone, mobile, email, gg, bank_account, login , clear_name , full_name,  nip, regon, postcode, price
            * 'valid_error' => false // Inna niz w valid tresc bledu
         * @return
         */
        public function field( $fname , $valid ){
            
            $this->field_valid['fname'] = $fname;
            
            if( is_array($valid) ){
                
                foreach( $valid AS $v_name => $v_value ) $this -> field_valid[$v_name] = $v_value;
                
                
                
            } else $this->field_valid['valid'] = true;
            
            // Wartosc pola
            if(!in_array($this->field_valid['valid_type'],array('image','file'))){
                if( !$this->field_valid['value'] ) $this->field_valid['value'] = $_REQUEST[$fname];
            } else {
                 $this->field_valid['is_resource'] = true;
                 
                 $this->field_valid['value'] = $_FILES[$fname];
            }
            
            
            // Jesli polu nie przypisano nazwy , przypisz nazwę pola
            if( !$this->field_valid['name'] ) $this->field_valid['name'] = $fname;
            
            // Jeśli nie zdefiniowano nazwy batch przypisz nazwe pola
            if( !$this->field_valid['bname'] ) $this->field_valid['bname'] = $fname;
            
            /**
             * WALIDACJA
             */
            if( $this->valid_now ){
                if($this->isEmpty()){
                
                    // Walidacja
                    if( $this->field_valid['valid'] ){
                        
                        if( $this->field_valid['valid_type'] ){
                            
                            $validation_method = $this->field_valid['valid_type'];
                            
                            switch( $validation_method ){
                                
                                case 'array':
                                
                                   $this->field_valid['value'] = join($this->field_valid['special']['join'],$this->field_valid['value']);
                                    
                                break;
                                
                                /**
                                 * SPECIAL:
                                 * ext - Dozwolone rozszerzenia, [all] - Oznacza wszystkie
                                 * error_ext - Zabronione rozszerzenia
                                 * name - Nazwa pliku wyjściowego, [md5] - Oznacza automatyczne generowanie nazwy md5
                                 * target_dir - Katalog docelowy
                                 * ext_field - Dodaj do bazy rozszerzenie pliku
                                 * size_field - Dodaj do bazy rozmiar pliku
                                 * size_type - Rozmiar pliku KB lub MB
                                 */
                                case 'file':
                            
                                     if(is_uploaded_file( $this->field_valid['value']['tmp_name'] )){
                                        
                                        // Informacje o pliku
                            			$info = file::info( $this->field_valid['value']['name'] );
                            			$target = $this->field_valid['special']['target_dir'];
                            			
                                        // Określenie nazwy pliku
                                        if( $this->field_valid['special']['name']=='[md5]' or empty($this->field_valid['special']['name'])) $target .= $info['md5'] . '.' . mb_strtolower($info['extension'],'utf-8');
                                        else $target .= $this->field_valid['special']['name'] . '.' . mb_strtolower($info['extension'],'utf-8');
                                        
                                            
                                        
                                            // Dozwolone  rozszerzenia
                                            if( ( is_array( $this->field_valid['special']['ext'] ) and in_array(mb_strtolower($info['extension'],'UTF-8'),$this->field_valid['special']['ext'])) OR $this->field_valid['special']['ext']=='[all]'){
                                				
                                                if(is_array($this->field_valid['special']['error_ext']) and !in_array(mb_strtolower($info['extension'],'UTF-8'),$this->field_valid['special']['error_ext'])){
                                                        // Przenoszenie pliku
                                                        if( move_uploaded_file( $this->field_valid['value']['tmp_name'] , $target ) ){
                                        
                                                            query::$i->put( esc($target) , $this->field_valid['bname'] , $this->field_valid['group'] );
                                        
                                                            $this->field_valid['special']['uploaded'] = $target;
                                        
                                                            // Dodaj rozszerzenie
                                                            if( !empty($this->field_valid['special']['ext_field']) ){
                                                                query::$i->put( esc(mb_strtolower($info['extension'],'utf-8')) , $this->field_valid['special']['ext_field'] , $this->field_valid['group'] );
                                                            }
                                        
                                                            // Dodaj rozmiar
                                                            if( !empty($this->field_valid['special']['size_field']) ){
                                                                
                                                                switch($this->field_valid['special']['size_type']){
                                                                    case 'MB':
                                                                        $filesize = round(($_FILES[$fname]['size']/1024/1024),2);
                                                                    break;
                                                                    
                                                                    case 'KB':
                                                                    default:
                                                                        $filesize = intval(($_FILES[$fname]['size']/1024));
                                                                    break;
                                                                }
                                                                
                                                                query::$i->put( esc( $filesize ) , $this->field_valid['special']['size_field'] , $this->field_valid['group'] );
                                                            }
                                                                  
                                                                              			
                                        				} else error::$i->put( $this->parseErrorText('Error when moving a file, the field <b>{name}</b>'),$this->field_valid['fname']);
                                                    } else error::$i->put( $this->parseErrorText('Illegal file extension in the <b>{name}</b>' ),$this->field_valid['fname']);
                                                } else error::$i->put( $this->parseErrorText('Illegal file extension in the <b>{name}</b>' ),$this->field_valid['fname']);
                                            
                                    } else error::$i->put( $this->parseErrorText('Error handling / uploading a file, check the <b>{name}</b>') ,$this->field_valid['fname']);
                                       
                                break;

                                /**
                                 * SPECIAL:
                                 * ext - Dozwolone rozszerzenia, [all] - Oznacza wszystkie
                                 * name - Nazwa pliku wyjściowego, [md5] - Oznacza automatyczne generowanie nazwy md5
                                 * target_dir - Katalog docelowy,
                                 * scale - array('x'=>value,'y'=>value)
                                 * thumb - array('x'=>value,'y'=>value),
                                 * thumb_prefix
                                 * thumb_field
                                 */
                                case 'image':
                            
                                     if(is_uploaded_file( $this->field_valid['value']['tmp_name'] )){
                                        
                                        // Informacje o pliku
                            			$info = file::info( $this->field_valid['value']['name'] );
                            			$target = $this->field_valid['special']['target_dir'];
                            			$info['extension'] = $this->field_valid['special']['file_extension'] = mb_strtolower($info['extension'],'utf-8');
                                        if($info['extension']=='jpeg') $info['extension'] = 'jpg';
                                        
                                        
                                        // Określenie nazwy pliku
                                        $filename = (($this->field_valid['special']['name']=='[md5]' or empty($this->field_valid['special']['name'])) ? $info['md5'] : $this->field_valid['special']['name']);
                                        $target .= $filename . '.' . mb_strtolower($info['extension'],'utf-8');
                                        
                                            
                                        
                                            // Dozwolone rozszerzenia
                                            if( ( is_array( $this->field_valid['special']['ext'] ) and in_array(mb_strtolower($info['extension'],'UTF-8'),$this->field_valid['special']['ext'])) OR $this->field_valid['special']['ext']=='[all]'){
                                				
                                                // Przenoszenie pliku
                                                if( move_uploaded_file( $this->field_valid['value']['tmp_name'] , $target ) ){
                                
                                                    $resizer = new resizer( $target );
                                                    
                                                    // Przeskalowanie oryginalu
                                                    if( $this->field_valid['special']['scale'] ){
                                                        
                                                        if(!$this->field_valid['special']['scale_dimension']) $scale_dimension = 2;
                                                        else $scale_dimension = $this->field_valid['special']['scale_dimension'];
                                                        
                                                        $resizer->max_width( $this->field_valid['special']['scale']['x'] );
                                                        $resizer->max_height( $this->field_valid['special']['scale']['y'] );
                                                        $resizer->destination( $this->field_valid['special']['target_dir'] ,$filename);
                                                        $resizer->image_resize( $scale_dimension );
                                                        
                                                    }

                                                    // Przeskalowanie oryginalu
                                                    if( $this->field_valid['special']['thumb'] ){
                                                        
                                                        if(!$this->field_valid['special']['dimension']) $dimension = 2;
                                                        else $dimension = $this->field_valid['special']['dimension'];
                                                        
                                                        $thumbName = $filename . (empty($this->field_valid['special']['prefix']) ? '_thumb' : $this->field_valid['special']['prefix']);
                                                        
                                                        $resizer->max_width( $this->field_valid['special']['thumb']['x'] );
                                                        $resizer->max_height( $this->field_valid['special']['thumb']['y'] );
                                                        $resizer->destination( $this->field_valid['special']['target_dir'] , $thumbName );
                                                        $resizer->image_resize( $dimension );
                                                        
                                                        // Dodaj miniature do bazy danych
                                                        if($this->field_valid['special']['thumb_field']){
                                                            query::$i->put( esc($this->field_valid['special']['target_dir'] . $thumbName . '.' . mb_strtolower($info['extension'],'UTF-8')) , $this->field_valid['special']['thumb_field'] );
                                                        }
                                                        
                                                    }                                                    
                                                    
                                                    query::$i->put( esc($target) , $this->field_valid['bname'] , $this->field_valid['group'] );
                                                    $this->field_valid['special']['uploaded'] = $target;
                                                    $this->field_valid['special']['uploaded_thumb'] = $this->field_valid['special']['target_dir'] . $thumbName . '.' . mb_strtolower($info['extension'],'UTF-8');
                                                          
                                                                      			
                                				} else error::$i->put($this->parseErrorText('Error handling / uploading a file, check <b>{name}</b>'),$this->field_valid['fname']);
                                            
                                            } else error::$i->put($this->parseErrorText('Illegal file extension in the <b>{name}</b>'),$this->field_valid['fname']);
                                        
                                    } else error::$i->put($this->parseErrorText('Error handling / uploading a file, check <b>{name}</b>'),$this->field_valid['fname']);
                                       
                                break;
                                                                
                                default:
                                    if( !valid::$validation_method( $this->field_valid['value'] ) ){
                                        
                                         error::$instance->put( $this->parseErrorText( ($this->field_valid['valid_error'] ? $this->field_valid['valid_error'] : valid::$list_error[$this->field_valid['valid_type']]) ) );
                                    }
                                break;
                            }

                            
                        }
                        
                        // Dalsza walidacja
                            # Dodatkowe funkcje walidacji
                            if(count($this->field_valid['functions'])>0){
                                foreach( $this->field_valid['functions'] AS $valid_method ){
                                    
                                    if( $valid_method['function'] AND function_exists( $valid_method['function']) ){
                                        
                                        // Walidacja z użyciem function()
                                        if( !$valid_method['function']( $this->field_valid['value'] ) ){
                                            error::$instance->put( $this->parseErrorText($valid_method['error']) );
                                        }
                                        
                                    } elseif( $valid_method['class'] AND $valid_method['method'] ){

                                         // Walidacja z użyciem class::method()
            					      // if((version_compare(phpversion(),"5.3.0")>=0)){
            					       /*
                                            if( !$valid_method['class']::$valid_method['method']( $this->field_valid['value']  ) ){
                                                error::$instance->put( $this->parseErrorText($valid_method['error']) );
                                            }
                                        */
            					       //} else {
                                            if( !eval(''.$valid_method['class'].'::'.$valid_method['method'].'( '.$this->field_valid['value'] .' )') ){
                                                error::$instance->put( $this->parseErrorText($valid_method['error']) );
                                            }
            					       //}  
                                       

                                        
                                    } else {
                                        
                                        #ERR:001
                                        error::system('Błąd','class','001');
                                        
                                    }
                                    
                                }
                            }
                            
                            # Usuwanie tagów
                            if($this->field_valid['strip_tags']){
                                $this->field_valid['value'] = strip_tags( $this->field_valid['value'] , ($this->field_valid['allowed_tags'] ? $this->field_valid['allowed_tags'] : null) ); 
                            }
                            
                            # lineBreak - Sprawdzanie dlugosci stringow
                            if($this->field_valid['lineBreak']){
                                if(!valid::lineBreak($this->field_valid['lineBreak'])){
                                    error::$instance->put( $this->parseErrorText( valid::$list_error[$this->field_valid['lineBreak']] ) );
                                }
                            }
                            
                            # Intval
                            if($this->field_valid['int'] and !$this->field_valid['is_resource']){
                                $this->field_valid['value'] = intval( $this->field_valid['value'] );
                            }                            

                            # Intval
                            if($this->field_valid['float'] and !$this->field_valid['is_resource']){
                                $this->field_valid['value'] = floatval( $this->field_valid['value'] );
                            } 
                                                                                    
                            # Escape - magic quotes itd.
                            if($this->field_valid['esc'] and !$this->field_valid['is_resource']){
                                $this->field_valid['value'] = esc( $this->field_valid['value'] );
                            }
                            
                            // Występowanie pola | DUPLICATE
                            if(!$this->field_valid['duplicate']){
                                if(db::$i->chk($this->field_valid['value'],$this->field_valid['duplicate_table'],$this->field_valid['fname'])) error::$instance->put( $this->parseErrorText( $this->field_valid['duplicate_error'] ) );
                            }
                            
                        // Minimalna wielkosc
                        if($this->field_valid['min_len']){
                            switch( $this->field_valid['valid_type'] ){
                                
                                case 'array':
                                    if(count((stristr($this->field_valid['value'],',')?explode(',',$this->field_valid['value']):1)) < $this->field_valid['min_len']){
                                        error::$instance->put( $this->parseErrorText( $this->field_valid['min_len_array_error'] ) );
                                    }
                                break;
                                
                                case 'image':
                                case 'file':
                                    if(($this->field_valid['value']['size']/1024) < $this->field_valid['min_len']){
                                        error::$instance->put( $this->parseErrorText( $this->field_valid['min_len_file_error'] ) );
                                    }
                                break;
                                                                
                                default:
                                    if(strlen($this->field_valid['value']) < $this->field_valid['min_len']){
                                        error::$instance->put( $this->parseErrorText( $this->field_valid['min_len_error'] ) );
                                    }
                                break;
                                
                            }

                        }

                        // Maksymalna wielkosc
                        
                        if($this->field_valid['max_len']){
                            
                            switch( $this->field_valid['valid_type'] ){
                                
                                case 'array':
                                    if(count((stristr($this->field_valid['value'],',')?explode(',',$this->field_valid['value']):1)) > $this->field_valid['max_len']){
                                        error::$instance->put( $this->parseErrorText( $this->field_valid['max_len_array_error'] ) );
                                    }
                                break;
                                
                                case 'image':
                                case 'file':
                                    if(($this->field_valid['value']['size']/1024) > $this->field_valid['max_len']){
                                        error::$instance->put( $this->parseErrorText( $this->field_valid['max_len_file_error'] ) );
                                    }
                                break;
                                
                                default:
                                    if(strlen($this->field_valid['value']) > $this->field_valid['max_len']){
                                        error::$instance->put( $this->parseErrorText( $this->field_valid['max_len_error'] ) );
                                    }
                                break;
                                
                            }

                        }
                        

                    }
                    
                }
                
                // Dodaj parametr BATCH
                if(!$this->field_valid['is_resource']){
                        if($this->field_valid['value'] !== null OR !$this->field_valid['null_not_put'])
                            query::$i->put( $this->field_valid['value'] , $this->field_valid['bname'] , $this->field_valid['group'] );
                }
            }
            
            // Przechowanie pola
            $this->fields[$this->field_valid['fname']] = $this->field_valid;
            
            // Przywrocenie parametrow
            $this->field_valid = $this->memory_field_valid;
        }
        
        /**
         * 
         */
        public function isEmpty(){
            if( !$this->field_valid['empty'] ){
                switch( $this->field_valid['valid_type']){
                    
                    // Pliki
                    case 'image':
                    case 'file':
                        if(empty($this->field_valid['value']['name'])){
                            
                            // Tablica bledow
                            error::$instance->put( $this->parseErrorText($this->field_valid['empty_text']) );
                            return false;
                            
                        } else return true;
                    break;
                    
                    // Zwykłe pola i tablice (W postaci joined)
                    default:
                        if(empty($this->field_valid['value'])){
                            
                            // Tablica bledow
                            error::$instance->put( $this->parseErrorText($this->field_valid['empty_text']) );
                            return false;
                            
                        } else return true;
                    break;
                }

            } else {
                
                if(empty($this->field_valid['value'])){
                    $this->field_valid['value'] = null;
                    return false;
                } else return true;
                
            }
        }
        
        public function parseErrorText( $text ){
            
            return str_replace( array('{name}','{min_len}','{max_len}') , array($this->field_valid['name'],$this->field_valid['min_len'],$this->field_valid['max_len']) , $text );
            
        }
        
        public function setHead( $value ){
            $this->head = $value;
        }
        
        /**
         * Set HTML title
         */
        public function setTitle( $value , $rewrite = false ){
            
            if( $rewrite ){
                
                $this->title = $value;
                
            } else {
                
                $this->title .= ' ' . $value;
                
            }
            
        }

        public function setBody( $value ){
            $this->body = $value;
        }
        
        /**
         * 
         */
        public function StdValid( $table , $tMode = 'update' , $by='id' ){
            
            switch( $tMode ){
                
                case 'update':
                    if( core::POST() ){
                        
                        if( error::$i->valid() ){
                            
                            if(count(query::$i->getBatch())>0){
                                if( db::$i->update( $table ,query::$i->getBatch(),core::$i->id,$by) ) page::$i->val( html::$i->ok( I_UPDATED ) );
                                else page::$i->val( html::$i->error( CE_MYSQL ) ); 
                            } else page::setOk( I_ESAVED );
                            
                        } else {
                            
                            if( is_array($this->fields) ){
                                foreach( $this->fields as $field ){
                                    if($field['valid_type']=='file'){
                                        @unlink( $field['special']['uploaded'] );
                                    } 
                                }
                            }
                            
                            error::$i->toContent( false );
                            
                        }
                        
                    }  
                break;
                
                case 'new':
                    if( core::POST() ){
                        if( error::$i->valid() ){
                            
                            if( db::$i->insert( $table ,query::$i->getBatch()) ) page::$i->val( html::$i->ok( I_SAVED ) );
                            else page::$i->val( html::$i->error( CE_MYSQL ) );
                            
                        } else {
                            if( is_array($this->fields) ){
                                foreach( $this->fields as $field ){
                                    if($field['valid_type']=='file'){
                                        @unlink( $field['special']['uploaded'] );
                                    } 
                                }
                            }
                            error::$i->toContent( false );
                        }
                    }
                break;
                
            }
            

        }
        
        /**
         * Alias dla page::$i->val( html::$i->error( $value , $add_params = false ,  $tpl_prefix = 'page' ) );
         */
        public static function setError( $value , $add_params = false ,  $tpl_prefix = 'page' ){
            page::$i->val( html::$i->error( $value , $add_params = false ,  $tpl_prefix = 'page' ) );
        }

        /**
         * Alias dla page::$i->val( html::$i->ok( $value , $add_params = false ,  $tpl_prefix = 'page' ) );
         */
        public static function setOk( $value , $add_params = false ,  $tpl_prefix = 'page' ){
            page::$i->val( html::$i->ok( $value , $add_params = false ,  $tpl_prefix = 'page' ) );
        }       
                
    }



?>