Hirse / brackets-outline-list

Extension for Brackets and Phoenix to display a list of the functions or definitions in the currently opened document.
MIT License
79 stars 30 forks source link

Problem in latest update (63cd4d6): Lag when swapping files #70

Closed thundree closed 7 years ago

thundree commented 7 years ago

Hello, Hirse! Would like to say that this extension is amazing. Been using it a lot this year.

That said, this latest commit (63cd4d6) changed something and I got a lot of lag when changing document files(PHP) in Brackets (Release 1.8 build 1.8.0-17108 3af64fae4).

I'm working on an API and some PHP CLASS files have somewhat 50\~70 functions, and listing them all, right now, takes some 20\~30 seconds. Before this last update, it was almost instantly when swapping files.

Observation: noticed that saving these files freezes Brackets for a while.

About labeling the issue: Can't figure out how to put a label on this, sorry :(

Hirse commented 7 years ago

Thanks, I am happy you like it.

In the last release the PHP parser changed. It is now using a custom lexer to support more cases and style variations. I have to admit, I didn't do any performance testing on it though.

Could you possibly share the file you are working on (if it is open source) or alternatively create a file with similar structure? That would help significantly in improving it.

Only contributors can put labels, so don't worry about it. 😉

thundree commented 7 years ago

Hey, thanks! Gonna do my best to help you guys. Hold on for a while as I create a similar file in size.

thundree commented 7 years ago

There you go... This is the best I can do here in this editor. Changed the code so it was kept inside the "code" block. If you need, tell me and I try to send you the file in .php

<?php class API{
    protected $error=array(
        'code'=>0,'msg'=>''
    );

    protected $debug=1;//
    protected $debugSQL=2;//
    protected $compression=1;//

    public function __construct(){
        if( !($this->requestTime=getenv('REQUEST_TIME_FLOAT')) ){
            $this->requestTime=microtime(true);
        }

        $this->userIp=
            getenv('HTTP_CLIENT_IP')?:
            getenv('HTTP_X_FORWARDED_FOR')?:
            getenv('HTTP_X_FORWARDED')?:
            getenv('HTTP_FORWARDED_FOR')?:
            getenv('HTTP_FORWARDED')?:
            getenv('REMOTE_ADDR');

        $this->method=$method=strtoupper(getenv('REQUEST_METHOD'));
        //$this->_response( 200,1 );

        if( "{$method}"==='POST' && isset($_SERVER['HTTP_X_HTTP_METHOD']) ){
            if( isset($_SERVER['HTTP_X_HTTP_METHOD']) ){
                $this->method=$method=strtoupper($_SERVER['HTTP_X_HTTP_METHOD']);
                if( "{$method}"!='DELETE' && "{$method}"!='PUT' ){
                    $this->_response( 200,1 );
                }

            }else{
                $this->_response( 200,1 );
            }

        }else if( in_array("{$method}",array('HEAD')) ){
            $this->_response( 200,1 );
            die;//Impede a criacao do log!

        }else if( in_array("{$method}",array('OPTIONS')) ){
            if( getenv('HTTP_ACCEPT')==="*/*" ){
                $this->_response( 200,1 );
                die;//Impede a criacao do log!
            }
        }

        if( isset($_GET['request']) ){
            $this->request=trim(strtolower($_GET['request'])," / *-+.,?{}'\"-=_+!@#$%¨&()<>:;\\");
            //unset($_GET['request']);
        }

        //var_dump($this->request);die;

        if( getenv('HTTP_AUTHENTICATION') ){
            $this->vars['Authentication']=$this->authentication=getenv('HTTP_AUTHENTICATION');
        }

        if( isset($_SERVER['HTTP_ACCEPT_ENCODING']) ){
            $this->encodingMethods=explode(',',strtolower(str_replace(' ','',$_SERVER['HTTP_ACCEPT_ENCODING'])));
        }

        if( isset($_SERVER["CONTENT_TYPE"]) ){
            $this->contentType=$_SERVER['CONTENT_TYPE'];
        }

        if( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ){
            $this->userLaguages=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
        }

        $this->funcs=new apiFunctions();

        switch( "{$this->method}" ){
            case "HEAD":
            case "OPTIONS":
                break;

            case "DELETE":
            case "POST":
                $contents="";
                $simples=false;
                try{
                    if( is_array($contents=file_get_contents('php://input')?:'') ){
                        $simples=true;
                    }
                }catch(Exception $e){
                    $simples=false;
                }
                //var_dump($contents);die;

                if( empty($_POST) && (isset($_SERVER['QUERY_STRING']) || $contents) ){

                    $fields=false;
                    if( !$simples ){
                        try{
                            if( !($fields=json_decode($contents,true)) ){
                                $str="{$_SERVER['QUERY_STRING']}&{$contents}";
                                $fields=explode('&',trim($str,' &'));
                            }else{
                                $simples=true;
                            }
                        }catch(Exception $e){

                        }
                    }

                    //$this->_response( 200,1 );
                    if( $simples && is_array($fields) ){
                        $_POST=array_merge($_POST,$fields);
                    }else{
                        $_POST=array();
                        if( $fields ){
                            foreach( $fields as $index=>$object ){
                                if( $simples ){
                                    if( is_array($object) ){
                                        foreach( $object as $index2=>$item2 ){
                                            if( !is_array($item2) ){
                                                if( !(int)$index2 ){
                                                    $_POST[$index][]=$item2;
                                                }else{
                                                    $_POST[$index2][]=$item2;
                                                }
                                            }else{
                                                $_POST[$index][$index2]=$item2;
                                            }
                                        }
                                    }else{
                                        $_POST[$index]=$object;
                                    }
                                }else{
                                    $object=str_replace(
                                        array('&{"','","','"}','='),
                                        array('&','&','',':'),
                                        $object
                                    );
                                    if( count($tmp=explode('=',$object))>1 || count($tmp=explode(':',$object))>1 ){
                                        $_POST[$tmp[0]]=$tmp[1];
                                    }
                                }
                            }
                        }
                    }
                }
                //var_dump($_POST);die;

                $this->vars=array_merge($this->vars,$_POST);
                break;

            case "GET":
                //var_dump($_GET);die;
                $this->vars=array_merge($this->vars,$_GET);
                break;

            case "PATCH":
            case "PUT":
                $this->vars=array_merge($this->vars,$_POST);
                $vars=array();
                parse_str( file_get_contents("php://input"),$vars );
                $this->vars=array_merge($this->vars,$vars);
                break;

            default:
                $this->_response( 200,1 );
                break;
        }
        //$this->_response( 200,1 );
        $this->vars=$this->_cleanInputs($this->vars);

        if( isset($this->vars['debug']) ){
            $this->debug=$this->vars['debug'];
        }
        if( isset($this->vars['id']) ){
            $this->vars['id']=intval($this->vars['id'],10);
        }
        if( isset($this->vars['id_loja']) ){
            $this->idLoja=intval($this->vars['id_loja'],10);
        }
        if( isset($this->vars['escape']) && "{$this->vars['escape']}"=='0' ){
            $this->escapingMethod=0;
        }
        if( empty($this->vars['idiom']) ){
            $this->idiom=$this->funcs->getLanguage($this->userLaguages);
        }else{
            $this->idiom=$this->funcs->getLanguage($this->vars['idiom']);
        }

        //$this->_response( 200,1 );

        if( isset($this->vars['compression']) ){
            $this->compression=(int)$this->vars['compression'];
        }

        unset(
            $this->vars['debug'],$this->vars['request'],$this->vars['compression'],$this->vars['escape'],$this->vars['idiom'],
            $this->vars['method'],$this->vars['path'],$this->vars['sign'],$this->vars['id_loja'],$this->vars['ignoreLoading']
        );

        if( isset($this->vars['cache_time']) ){
            $this->vars['cache_time']=(int)$this->vars['cache_time'];
        }

        /*DEBUG*/

        $origin=NULL;
        if( !empty($_SERVER['HTTP_ORIGIN']) ){
            $origin=$_SERVER['HTTP_ORIGIN'];
        }

        $this->_response( 200,1 );
    }
    /*********************************************************************/
    public function processAPI(){
        //var_dump($this->request);die;

        //$this->_response( 200,1 );
        if( strstr($this->request,"/") ){
            $resquest=explode("/","{$this->request}");
            $total=count($resquest)-1;

            //$this->_response( 200,1 );

            for( $i=$total; $i>=0; $i-- ){
                $resquest[$i]=trim($resquest[$i],"  _");
                if( (int)$resquest[$i] && $resquest[$i]==(int)$resquest[$i] ){
                    if( !$this->idControl ){
                        $this->vars['id']=$this->idControl=(int)$resquest[$i];
                    }
                    unset($resquest[$i]);
                }else{
                    if( $i ){
                        $resquest[$i]=ucfirst($resquest[$i]);
                    }
                }
            }

            $this->request=implode("",$resquest);
            //$this->_response( 200,1 );
        }

        if( (int)method_exists($this, $this->request) ){
            call_user_func_array(array($this,$this->request),array());
        }

        return $this->_response( 200,1 );
    }
    /*********************************************************************/
    private function _response( $statusCode=200,$idStatus=2,$data="*/*" ){
        list($statusType,$statusMsg)=$this->_requestStatus($statusCode);

        while( ob_get_level() ){ ob_end_clean(); }

        header("HTTP/1.1 {$statusCode} {$statusMsg}");

        header("Content-type: application/json; charset=utf-8");

        if( in_array("{$this->method}",array('HEAD','OPTIONS')) ){
            header("Content-Length: 0");die;
        }

        $data=($data!="*/*")?$data:$statusMsg;

        /*ESCAPING METHOD*/
        $escapeMethod=NULL;
        switch( (int)$this->escapingMethod ){
            case 1:
                $escapeMethod=NULL;
                break;
            case 0:
            default:
                $escapeMethod=JSON_UNESCAPED_UNICODE;
                break;
        }
        /*ESCAPING METHOD*/

        $responseArr=array();

        $sessionToken=0;
        if( in_array($statusCode,array(200,201)) ){
            if( in_array("{$this->method}",array('POST','DELETE')) ){
                $this->createNewCacheTokenUser();
                if( !($sessionToken=$this->createSessionToken()) ){
                    $sessionToken=0;
                }
                if( in_array($this->request,array("contato","pagamento","pedido","cadastro")) ){
                    $this->createNewCacheTokenLoja();
                }
            }
        }else{
            $this->error=array(
                'code'=>$idStatus?:$statusCode,
                'msg'=>$data
            );
            $data=array();
        }

        $responseArr=array(
                "fingerprint"=>"{$this->signature}",
                "restrict"=>$this->restrict,
                "status"=>"{$statusType}",
                "response"=>$idStatus,
                "idiom"=>$this->idiom,
                "cache"=>"{$this->cacheCodeUser}{$this->cacheCodeLoja}",
                "error"=>$this->error,
                "escape"=>$this->escapingMethod,
                "currency"=>$this->currency,
                "data"=>$data
        );

        if( $this->debug=='2' ){
            $responseArr=array(
                    "fingerprint"=>"{$this->signature}",
                    "status"=>"{$statusType}",
                    "response"=>$idStatus,
                    "delay"=>(microtime(true)-$this->requestTime),
                    "memory"=>$this->funcs->calcSize(memory_get_peak_usage()),
                    "compression"=>$this->compression,
                    "restrict"=>$this->restrict,
                    "idiom"=>$this->idiom,
                    "escape"=>$this->escapingMethod,
                    "cache"=>"{$this->cacheCodeUser}{$this->cacheCodeLoja}",
                    "error"=>$this->error,
                    "currency"=>$this->currency,
                    "data"=>$data
                    //,"phpinfo"=>'"'.phpinfo().'"'
            );
        }

        if( $sessionToken ){
            $responseArr["sessionToken"]=$sessionToken;
        }

        $apiResponse=json_encode(
            $responseArr,$escapeMethod
        );

        /*ENCODING METHOD*/
        $encodingMethod=NULL;
        if( $this->compression && in_array('gzip',$this->encodingMethods) ){
            $encodingMethod="ob_gzhandler";
        }
        /*ENCODING METHOD*/

        /*JSON RESPONSE*/
        ob_start();
        ob_start($encodingMethod);
        echo $apiResponse;
        //header("Content-Length: ".strlen($apiResponse));
        header("Connection: close");
        //header("Content-Length: ".ob_get_length());

        if( !headers_sent() ){
            ob_end_flush(); // Flush the output from ob_gzhandler
            header("Content-Length: ".ob_get_length());
            ob_end_flush(); // Flush the outer ob_start()
        }
        /*JSON RESPONSE*/

        /*GERAR LOG*/
        if( $this->gerar_log ){
            $resp=trim(str_replace( array('\\"',"'",'\\"'),array('"','"','"'),json_encode( $responseArr ) ),'\'"');
            $this->id_log=$this->tmp_mysqli->getAsyncRes();
            $campos=array(
                "id"=>$this->id_log,
                "status"=>"{$statusCode}",
                "msg"=>"{$statusMsg}",
                "fingerprint"=>$this->signature,
                "response"=>"{$resp}"
            );
            if( !empty($this->userFull['id']) ){
                $campos["nome"]="{$this->userFull['nome']}";
                $campos["id_user"]="{$this->userFull['id']}";
            }
            $dados=array(
                "tabela"=>"api_log_site",
                "campos"=>$campos,
                "debug"=>$this->debugSQL,
                "update"=>true
            );
            $this->tmp_mysqli->sqlInsert($dados);
        }
        /*GERAR LOG*/

        die; //Fim do retorno!
    }
    /*********************************************************************/
    private function createSessionToken(){
        $tempo_criacao=time();
        $data_criacao=date( "Y-m-d H:i:s",$tempo_criacao );

        if( $resp && $newSessionToken ){
            return $this->sessionToken=$newSessionToken;
        }else{
            return false;
        }
    }
    /*********************************************************************/
    private function createNewCacheTokenLoja(){
        if( empty($this->idLoja) ){
            return false;
        }

        return true;
    }
    /*********************************************************************/
    private function createNewCacheTokenUser(){

        $this->cacheCodeUser=$this->createNewName(1);

        $campos=array(
            'fingerprint'=>$this->signature,
            'cache'=>$this->cacheCodeUser
        );
        $params=array(
            'tabela'=>"users_cache",
            'debug'=>$this->debugSQL,
            //'wherez'=>"",
            'campos'=>$campos,
            "update"=>true
        );
        $resposta=$this->mysqli->sqlInsert( $params );

        return true;
    }
    /*********************************************************************/
    private function iuguRetorno(){
        if( $this->_allowedMethods( array('GET','POST','PUT') ) ){
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function createNewName($lengthType=6){
        srand(microtime(true));
        $seed=rand(10,99).$this->requestTime.microtime(true).'1';
        switch( (int)$lengthType ){
            case 1;
                //8
                return hash('crc32b',$seed);
                break;

            case 2;
                //16=8+8
                return hash('crc32b',$seed).hash('adler32',$seed);
                break;

            case 3;
                //24=8+8+8
                return hash('crc32b',$seed).hash('adler32',substr($seed,0,5)).hash('crc32',$seed);
                break;

            default:
            case 0;
            case 4;
                //32
                return hash('ripemd128',$seed);
                break;

            case 5;
                //40
                return hash('ripemd160',$seed);
                break;

                //64
            case 6;
                return hash('sha256',$seed);
                break;

                //96
            case 7;
                return hash('sha384',$seed);
                break;

                //128
            case 8;
                return hash('sha512',$seed);
                break;

                //224=128+64
            case 9;
                return hash('sha512',$seed).hash('sha256',$seed);
                break;

                //256=128+64+32+32
            case 10;
                return hash('sha512',$seed).hash('sha256',$seed).hash('ripemd128',$seed).hash('md5',$seed);
                break;
        }
        //return date("Ymdhis",time()).'-'.microtime(true);
    }
    /*********************************************************************/
    private function vars($index="abc",$padrao=NULL){
        $return=$padrao;

        if( gettype($index)=="string" ){
            if( isset($this->vars[$index]) ){
                return $this->vars[$index];
            }
        }

        return $return;
    }
    /*********************************************************************/
    private function paypalToken(){
        if( $this->_allowedMethods( array('GET') ) ){
            $resp=0;

            require_once('paypal.php');
            $pagPaypal=new PagPaypal();
            $resp=$pagPaypal->getToken();

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function crons(){
        if( $this->_allowedMethods( array('GET') ) ){

            $resp=$ids=array();

            if( empty($this->vars['ids']) ){
                $this->_response( 200,1 );
            }

            if( gettype($this->vars['ids'])=="array" ){
                $ids=$this->vars['ids'];
            }else if( gettype($this->vars['ids'])=="string" ){
                $ids=explode(',',$this->vars['ids']);
            }

            $ids=array_unique($ids);

            foreach( $ids as $index=>$id ){
                $resp["cron{$id}"]=array($this->_cronRunner("_cron{$id}.php",array("hidden"=>1)));
            }

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function carrinhoPromocode(){
        if( $this->_allowedMethods( array('POST') ) ){

            if( "{$this->method}"==="POST" ){
                $voucher=array();
                if( !($codigo=$this->vars('codigo',false)) ){
                    $this->_response( 200,1 );

                }else if( !$voucher=$this->apiEngine->getPromocode($this->vars) ){
                    $this->_response( 200,1 );

                }else if( empty($voucher['qtde_disponivel']) ){
                    $this->_response( 200,1 );

                }else if( empty($voucher['status']) ){
                    $this->_response( 200,1 );
                }

                $carrinho=$this->apiEngine->getCarrinho($this->vars);
                //$this->_response( 200,1 );
                if(
                    empty($carrinho['carrinho']['id']) ||
                    empty($carrinho['carrinho']['itens']) ||
                    !$id_carrinho=$carrinho['carrinho']['id']
                ){
                    $this->_response( 200,1 );
                }

                $carrinho=$this->apiEngine->getCarrinho($this->vars);
                $this->_response( 200,1 );

            }

        }
    }
    /*********************************************************************/
    private function carrinhoItem(){
        if( $this->_allowedMethods( array('POST','DELETE') ) ){

            if( "{$this->method}"==="POST" ){

                $id_item=$id_produto=$id_variacao=0;
                $this->vars['index']=1;
                $prod=$produto=array();

                if( !($qtde=(int)$this->vars('qtde',1)) ){
                    $qtde=1;
                }

                if( isset($this->vars['id_produto']) ){

                    if( !($id_produto=(int)$this->vars('id_produto')) ){
                        $this->_response( 200,1 );
                    }else if( !($id_variacao=(int)$this->vars('id_variacao')) ){
                        $this->_response( 200,1 );
                    }else{
                        $prod=$this->apiEngine->getProduto($this->vars);

                        //$this->_response( 200,1 );

                        if( empty($prod['produto']) || !($produto=$prod['produto']) ){
                            $this->_response( 200,1 );

                        }else if( !isset($produto['variacoes_filtro'][$id_variacao]) ){
                            $this->_response( 200,1 );

                        }else if( empty($estoque=$produto['variacoes_filtro'][$id_variacao]['estoque']) ){
                            $this->_response( 200,1 );

                        }else if( $produto['variacoes_filtro'][$id_variacao]['estoque']<$qtde ){
                            $this->_response( 200,1 );
                        }
                    }

                }else if( isset($this->vars['id_item']) ){

                    if( !($id_item=(int)$this->vars('id_item')) ){
                        $this->_response( 200,1 );
                    }

                }else{

                    $this->_response( 200,1 );
                }

                $carrinho=$this->apiEngine->getCarrinho($this->vars);
                $carrinho_id=0;
                if( !empty($carrinho['carrinho']['id']) ){
                    $carrinho_id=$carrinho['carrinho']['id'];
                }

                if( !$carrinho_id ){
                    $carSave=$this->mysqli->getFields("carrinhos");

                    if( $this->userFull ){
                        $carSave['id_user']=$this->userFull['id'];
                    }

                    $carSave['id_loja']=$this->idLoja;
                    $carSave['fingerprint']=$this->signature;
                    $dados=array(
                        "tabela"=>"carrinhos",
                        "campos"=>$carSave,
                        "debug"=>$this->debugSQL,
                        //"debug"=>5,
                        "update"=>false
                    );
                    if( !($carrinho_id=$this->mysqli->sqlInsert($dados)) ){
                        $this->_response( 200,1 );
                    }
                }

                if( $carrinho_id ){

                    $item=$this->mysqli->getFields("carrinhos_item");
                    $item['id_carrinho']=$carrinho_id;

                    if( !$id_item ){

                        $item['id_produto']=$id_produto;
                        $item['id_variacao']=$id_variacao;
                        $item['sku']=$produto['sku'];
                        $variacoes=trim($produto['variacoes_filtro'][$id_variacao]['variacao']?:"Padrão");
                        $item['variacao']=$variacoes;

                        //$this->_response( 200,1 );

                    }else{

                        if( !isset($carrinho['carrinho']['itens'][$id_item]) ){
                            $this->_response( 200,1 );
                        }

                        $antigo=$carrinho['carrinho']['itens'][$id_item];

                        $this->vars['id_produto']=$antigo['id_produto'];
                        $prod=$this->apiEngine->getProduto($this->vars);

                        $id_variacao=$item['id_variacao']=$antigo['id_variacao'];

                        //$this->_response( 200,1 );

                        if( empty($prod['produto']) || !($produto=$prod['produto']) ){
                            $this->_response( 200,1 );

                        }else if( !isset($produto['variacoes_filtro'][$id_variacao]) ){
                            $this->_response( 200,1 );

                        }else if( empty($estoque=$produto['variacoes_filtro'][$id_variacao]['estoque']) ){
                            $this->_response( 200,1 );

                        }else if( $produto['variacoes_filtro'][$id_variacao]['estoque']<$qtde ){
                            $this->_response( 200,1 );
                        }

                        $item['id_produto']=$antigo['id_produto'];
                        $item['id']=$id_item;
                    }

                    $item['qtde']=$qtde;

                    $dados=array(
                        "tabela"=>"carrinhos_item",
                        "campos"=>$item,
                        "debug"=>$this->debugSQL,
                        //"debug"=>5,
                        "update"=>true
                    );

                    //$this->_response( 200,1 );

                    if( !$item=$this->mysqli->sqlInsert($dados) ){
                        $this->_response( 200,1 );
                    }

                    //$this->_response( 200,1 );

                    $carrinhoUpdate="
                    UPDATE `carrinhos`
                    SET
                        `id_promocode`='0',
                        `id_endereco`='0',
                        `cep`=''
                    WHERE `id`='{$carrinho_id}'
                    ;";
                    $dadosUpdate=array(
                        "debug"=>$this->debugSQL,
                        //"debug"=>5,
                        //"async"=>1,
                        "update"=>1
                    );
                    $resp=$this->mysqli->sqlQuery($carrinhoUpdate,$dadosUpdate);

                    $this->vars['index']=0;
                    $carrinho=$this->apiEngine->getCarrinho($this->vars);
                }

                $this->_response( 200,1 );

            }else if( "{$this->method}"==="DELETE" ){

                //$this->_response( 200,1 );

                $id_itens=$id_produtos=array();
                if( !($id_itens=$this->vars('ids',$id_itens)) && !($id_itens=$this->vars('id_itens',$id_itens)) ){
                    if( !$this->vars('id_produtos') ){
                        $this->_response( 200,1 );
                    }else if( !$id_produtos=$this->vars('id_produtos',$id_produtos) ){
                        $this->_response( 200,1 );
                    }
                }

                if( in_array(gettype($id_itens),array('string','integer')) ){
                    $id_itens=str_replace(' ','',$id_itens);
                    $id_itens=explode(',',$id_itens);
                }

                if( in_array(gettype($id_produtos),array('string','integer')) ){
                    $id_produtos=str_replace(' ','',$id_produtos);
                    $id_produtos=explode(',',$id_produtos);
                }

                //$this->_response( 200,1 );

                $carrinho=$this->apiEngine->getCarrinho($this->vars);

                $removidos=0;
                if( !empty($carrinho['carrinho']['itens']) && !empty($carrinho['carrinho']['id']) ){

                    foreach( $carrinho['carrinho']['itens'] as $item ){
                        $params=false;
                        if( $id_itens && in_array($item['id'],$id_itens) ){
                            $params=array(
                                'tabela'=>"carrinhos_item",
                                'debug'=>$this->debugSQL,
                                //'wherez'=>"",
                                'campos'=>array(
                                    "id"=>$item['id'],
                                    "id_carrinho"=>"{$carrinho['carrinho']['id']}"
                                )
                            );
                        }else if( $id_produtos && in_array($item['id_produto'],$id_produtos) ){
                            $params=array(
                                'tabela'=>"carrinhos_item",
                                'debug'=>$this->debugSQL,
                                //'wherez'=>"",
                                'campos'=>array(
                                    "id_produto"=>$item['id_produto'],
                                    "id_carrinho"=>"{$carrinho['carrinho']['id']}"
                                )
                            );
                        }

                        if( $params ){
                            $resposta=$this->mysqli->sqlDelete( $params );
                            $removidos++;
                        }
                    }
                }

                $carrinho=array();
                $carrinho['removidos']=$removidos;
                $carrinho+=$this->apiEngine->getCarrinho($this->vars);
                $this->_response( 200,1 );

            }

        }
    }
    /*********************************************************************/
    private function carrinho(){
        if( $this->_allowedMethods( array('GET','POST') ) ){

            if( "{$this->method}"==="GET" ){
                $carrinho=$this->apiEngine->getCarrinho($this->vars);

                //$this->_response( 200,1 );
                $this->_response( 200,1 );

            }else if( "{$this->method}"==="POST" ){
                //$carrinhoBase=$this->mysqli->getFields("carrinhos");

                $campos=array(
                    "id"=>NULL,
                    "status"=>1
                );

                $cep=0;
                if( !empty($this->vars['cep']) && ($cep=$this->funcs->validaCEP($this->vars['cep'])) ){
                    $campos['cep']=$cep;
                }

                $carrinho=$this->apiEngine->getCarrinho();

                if( !empty($carrinho['carrinho']['id']) ){
                    $campos["id"]="{$carrinho['carrinho']['id']}";
                }else{
                    $campos["fingerprint"]=$this->signature;
                }

                if( !empty($this->userFull['id']) ){
                    $campos['id_user']=$this->userFull['id'];
                }
                //$this->_response( 200,1 );

                if( !empty($this->idLoja) ){
                    $campos['id_loja']=$this->idLoja;
                }

                if( count($campos)>2 ){
                    $params=array(
                        'tabela'=>"carrinhos",
                        'debug'=>$this->debugSQL,
                        //'wherez'=>"",
                        'campos'=>$campos,
                        "update"=>true
                    );
                    $resposta=$this->mysqli->sqlInsert( $params );
                    //$this->_response( 200,1 );
                }

                $resp=$this->apiEngine->getCarrinho($this->vars);
                $this->_response( 200,1 );
            }

        }
    }
    /*********************************************************************/
    private function ping(){
        if( $this->_allowedMethods( array('GET','POST','PUT','PATCH','DELETE','OPTIONS','HEADER') ) ){
            $resp=array("status"=>42,"method"=>$this->method,"fields"=>$this->vars);

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function teste(){
        if( $this->_allowedMethods( array('GET','POST','PUT','PATCH','DELETE','OPTIONS','HEADER') ) ){
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function email(){
        if( $this->_allowedMethods( array('GET') ) ){
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function funcoesFrete(){
        if( $this->_allowedMethods( array('GET','POST') ) ){
            $extras=1;
            if( !empty($this->vars['extras']) ){
                $extras=$this->vars['extras'];
            }

            $limitado=0;
            if( isset($this->vars['limitado']) ){
                $limitado=$this->vars['limitado'];
            }

            $qtde_opcoes=2;
            if( isset($this->vars['qtde_opcoes']) ){
                $qtde_opcoes=$this->vars['qtde_opcoes'];
            }

            $res_end=$cep=$id_endereco=0;
            if( !($cep=$this->funcs->validaCEP($this->vars('cep'))) ){
                if( $this->vars('id_endereco') && !($res_end=$this->apiEngine->getEnderecos($this->vars)) ){
                    $this->_response( 200,1 );
                }

                if( $res_end ){
                    //$this->_response( 200,1 );
                    foreach( $res_end['enderecos'] as $endereco ){
                        $id_endereco=$endereco['id'];
                        $cep=$endereco['cep'];
                        break;
                    }
                }

                if( !$cep ){
                    $this->_response( 200,1 );
                }
            }

            $itens=array();
            $this->vars['cache_time']=0;
            $carrinho=$this->apiEngine->getCarrinho($this->vars);

            $id_variacao=$id_carrinho=NULL;

            if( ($id_variacao=$this->vars('id_variacao')) && !($itens=$this->apiEngine->getProdutosFrete($this->vars)) ){
                $this->_response( 200,1 );
            }

            if( !$itens && !empty($carrinho['carrinho']['id']) ){
                $this->vars['id_carrinho']=$id_carrinho="{$carrinho['carrinho']['id']}";
                if( !$id_variacao && !($itens=$this->apiEngine->getProdutosFreteCarrinho($this->vars)) ){
                    $this->_response( 200,1 );
                }
            }

            //$this->_response( 200,1 );

            $somaMin=29;
            $somaMax=200;

            //Em KG!
            $pesoMin=0.300;
            $pesoMax=30.000;
            //Em KG!

            $resp=array();
            $transportadoras=array();

            $id_frete=$this->vars('id_frete','');

            $opcoes_frete=$this->apiEngine->getDistribuidorasFrete();
            //$this->_response( 200,1 );

            if( $id_carrinho && $id_frete && empty($opcoes_frete['servicos'][$id_frete]) ){
                $this->_response( 200,1 );
            }else if( $id_frete && empty($opcoes_frete['servicos'][$id_frete]) ){
                foreach( $opcoes_frete as $id_frete=>$resposta ){
                    $id_frete=$resposta['id_frete'];
                    break;
                }
            }
            //$opcoes_frete=array_values($opcoes_frete);
            //$this->_response( 200,1 );

            $correiosOK=true;
            $braspress=false;
            $personalizado=true;

            $resposta=array(
                'limitado'=>$limitado,
                'carrinho'=>array(),
                'itens'=>array(),
                'frete'=>array()
            );

            foreach( $itens as $item ){
                $somaMedidas=100*($item['largura']+$item['altura']+$item['comprimento']);

                if( $somaMedidas<$somaMin ){}

                if( $somaMedidas>$somaMax ){}

                if( $item['peso']>$pesoMax ){}

                if( $item['peso']<$pesoMin ){
                    $item['peso']=$pesoMin;
                }

                if( !$correiosOK || !$limitado ){
                    if( !$correiosOK ){
                        unset($transportadoras["correios"]);
                    }
                    if( $braspress ){
                        $transportadoras["braspress"][]=$item;
                    }
                    if( $personalizado ){
                        $transportadoras["personalizado"][]=$item;
                    }
                }
            }

            //$this->_response( 200,1 );

            set_time_limit(10);

            $qtde_opcao=count($itens);

            $opcoes_arr=$arr_update=array();
            $padrao_ok=true;
            $prod_fretes=$qtde_opcoes=array();
            $prod_fretes['frete']=array();
            foreach( $transportadoras as $nome=>$pesqs ){
                $padrao_ok=true;
                foreach( $pesqs as $index=>$prod ){

                    switch( $nome ){
                        case 'braspress':
                            $respFrete=$this->funcs->calcularFreteBraspress($prod['config']);
                            //$this->_response( 200,1 );
                            break;

                        case 'personalizado':
                            $respFrete=$this->funcs->calcularFretePersonalizado($prod['config']);
                            //$this->_response( 200,1 );
                            break;

                        default:
                        case 'correios':
                            $respFrete=$this->funcs->calcularFreteCorreios($prod['config']);
                            //$this->_response( 200,1 );
                            break;
                    }
                    unset($prod['config']);

                    if( empty($respFrete['opcoes']) ){
                        break;
                    }

                    $fretado=1;
                    if( $prod['item']['gratis'] ){
                        $fretado=0;
                    }else{
                        //$this->_response( 200,1 );
                    }

                    if( !$id_carrinho ){
                        foreach( $respFrete['opcoes'] as $opcao ){
                            $idOpcao="{$opcao['frete_dec']}.{$opcao['id_frete']}";
                            $prod_fretes['frete'][$idOpcao]=$opcao;
                        }
                    }else{
                        //if( $id_frete ){
                        foreach( $respFrete['opcoes'] as $opcao ){
                            if( !$opcao['valido'] ){
                                continue;
                            }

                            $idOpcao=$opcao['id_frete'];
                            if( empty($qtde_opcoes[$idOpcao]) ){
                            }else{
                                $qtde_opcoes[$idOpcao]['qtde']++;
                                if( $qtde_opcoes[$idOpcao]['prazo_sys']<$opcao['prazo_sys'] ){
                                    $qtde_opcoes[$idOpcao]['prazo_sys']=$opcao['prazo_sys'];
                                    $qtde_opcoes[$idOpcao]['prazo_dias']=$opcao['prazo_dias'];
                                }
                                $qtde_opcoes[$idOpcao]['frete_dec']+=($opcao['frete_dec']*($fretado*$prod['item']['qtde']));
                            }

                            //if( $fretado ){
                            //  $this->_response( 200,1 );
                            //}

                            if( $id_frete && $id_frete==$opcao['id_frete'] ){
                                $valor=$opcao['frete_dec'];
                                if( $prod['item']['gratis'] ){
                                    $valor=0;
                                    //$padrao_ok=false;
                                }
                            }else if( $id_frete ){
                                //$this->_response( 200,1 );
                            }
                        }
                    }

                }
            }
            //$this->_response( 200,1 );

            if( $id_variacao ){
                ksort($prod_fretes['frete']);
                foreach( $prod_fretes['frete'] as &$opcao ){
                    $opcao['sel']=1;
                    break;
                }
                $prod_fretes['frete']=array_values($prod_fretes['frete']);
                $this->_response( 200,1 );
            }

            //$this->_response( 200,1 );

            $fretes_opcoes=array();
            $ordem=00.01;
            foreach( $qtde_opcoes as &$opcao ){
                if( $qtde_opcao==$opcao['qtde'] ){
                    unset($opcao['qtde']);
                    $opcao['frete']=$this->funcs->moneyReais($opcao['frete_dec']);
                    $opcao['prazo']=date("d/m/Y",strtotime("{$opcao['prazo_sys']}"));
                    $index=(float)$opcao['frete_dec']+$ordem;
                    $ordem=$ordem+$ordem;
                    $fretes_opcoes["{$index}"]=$opcao;
                }
            }

            //$this->_response( 200,1 );
            //$this->_response( 200,1 );
            //$this->_response( 200,1 );

            if( !$id_frete ){
                ksort($fretes_opcoes,SORT_NUMERIC);
                $fretes_opcoes=array_values($fretes_opcoes);
                $fretes_opcoes=array(
                    'frete'=>$fretes_opcoes
                    //,'debug'=>$qtde_opcoes
                );
                $this->_response( 200,1 );
            }

            $prazo_dias=20;
            if( !empty($qtde_opcoes[$id_frete]['prazo_dias']) ){
                $prazo_dias=$qtde_opcoes[$id_frete]['prazo_dias'];
            }
            $prazo_data=date("Y-m-d",strtotime("+{$prazo_dias} days"));

            if( $id_carrinho && $arr_update && $id_frete ){
                //$this->_response( 200,1 );

                $sqlUpdate1="
                UPDATE `carrinhos_item` SET
                    `frete`=
                        CASE `id`
                ";
                foreach( $arr_update['itens'] as $str_update){
                    $sqlUpdate1.="
                            {$str_update}";
                }
                $sqlUpdate1.="
                        END
                WHERE `id_carrinho`='{$id_carrinho}';
                ";
                //die($sqlUpdate1);

                $dadosUpdate=array(
                    "debug"=>$this->debugSQL,
                    //"debug"=>5,
                    //"async"=>1,
                    "update"=>1
                );
                $resp=$this->mysqli->sqlQuery($sqlUpdate1,$dadosUpdate);

                //$carrinho['arr_update']=$arr_update;
            }

            if( $id_carrinho && $prazo_dias && $id_frete ){
                $carrinhoUpdate="
                UPDATE `carrinhos` SET
                    `id_endereco`='{$id_endereco}',
                    `id_frete`='{$id_frete}',
                    `cep`='{$cep}',
                    `prazo_dias`='{$prazo_dias}',
                    `prazo_entrega`='{$prazo_data}'
                WHERE `id`='{$id_carrinho}';";
                //die($carrinhoUpdate);

                $dadosUpdate=array(
                    "debug"=>$this->debugSQL,
                    //"debug"=>5,
                    //"async"=>1,
                    "update"=>1
                );
                $resp=$this->mysqli->sqlQuery($carrinhoUpdate,$dadosUpdate);
                if( $resp ){
                    $carrinho=$this->apiEngine->getCarrinho($this->vars);
                    $this->_response( 200,1 );
                }
            }

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function funcoesCotacoes(){
        if( $this->_allowedMethods( array('GET') ) ){
            //https://www.quandl.com/blog/api-for-currency-data

            $resposta=$this->funcs->cotacoes($this->vars);
            sort($resposta);

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function cacheSearch(){
        if( $this->_allowedMethods( array('GET','POST') ) ){
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function cache(){
        if( $this->_allowedMethods( array('GET') ) ){

            if( !$this->cacheCodeUser ){

                $this->cacheCodeUser=$this->createNewName(1);

                $campos=array(
                    'fingerprint'=>$this->signature,
                    'cache'=>$this->cacheCodeUser
                );
                $params=array(
                    'tabela'=>"users_cache",
                    'debug'=>$this->debugSQL,
                    //'wherez'=>"",
                    'campos'=>$campos,
                    "update"=>true
                );
                $resposta=$this->mysqli->sqlInsert( $params );

            }

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function cadastroEmail( $facebookLogin=false ){
        if( $this->_allowedMethods( array('POST') ) ){
            $email=0;

            extract($this->vars);

            if( !$email=$this->funcs->validEmail($email) ){
                $this->_response( 200,1 );
            }

            if( $this->apiEngine->getUserByEmail($email) ){
                $this->_response( 200,1 );
            }

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function cadastro( $facebookLogin=false ){
        if( $this->_allowedMethods( array('POST') ) ){
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function perfil(){
        if( $this->_allowedMethods( array('GET','POST') ) ){

            if( "{$this->method}"==="GET" ){

                $this->vars['cache_time']=0;
                $respLogin["perfil"]=$this->userInfo;

                $this->_response( 200,1 );

            }else if( "{$this->method}"==="POST" ){

                $userInfo=$this->mysqli->getFields("users");

                //Campos nao editaveis
                unset(
                    $userInfo['id']
                    ,$userInfo['status']
                    ,$userInfo['data_criacao']
                    ,$userInfo['data_edicao']
                    ,$userInfo['email']
                    ,$userInfo['codigo']
                    ,$userInfo['senha']
                    ,$userInfo['user_name']
                );
                //$this->_response( 200,1 );

                $userUpdate=array();
                foreach( $userInfo as $nomeCampo=>$padrao ){
                    if( isset($this->vars[$nomeCampo]) ){
                        $userUpdate[$nomeCampo]=$this->vars[$nomeCampo];
                    }
                }

                $userUpdate["id"]=$this->userFull['id'];

                if( isset($this->vars['senha']) && $senha=trim($this->vars['senha']) ){
                    if( strlen($senha)>2 ){
                        $data_criacao=$this->userFull['data_criacao'];
                        $userUpdate['senha']=$this->funcs->dataEncrypt("{$senha}",$data_criacao);

                    }
                }

                if( isset($this->vars['username']) && $username=trim($this->vars['username']) ){
                    if( strlen($username)<5 ){
                        $emailAntigo=$this->userFull['email'];
                        list($username)=explode('@',$emailAntigo);
                        $username=substr($username,0,11).rand(1324,8675);
                    }
                    $username=$this->funcs->getCleartext($username);
                    $userUpdate['user_name']=strtolower(substr($username,0,15));
                }

                //$this->_response( 200,1 );

                if( count($userUpdate)>1 ){
                    $dados=array(
                        "tabela"=>"users",
                        "campos"=>$userUpdate,
                        "debug"=>$this->debugSQL,
                        //"debug"=>5,
                        "update"=>true
                    );
                    $insertId=(int)$this->mysqli->sqlInsert($dados);
                }

                $userInfo=$this->apiEngine->getUserByEmail($this->userInfo['email']);

                $this->_response( 200,1 );
            }else{
                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function perfilSenha(){
        if( $this->_allowedMethods( array('POST') ) ){

            if( "{$this->method}"==="POST" ){

                $data_agora=date("Y-m-d H:i:s",time());
                $data_limite=date("Y-m-d H:i:s",strtotime("+48 HOUR {$data_agora}"));

                $return=false;

                $user=array();
                if(
                    (   !isset($this->vars['email']) &&
                        !empty($this->userFull['email']) &&
                        ($email=$this->userFull['email'])
                    ) ||
                    ($email=$this->vars('user',false)) ||
                    ($email=$this->vars('email',false))
                ){
                    if( !($user=$this->apiEngine->getUserByEmail($email)) ){
                        $this->_response( 200,1 );
                    }

                    $user=$this->apiEngine->userFull;
                }

                if( $user ){

                    $codigo=$this->createNewName(6);
                    $userPassword=array(
                        'codigo'=>$codigo,
                        'id_user'=>$user['id'],
                        'data_limite'=>$data_limite
                    );
                    $dados=array(
                        "tabela"=>"users_recovery",
                        "campos"=>$userPassword,
                        "debug"=>$this->debugSQL,
                        //"debug"=>5,
                        "update"=>true
                    );
                    $return = $this->mysqli->sqlInsert($dados) ? true : false;

                    if( $return ){

                        $configMail=array(
                            'tipo'=>"2",
                            'modelo'=>$this->vars("modelo","recuperar-senha"),
                            'data'=>array(
                                'cvalidacao'=>$codigo
                            )
                        );

                        $configMail['emails']=array($user['nome']=>$user['email']);

                        $mailer=new mailSender();

                        if( true===($return=$mailer->send($configMail)) ){
                            $this->_response( 200,1 );
                        }
                    }

                    $this->_response( 200,1 );

                }else if( !empty($this->vars['codigo']) ){
                    $returnCodigo=$this->apiEngine->getRecoveryCode($this->vars);

                    //$this->_response( 200,1 );
                    if( $returnCodigo && !empty($returnCodigo['data_criacao']) ){

                        $password1=$password2="";
                        extract($this->vars);

                        if( empty($this->vars['password1']) || empty($this->vars['password2']) ){
                            $this->_response( 200,1 );
                        }

                        if( strlen($password1)<3 || strlen($password2)<3 ){
                            $this->_response( 200,1 );
                        }

                        if( "{$password1}"!=="{$password2}" ){
                            $this->_response( 200,1 );
                        }

                        /*CRIPTOGRAFIA DA SENHA*/
                        $data_criacao=$returnCodigo['data_criacao'];
                        $senhaCrip=$this->funcs->dataEncrypt("{$password1}",$data_criacao);
                        /*CRIPTOGRAFIA DA SENHA*/

                        $user=array(
                            'id'=>$returnCodigo['id_user'],
                            'senha'=>$senhaCrip
                        );

                        $dados=array(
                            "tabela"=>"users",
                            "campos"=>$user,
                            "debug"=>$this->debugSQL,
                            //"debug"=>5,
                            "update"=>true
                        );
                        $return=(int)$this->mysqli->sqlInsert($dados) ? true : false;

                        $params=array(
                            'debug'=>$this->debugSQL,
                            'tabela'=>"api_sessions_site",
                            'wherez'=>" OR TIMESTAMPDIFF(MONTH,`data_criacao`,NOW())>1",
                            'campos'=>array(
                                "id_user"=>"{$returnCodigo['id_user']}"
                            )
                        );
                        $resposta=$this->mysqli->sqlDelete( $params );

                        $params=array(
                            'debug'=>$this->debugSQL,
                            'tabela'=>"api_sessions_site",
                            //'wherez'=>" OR TIMESTAMPDIFF(MONTH,`data_criacao`,NOW())>1",
                            'campos'=>array(
                                "signature"=>"{$this->signature}"
                            )
                        );
                        $resposta=$this->mysqli->sqlDelete( $params );

                        $params=array(
                            'debug'=>$this->debugSQL,
                            'tabela'=>"users_recovery",
                            //'wherez'=>" OR TIMESTAMPDIFF(MONTH,`data_criacao`,NOW())>1",
                            'campos'=>array(
                                "id_user"=>"{$returnCodigo['id_user']}"
                            )
                        );
                        $resposta=$this->mysqli->sqlDelete( $params );

                    }else{
                        $this->_response( 200,1 );
                    }

                    $this->_response( 200,1 );
                }

                $this->_response( 200,1 );

            }
        }
    }
    /*********************************************************************/
    private function perfilValidar(){
        if( $this->_allowedMethods( array('POST') ) ){

            $user=$codigoValido=false;

            if( isset($this->vars['email']) ){

                $email=$this->vars['email'];

                if( !$email=$this->funcs->validEmail($email) ){
                    $this->_response( 200,1 );
                }

                if( !($user=$this->apiEngine->getUserByEmail($email)) ){
                    $this->_response( 200,1 );
                }

                //$this->_response( 200,1 );

                if( empty($user['validado']) ){
                    $data_agora=date("Y-m-d H:i:s",time());
                    $data_limite=date("Y-m-d H:i:s",strtotime("+48 HOUR {$data_agora}"));

                    $codigo=$this->createNewName(6);

                    /*EMAIL VALIDACAO CADASTRO*/
                    $mailer=new mailSender();

                    $configMail=array(
                        'tipo'=>"2",
                        'modelo'=>"cadastro-validar",
                        'data'=>array(
                            'clientenome'=>"{$user['nome']}",
                            'cvalidacao'=>$codigo
                        )
                    );

                    $configMail['emails']=array("{$user['nome']}"=>"{$user['email']}");

                    $return = $mailer->send($configMail);
                    /*EMAIL VALIDACAO CADASTRO*/

                    $userPassword=array(
                        'codigo'=>$codigo,
                        'id_user'=>$user['id'],
                        'data_limite'=>$data_limite
                    );
                    $dados=array(
                        "tabela"=>"users_validar",
                        "campos"=>$userPassword,
                        "debug"=>$this->debugSQL,
                        //"debug"=>5,
                        "update"=>true
                    );
                    $return = $this->mysqli->sqlInsert($dados) ? true : false;

                    //$this->_response( 200,1 );
                }

                $this->_response( 200,1 );

            }else if( isset($this->vars['codigo']) ){

                if( !empty($this->vars['codigo']) ){
                    $codigoValido=$this->apiEngine->getValidationCode($this->vars)?:array();
                }

                if( empty($codigoValido['email']) ){
                    //$this->_response( 200,1 );
                    $this->_response( 200,1 );
                }
                $email=$codigoValido['email'];

                if( !($user=$this->apiEngine->getUserByEmail($email)) ){
                    $this->_response( 200,1 );
                }

                $respLogin["perfil"]=$this->userInfo;
                $respLogin["carrrinho"]=$this->apiEngine->getCarrinho($this->vars);
                $this->cacheCodeLoja=$this->apiEngine->cacheCodeLoja;
                $this->userFull=$this->apiEngine->userFull;

                $userUpdate=array(
                    'id'=>$this->userInfo['id'],
                    'validado'=>1
                );

                $dados=array(
                    "tabela"=>"users",
                    "campos"=>$userUpdate,
                    "debug"=>$this->debugSQL,
                    //"debug"=>5,
                    "update"=>true
                );
                $return=(int)$this->mysqli->sqlInsert($dados) ? true : false;

                $params=array(
                    'debug'=>$this->debugSQL,
                    'tabela'=>"users_validar",
                    //'wherez'=>" OR TIMESTAMPDIFF(MONTH,`data_criacao`,NOW())>1",
                    'campos'=>array(
                        "id_user"=>"{$this->userInfo['id']}"
                    )
                );
                $resposta=$this->mysqli->sqlDelete( $params );

                $this->_response( 200,1 );
            }

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function perfilEnderecos(){
        if( $this->_allowedMethods( array('GET','POST','DELETE') ) ){

            if( "{$this->method}"==="GET" ){

                $this->vars['cache_time']=0;
                $enderecos=$this->apiEngine->getEnderecos($this->vars);
                $this->_response( 200,1 );

            }else if( "{$this->method}"==="POST" ){

                $id_endereco=NULL;
                if( !empty($this->vars['id']) || !empty($this->vars['id_endereco']) ){
                    if( !empty($this->vars['id_endereco']) ){
                        $id_endereco=$this->vars['id_endereco'];
                    }else{
                        $id_endereco=$this->vars['id'];
                    }
                }

                $enderecoBase=$this->mysqli->getFields("users_endereco");

                $enderecoSave=array();
                foreach( $enderecoBase as $nomeCampo=>$valorPadrao ){
                    if( !isset($proibidos[$nomeCampo]) && isset($this->vars[$nomeCampo]) ){
                        $enderecoSave[$nomeCampo]=$this->vars[$nomeCampo];
                    }
                }

                $enderecoSave['id']=$id_endereco;
                $enderecoSave['id_user']=$this->userFull['id'];

                $update=false;
                if( $id_endereco ){
                    $update=true;
                }

                if( !empty($this->vars['padrao']) ){

                    $dados=array(
                        "debug"=>$this->debugSQL,
                        "debug"=>5,
                        //"async"=>1,
                        "update"=>1
                    );

                    $stringUpdate="
                    UPDATE `users_endereco`
                    SET `padrao`='0'
                    WHERE `id_user`='{$this->userFull['id']}'
                    ;";
                    $resp=$this->mysqli->sqlQuery($stringUpdate,$dados);
                }

                $dados=array(
                    "tabela"=>"users_endereco",
                    "campos"=>$enderecoSave,
                    "debug"=>$this->debugSQL,
                    //"debug"=>5,
                    "update"=>$update
                );

                if( !$resp=$this->mysqli->sqlInsert($dados) ){
                    $this->_response( 200,1 );
                }

                $this->vars['cache_time']=0;
                unset($this->vars['id'],$this->vars['id_endereco']);
                $enderecos=$this->apiEngine->getEnderecos($this->vars);
                $this->_response( 200,1 );

            }else if( "{$this->method}"==="DELETE" ){

                $id_endereco=NULL;
                if( empty($this->vars['id']) && empty($this->vars['id_endereco']) ){
                    $this->_response( 200,1 );
                }

                if( !empty($this->vars['id_endereco']) ){
                    $id_endereco=$this->vars['id_endereco'];
                }else{
                    $id_endereco=$this->vars['id'];
                }

                $params=array(
                    'debug'=>$this->debugSQL,
                    'tabela'=>"users_endereco",
                    //'wherez'=>" OR TIMESTAMPDIFF(MONTH,`data_criacao`,NOW())>1",
                    'campos'=>array(
                        "id"=>"{$id_endereco}"
                    )
                );
                $resposta=$this->mysqli->sqlDelete( $params );

                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function login($facebookLogin=false){
        unset($this->userInfo['facebookLogin']);

        if( $this->_allowedMethods( array('POST') ) ){
            $senha=$password="";
            extract($this->vars);

            $senha=$senha?$senha:$password;

            $respLogin=array(
                "perfil"=>array()
            );

            if( !$facebookLogin ){
                if( empty($senha) ){
                    $this->_response( 200,1 );
                }
            }

            if( isset($email) || isset($celular) || isset($user) ){
                if( 
                    ( isset($email) && $loginData=$this->funcs->validEmail($email) ) ||
                    ( isset($user) && $loginData=$this->funcs->validEmail($user) )
                ){
                    $this->userInfo=$this->apiEngine->getUserByEmail($loginData);

                }else if( 
                    ( isset($celular) && $loginData=$this->funcs->validPhone($celular) ) ||
                    ( isset($user) && $loginData=$this->funcs->validPhone($user) )
                ){
                    $this->userInfo=$this->apiEngine->getUserByPhone($loginData);

                }else if( isset($user) && $loginData=$this->funcs->validUsername($user) ){
                    $this->userInfo=$this->apiEngine->getUserByUsername($loginData);
                }
            }else{
                $this->_response( 200,1 );
            }

            //$this->_response( 200,1 );

            if( !$this->userInfo ){
                $this->_response( 200,1 );
            }

            //$this->_response( 200,1 );
            $this->userFull=$this->apiEngine->userFull;
            //$this->_response( 200,1 );

            /*VERIFICACOES COMO SENHA E STATUS*/
            if(
                !$facebookLogin && 
                !$this->funcs->dataCompare("{$this->userFull['senha']}","{$senha}",$this->userFull['data_criacao'])
            ){
                $this->_response( 200,1 );
            }

            if( "{$this->userInfo['status']}"!=="1" ){
                $this->_response( 200,1 );
            }
            /*VERIFICACOES COMO SENHA E STATUS*/

            $respLogin["perfil"]=$this->userInfo;
            $respLogin["carrrinho"]=$this->apiEngine->getCarrinho($this->vars);

            $this->cacheCodeLoja=$this->apiEngine->cacheCodeLoja;

            //$this->_response( 200,1 );
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function logout(){
        if( $this->_allowedMethods( array('GET') ) ){
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produto(){
        if( $this->_allowedMethods( array('GET') ) ){

            if( empty($this->vars['slug']) && empty($this->vars['id']) && empty($this->vars['id_produto']) ){
                $this->_response( 200,1 );
            }

            $produto=$this->apiEngine->getProduto($this->vars);

            if( empty($produto['produto']) ){
                $this->_response( 200,1 );
            }

            $this->_response( 200,1 );

        }
    }
    /*********************************************************************/
    private function produtoGaleria(){
        if( $this->_allowedMethods( array('GET') ) ){
            if( "{$this->method}"==="GET" ){
                $listar=0;
                if( empty($this->vars['id']) || !$this->funcs->isNumeric($id_produto=$this->vars['id']) ){
                    $this->_response( 200,1 );
                }
                extract($this->vars);

                $config=array('id_produto'=>$id_produto,'listar'=>$listar);
                $response=$this->apiEngine->getProdutoGaleria($config);

                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function produtosFornecedores(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getProdutosFornecedores($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produtosPropriedades(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getProdutosPropriedades($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produtosCategorias(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getProdutosCategorias($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produtosTags(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getProdutosTags($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produtosMercados(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getProdutosMercados($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produtosDisponibilidades(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getProdutosDisponibilidades($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produtosDestaques(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getProdutosDestaques($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produtosColecoes(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getProdutosColecoes($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function produtos(){
        if( $this->_allowedMethods( array('GET') ) ){
            $this->vars['cache_time']=30;
            $res=$this->apiEngine->getProdutos($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function favoritos(){
        if( $this->_allowedMethods( array('GET','POST','DELETE') ) ){

            if( "{$this->method}"==='GET' ){

                $this->vars['favoritos']=1;
                $res=$this->apiEngine->getProdutos($this->vars);
                $this->_response( 200,1 );

            }else if( "{$this->method}"==='POST' ){

                $id_produto=0;

                if( !empty($this->vars['id']) ){
                    $id_produto=$this->vars['id'];
                }else if( !empty($this->vars['id_produto']) ){
                    $id_produto=$this->vars['id_produto'];
                }else{
                    $this->_response( 200,1 );
                }

                $favoritoSave=array(
                    "id_user"=>"{$this->userFull['id']}",
                    'id_produto'=>$id_produto
                );

                $update=true;
                $dados=array(
                    "tabela"=>"users_favoritos",
                    "campos"=>$favoritoSave,
                    "debug"=>$this->debugSQL,
                    //"debug"=>5,
                    "update"=>$update
                );

                if( !($resp=$this->mysqli->sqlInsert($dados)) ){
                    $this->_response( 200,1 );
                }

                $this->_response( 200,1 );

            }else if( "{$this->method}"==='DELETE' ){

                $id_produto=0;

                if( !empty($this->vars['id']) ){
                    $id_produto=$this->vars['id'];
                }else if( !empty($this->vars['id_produto']) ){
                    $id_produto=$this->vars['id_produto'];
                }else{
                    $this->_response( 200,1 );
                }

                $params=array(
                    'debug'=>$this->debugSQL,
                    'tabela'=>"users_favoritos",
                    //'wherez'=>" OR TIMESTAMPDIFF(MONTH,`data_criacao`,NOW())>1",
                    'campos'=>array(
                        "id_produto"=>"{$id_produto}"
                    )
                );
                $resposta=$this->mysqli->sqlDelete( $params );

                $this->_response( 200,1 );
            }

        }
    }
    /*********************************************************************/
    private function mercados(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getMercados($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function banners(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getBanners($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function faqs(){
        if( $this->_allowedMethods( array('GET','POST') ) ){

            if( "{$this->method}"==="GET" ){

                $faqs=$this->apiEngine->getFaqs($this->vars);
                $this->_response( 200,1 );

            }else if( "{$this->method}"==="POST" ){

                if( !($id=$this->vars('id',false)) ){
                    $this->_response( 200,1 );
                }

                $faqs=$this->apiEngine->getFaqs($this->vars);

                //$this->_response( 200,1 );

                if( !empty($faqs['faqs']) ){
                    $faqEditar=array();
                    foreach( $faqs['faqs'] as $faq ){
                        if( $id==$faq['id'] ){
                            $faqEditar['id']=$faq['id'];
                            $faqEditar['id_loja']=$this->idLoja;
                            $faqEditar['qtde_views']=$faq['qtde_views'] + 1;
                            break;
                        }
                    }

                    if( $faqEditar ){
                        $dados=array(
                            "tabela"=>"lojas_faq",
                            "campos"=>$faqEditar,
                            "debug"=>$this->debugSQL,
                            //"debug"=>5,
                            "update"=>true
                        );
                        if( !($resp=$this->mysqli->sqlInsert($dados)) ){
                            $this->_response( 200,1 );
                        }

                        $this->_response( 200,1 );
                    }
                }

                $this->_response( 200,1 );
            }

        }
    }
    /*********************************************************************/
    private function contato(){
        if( $this->_allowedMethods( array('GET','POST') ) ){

            if( "{$this->method}"==="GET" ){
                $contato=$this->apiEngine->getContato($this->vars);

                $this->_response( 200,1 );

            }else if( "{$this->method}"==="POST" ){

                $nome=0;
                if( !$nome=$this->vars('nome',false) ){
                    $this->_response( 200,1 );
                }

                $email=0;
                if( !($email=$this->vars('email',false)) || !$email=$this->funcs->validEmail($email) ){
                    $this->_response( 200,1 );
                }

                $mensagem=0;
                if( !$mensagem=$this->vars('mensagem',false) ){
                    $this->_response( 200,1 );
                }

                $id_contato=0;
                if( !($id_contato=$this->vars('id',false)) && !($id_contato=$this->vars('id_contato',false)) ){
                    $this->_response( 200,1 );
                }

                $assunto="";
                $contato=$this->apiEngine->getContatoEmails($this->vars);
                //$this->_response( 200,1 );
                if( empty($contato['id_contato']) || $id_contato!=$contato['id_contato'] ){
                    $this->_response( 200,1 );
                }
                $assunto=$contato['nome'];
                $emails=explode(',',$contato['emails']);

                $resposta=array('Tudo certo até agora! Finge que funcionou! ;D');

                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function contatoEmails(){
        if( $this->_allowedMethods( array('GET') ) ){
            if( "{$this->method}"==="GET" ){

                $emails=$this->apiEngine->getcontatoEmails($this->vars);

                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function institucional(){
        if( $this->_allowedMethods( array('GET') ) ){
            if( "{$this->method}"==="GET" ){
                $institucional=$this->apiEngine->getInstitucional();

                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function termos(){
        if( $this->_allowedMethods( array('GET') ) ){
            if( "{$this->method}"==="GET" ){
                $termos=$this->apiEngine->getTermos();

                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function menu(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getMenu($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function pedidos(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getPedidos($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function pedidoStatus(){
        if( $this->_allowedMethods( array('GET') ) ){

            if( "{$this->method}"==="GET" ){
                $id=0;
                if( empty($this->vars['id']) && empty($this->vars['id_pedido']) ){
                    $this->_response( 200,1 );
                }

                $pedido=$this->apiEngine->getPedido($this->vars);
                if( empty($pedido['pedido']) ){
                    $this->_response( 200,1 );
                }

                $resposta=$this->apiEngine->getPedidosStatus($this->vars);
                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function pagamento(){
        if( $this->_allowedMethods( array('POST') ) ){

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function pedido(){
        if( $this->_allowedMethods( array('GET','POST') ) ){
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function tags(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getTags($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function fornecedores(){
        if( $this->_allowedMethods( array('GET') ) ){
            $res=$this->apiEngine->getFornecedores($this->vars);
            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function fornecedor(){
        if( $this->_allowedMethods( array('GET') ) ){

            if( "{$this->method}"==="GET" ){
                $id_fornecedor=0;
                if( !empty($this->vars['id']) ){
                    $id_fornecedor=$this->vars['id'];
                }else if( !empty($this->vars['id_fornecedor']) ){
                    $id_fornecedor=$this->vars['id_fornecedor'];
                }else{
                    $this->_response( 200,1 );
                }

                if( !($res=$this->apiEngine->getFornecedor(array('id_fornecedor'=>$id_fornecedor))) ){
                    $this->_response( 200,1 );
                }

                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function fornecedorGaleria(){
        if( $this->_allowedMethods( array('GET','POST','DELETE') ) ){
            if( "{$this->method}"==="GET" ){
                $listar=0;
                if( empty($this->vars['id']) || !($id_fornecedor=$this->vars['id']) ){
                    $this->_response( 200,1 );
                }
                extract($this->vars);

                $config=array('id_produto'=>$id_produto,'listar'=>$listar);
                $response=$this->apiEngine->getFornecedorGaleria($config);

                $this->_response( 200,1 );
            }
        }
    }
    /*********************************************************************/
    private function funcoesEndereco(){
        if( $this->_allowedMethods( array('GET') ) ){
            $lat=$lng=$cep=0;
            extract($this->vars);

            $key="?";
            //$key="?key=YOUR_API_KEY";
            $url="http://maps.googleapis.com/maps/api/geocode/json{$key}latlng={$lat},{$lng}";
            if( $cep ){
                $url="http://maps.googleapis.com/maps/api/geocode/json{$key}components=country:BR|postal_code:{$cep}&sensor=false";
            }

            $endereco=array();

            $configGet=array(
                'name'=>$url,
                'timeout'=>86400//24h
            );
            if( !$output=$this->funcs->_getCache($configGet) ){
                $resp=file_get_contents($url);
                $output=json_decode($resp);
                if( !$output || $output->status!=='OK' ){
                    $this->_response( 200,1 );
                }
                $configSet=array(
                    'name'=>$url,
                    'content'=>$output
                );
                $this->funcs->_setCache($configSet);
            }

            $configGet=array(
                'name'=>array($lat,$lng,$cep),
                'timeout'=>86398//24h
            );
            if( !$endereco=$this->funcs->_getCache($configGet) ){
                $indice['cep']=array("field"=>"long_name","types"=>array("postal_code"));
                $indice['logradouro']=array("field"=>"short_name","types"=>array("route"));
                $indice['cidade']=array("field"=>"long_name","types"=>array("administrative_area_level_2"));
                $indice['pais']=array("field"=>"long_name","types"=>array("country"));
                $indice['uf']=array("field"=>"short_name","types"=>array("administrative_area_level_1"));
                $indice['estado']=array("field"=>"long_name","types"=>array("locality","political"));
                $indice['bairro']=array("field"=>"long_name","types"=>array("sublocality","sublocality_level_1"));

                $index=0;
                $tentativas=10;

                do{

                    $resultado=$output->results[$index];
                    $endereco['completo']="";
                    $endereco['numero']="0";
                    if( !empty($resultado->formatted_address) ){
                        $endereco['completo']=$resultado->formatted_address;
                    }

                    foreach( $resultado->address_components as $atual=>$campo ){
                        $campo=(array)$campo;
                        foreach( $indice as $nome_campo=>$config ){
                            foreach( $config['types'] as $type ){
                                if( in_array($type,$campo['types']) ){
                                    $endereco[$nome_campo]=$campo[$config['field']];
                                    $config['types']=array();
                                    break;
                                }
                            }
                        }
                        $tentativas--;
                    }

                    break;
                }while( $tentativas );

                $endereco['cep']=$this->funcs->validaCEP($endereco['cep'],"br");

                $configSet=array(
                    'name'=>array($lat,$lng,$cep),
                    'content'=>$endereco
                );
                $this->funcs->_setCache($configSet);
            }

            $this->_response( 200,1 );
        }
    }
    /*********************************************************************/
    private function _requestStatus($code=500){
        switch( "{$code}" ){
            case '200':
                $statusType="success";
                $statusMsg="OK";
                break;

            case '500':
            default:
                $statusType="error";
                $statusMsg="Internal Server Error";
                break;
        }

        return array( $statusType,$statusMsg );
    }
}?>