| Server IP : 162.214.74.102 / Your IP : 216.73.217.114 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/leve/application/plugins/module_imobles/helpers/ |
Upload File : |
<?php
class CrawlerHelper {
function handleListing($listings, $modelEnterprises, $modelUnitType, $modelUnit, $listing_id = null, $listing_enterprise_id = null, $enterprise_target_id = null){
// inicio as variáveis
$arr_enterprise = array();
$arr_unitType = array();
$arr_unit = array();
$arr_listing = array();
$obs_info = null;
$msg_return = null;
$listing_review = true;
// Resultado da API
if(!isset($listings->listing))
{
$return = array("enterprise_new" => null);
return $return;
}
$result_listing = $listings->listing;
$result_account = $listings->account;
$result_medias = $listings->medias;
$result_accountLink = $listings->accountLink;
$result_link = $listings->link;
// Monto a string de camparação com empreendimentos já cadastrados
$description = $listings->listing->description;
$title = $listings->listing->title;
$complement = $listings->listing->address->complement;
$codigo_ext = $listings->listing->externalId;
$str_compare = $description.' @@@ '.$title.' @@@ '.$complement.' @@@ '.$codigo_ext;
/*
* Verifico se o anúncio já está cadastrado
*/
if($listing_id === null)
{
$listing_review = false;
$listing_aux = ORM::for_table('module_imobles_listings')
->where('crawler_listing_id', $result_listing->id)
->where('crawler_type', 'vivareal')
->where('crawler_portal', $result_listing->portal)
->find_one();
if(isset($listing_aux->id) && $listing_aux->id > 0)
{
$listing_id = $listing_aux->id;
$listing_aux->crawler_status = $result_listing->status;
$listing_aux->crawler_json = json_encode($listings);
$listing_aux->updated_at = date('Y-m-d H:i:s');
$listing_aux->description = $result_listing->description;
$listing_aux->title = $result_listing->title;
// TODO: criar um planilha para salvar a evolução de preços de cada anúncio
$listing_aux->crawler_pricingInfos = json_encode($result_listing->pricingInfos);
$listing_aux->crawler_businessType = $result_listing->pricingInfos[0]->businessType;
$listing_aux->crawler_price = isset($result_listing->pricingInfos[0]->price)?$result_listing->pricingInfos[0]->price:null;
$listing_aux->crawler_whatsappNumber = $result_listing->whatsappNumber;
$listing_aux->crawler_listing_link = $result_link->href;
if($result_listing->status != "ACTIVE")
{
$listing_aux->unavailable = 1;
}
$listing_aux->save();
//persist pricing obj
$price = $listing_aux->crawler_price;
$yearlyIptu = @$result_listing->pricingInfos[0]->yearlyIptu;
$monthlyCondoFee = @$result_listing->pricingInfos[0]->monthlyCondoFee;
$listing_id = $listing_aux->id;
$unit_type_id = $listing_aux->unit_type_id;
$rental = $listing_aux->crawler_businessType == "RENTAL" ? 1 : null;
$this->persistPricing($price, $yearlyIptu, $monthlyCondoFee, $listing_id, $unit_type_id, $rental);
// echo "##################### ANÚNCIO JÁ CADASTRADO ###################\n\n";
return $listing_id;
}
}
/*
*
* CADASTRO DO EMPREENDIMENTO
*
*/
// Inicio as variáveis de controle
$enterprise_id = null;
$isNewEnterprise = true;
if($enterprise_target_id == null)
{
// Monto o array com o endereço do empreendimento
$address_cep = preg_replace('/\D/', '', $result_listing->address->zipCode);
$arr_address_listing = array(
'state' => null,
'city' => null,
'zipcode' => $address_cep,
'neighborhood' => null,
'street' => null,
'number' => null);
// Pego a Rua do Anúncio
$address_logradouro = null;
if(isset($result_listing->address->street) && $result_listing->address->street != '')
{
$address_logradouro = $result_listing->address->street;
}
$arr_address_listing['street'] = $address_logradouro;
// Pego o Bairro do Anúncio
$address_bairro = null;
if(isset($result_listing->address->neighborhood) && $result_listing->address->neighborhood != '')
{
$address_bairro = $result_listing->address->neighborhood;
}
$arr_address_listing['neighborhood'] = $address_bairro;
// Pego o Número do Anúncio
$address_number = null;
if(isset($result_listing->address->streetNumber) && intval($result_listing->address->streetNumber) > 0)
{
$address_number = intval($result_listing->address->streetNumber);
}
$arr_address_listing['number'] = $address_number;
// Pego a Cidade do Anúncio
$address_city = $result_listing->address->city;
$arr_address_listing['city'] = $address_city;
// Pego o Estado do Anúncio
$address_state = $result_listing->address->stateAcronym;
$arr_address_listing['state'] = $address_state;
if(isset($result_listing->address->stateAcronym) && !empty($result_listing->address->stateAcronym))
{
$c = ORM::for_table("state")->where("uf_state", trim($result_listing->address->stateAcronym))->find_one();
if($c)
{
$address_state_id = $c->id;
$arr_address_listing['state_id'] = $address_state_id;
// Pego o ID da Cidade
if(isset($result_listing->address->city) && !empty($result_listing->address->city))
{
$c = ORM::for_table("city")
->where("city_name", trim($result_listing->address->city))
->where("id_state", $c->id)
->find_one();
if ($c)
{
$address_city_id = $c->id;
$arr_address_listing['city_id'] = $address_city_id;
}
}
}
}
/*
* Comparo o anúncio atual com a base de anúncios
* para verificar se trata-se de um empreendimento já cadastrado
*/
$listing_similaridade = null;
$listing_compare = $listings;
$compare_resut = $this->compareEnterprise($str_compare,
$address_state_id,
$address_city_id,
$address_cep,
$address_bairro,
$address_logradouro,
$address_number,
$listing_compare,
$listing_enterprise_id);
// Monto o array com as imagens do anúncio
$listing_arr_images = isset($compare_resut['arr_imgs'])?$compare_resut['arr_imgs']:array();
// Verifico se deu Match com algum outro anúncio
if($compare_resut && isset($compare_resut['enterprise']->id))
{
$isNewEnterprise = false;
$enterprise_id = $compare_resut['enterprise']->id;
$listing_similaridade = isset($compare_resut['similaridade'])?$compare_resut['similaridade']:null;
// echo "######################### | EMPREENDIMENTO JÁ CADASTRADO | "
// . "MATCH TYPE: ".$compare_resut['similaridade']['type']." | ".$compare_resut['enterprise']->id." | ".$compare_resut['enterprise']->name.".\n";
}
elseif($address_logradouro)
{
$compare_resut = $this->compareEnterprise($str_compare,
$address_state_id,
$address_city_id,
$address_cep,
$address_bairro,
null,
$address_number,
$listing_compare,
$listing_enterprise_id);
if($compare_resut && isset($compare_resut['enterprise']->id))
{
$isNewEnterprise = false;
$enterprise_id = $compare_resut['enterprise']->id;
$listing_similaridade = isset($compare_resut['similaridade'])?$compare_resut['similaridade']:null;
// echo "######################### | EMPREENDIMENTO JÁ CADASTRADO | BUSCA POR BAIRRO | "
// . "MATCH TYPE: ".$compare_resut['similaridade']['type']." | ".$compare_resut['enterprise']->id." | ".$compare_resut['enterprise']->name.".\n";
}
}
// Verifico se está revisando um anúncio e se o empreendimento encontrado é o mesmo do atual
if(isset($compare_resut['enterprise']->id) && $compare_resut['enterprise']->id === $listing_enterprise_id)
{
$return = array("enterprise_new" => $compare_resut['enterprise'],
"match_type" => $compare_resut['similaridade']['type']);
return $return;
}
}
else
{
$isNewEnterprise = false;
$enterprise_id = $enterprise_target_id;
$listing_similaridade = null;
$compare_resut['enterprise'] = ORM::for_table("module_imobles_enterprise")->find_one($enterprise_id);
$compare_resut['similaridade']['type'] = 'manual';
$listing_similaridade['merge_type'] = 'manual';
// Verifico se está revisando um anúncio e se o empreendimento encontrado é o mesmo do atual
if($enterprise_target_id === $listing_enterprise_id)
{
$return = array("enterprise_new" => $compare_resut['enterprise'],
"match_type" => $compare_resut['similaridade']['type']);
return $return;
}
}
/*
* Se não encontrar nenhum empreendimento no mesmo endereço, cadastro um novo
*/
if($isNewEnterprise == true)
{
if($listing_id > 0)
{
$return = array("enterprise_new" => null);
return $return;
}
// pego os dados do endereço
// $address_number = 2394;
// $address_logradouro = 'Rodovia Virgílio Várzea';
// $address_cep = '88054-605';
// $address_state = 'SC';
// $address_city = 'Florianópolis';
// $address_bairro = 'Saco Grande';
// $address_encoded = 'Rodovia Virgílio Várzea, 2394 - Saco Grande, Florianópolis - SC, 88054-605';
//
// Procuro pelo endereço no Google
//
$address_encoded = null;
// if($address_logradouro && $address_number && $address_bairro)
// {
// $address_encoded .= $address_logradouro.', ';
// $address_encoded .= $address_number.' - ';
// $address_encoded .= $address_bairro.', ';
// $address_encoded .= $address_city.' - '.$address_state;
// }
if($address_logradouro && $address_bairro)
{
$address_encoded .= $address_logradouro.' - ';
$address_encoded .= $address_bairro.', ';
$address_encoded .= $address_city.' - '.$address_state;
}
elseif($address_bairro)
{
$address_encoded .= $address_bairro.', ';
$address_encoded .= $address_city.' - '.$address_state;
}
$address_encoded = $this->cleanString(strtolower($address_encoded));
$address_encoded_query = $address_logradouro.' - '.$address_bairro.', '.$address_city.' - '.$address_state;
// Verifico se já foi feita a pesquisa na API NEARBY do Google para esse endereço
$google_nearby = true;
$arr_google_nearby = ORM::for_table('module_imobles_google_nearby')
->find_many()->order_by_desc('id');
foreach ($arr_google_nearby as $gnb)
{
if($gnb->address_encoded == $address_encoded)
{
$google_nearby = false;
// echo "GOOGLE PLACE JÁ VERIFICADO: ".$gnb->address_encoded."\n";
$arr_enterprise['latitude'] = $gnb->latitude;
$arr_enterprise['longitude'] = $gnb->longitude;
break;
}
}
if($address_encoded && $google_nearby == true)
{
// echo "ENDEREÇO DO EMPREENDIMENTO: ".$address_encoded."\n";
$address_encoded_url = urlencode($address_encoded_query);
$url = 'https://maps.googleapis.com/maps/api/geocode/json?'
. 'address='.$address_encoded_url
. '&key=AIzaSyC0vUVt5Cy1kR1mP0BmRf94EBXS4_odsi0';
$json_google = curl_init($url);
curl_setopt($json_google, CURLOPT_RETURNTRANSFER, true);
$json_response = curl_exec($json_google);
$result = json_decode($json_response);
if(isset($result->results) && count($result->results))
{
$geocode = $result->results[0];
// pego os dados do endereço
$geo_address_number = null;
$geo_address_log = null;
$geo_address_zipcode = null;
$geo_address_state = null;
$geo_address_city = null;
$geo_address_neighborhood = null;
$arr_address = $geocode->address_components;
foreach($arr_address as $address)
{
if(in_array('street_number', $address->types))
{
if(intval($address->long_name) == $address->long_name)
{
$geo_address_number = intval($address->long_name);
}
}
if(in_array('postal_code', $address->types))
{
$geo_address_zipcode = preg_replace('/\D/', '', $address->long_name);
}
if(in_array('administrative_area_level_1', $address->types))
{
$geo_address_state = $address->short_name;
}
if(in_array('administrative_area_level_2', $address->types))
{
$geo_address_city = $address->long_name;
}
if(in_array('sublocality_level_1', $address->types))
{
$geo_address_neighborhood = $address->long_name;
}
if(in_array('route', $address->types))
{
$geo_address_log = $address->long_name;
}
}
if($geo_address_zipcode != $address_cep)
{
$obs_info .= 'DIVERGÊNCIA DE CEP | Crawler: '.$address_cep.' | GOOGLE MAPS: '.$geo_address_zipcode.'<br/>';
}
$geocode_lat = $geocode->geometry->location->lat;
$geocode_lng = $geocode->geometry->location->lng;
$arr_enterprise['latitude'] = $geocode_lat;
$arr_enterprise['longitude'] = $geocode_lng;
/*
* Pego os Empreendimentos cadastrados no Google Maps perto do local
*/
$search_nearby = true;
foreach ($arr_google_nearby as $gnb)
{
$dist = $this->getDistanceBetweenPoints($geocode_lat, $geocode_lng, $gnb->latitude, $gnb->longitude);
$dist = $dist['meters'];
if($dist <= 250)
{
$search_nearby = false;
// echo "######################### | NEAR BY JÁ EXECUTADO | RAIO: ".$dist." metros.\n";
break;
}
}
if($search_nearby == true)
{
$place_details = $this->googlePlaces($address_encoded_query,
$address_number,
$address_logradouro,
$address_bairro,
$address_encoded,
$listings, $modelEnterprises);
}
}
else
{
// Registro a pesquisa na API NEARBY do Google
$google_nearby = ORM::for_table('module_imobles_google_nearby')->create();
$google_nearby->address_encoded = $address_encoded;
$google_nearby->save();
}
}
/*
* Realizo o cadastro do empreendimento
*/
if(isset($place_details->arr_address_gp))
{
// Trato os dados do endereço
$address_number = $place_details->arr_address_gp['address_number'];
$address_logradouro = $place_details->arr_address_gp['address_log'];
$address_bairro = $place_details->arr_address_gp['address_neighborhood'];
$address_cep = $place_details->arr_address_gp['address_zipcode'];
$arr_enterprise['latitude'] = $place_details->geometry->location->lat;
$arr_enterprise['longitude'] = $place_details->geometry->location->lng;
$arr_enterprise['link_google'] = $place_details->url;
$arr_enterprise['google_geometry'] = json_encode($place_details->geometry);
$arr_enterprise['google_phone'] = isset($place_details->formatted_phone_number)?$place_details->formatted_phone_number:null;
$arr_enterprise['google_place_id'] = $place_details->place_id;
$arr_enterprise['google_plus_code'] = json_encode($place_details->plus_code);
$arr_enterprise['google_rating'] = isset($place_details->rating)?$place_details->rating:null;
$arr_enterprise['google_reference'] = $place_details->reference;
$arr_enterprise['google_reviews'] = isset($place_details->reviews)?json_encode($place_details->reviews):null;
$arr_enterprise['google_user_ratings_total'] = isset($place_details->user_ratings_total)?$place_details->user_ratings_total:null;
$arr_enterprise['google_json'] = json_encode($place_details);
$arr_enterprise['name'] = $place_details->name;
}
else
{
$arr_enterprise['name'] = $result_listing->portal.' | '.$result_listing->id;
}
// Endereço
$arr_enterprise['address_log'] = $address_logradouro;
$arr_enterprise['address_log_sanitized'] = $this->sanitizaLogradouro($address_logradouro);
$arr_enterprise['address_neighborhood'] = $this->sanitizaLogradouro($address_bairro);
$arr_enterprise['address_number'] = $address_number;
$arr_enterprise['address_neightborhood'] = $address_bairro;
$arr_enterprise['address_neighborhood_sanitized'] = $this->sanitizaLogradouro($address_bairro);
$arr_enterprise['address_zip'] = $address_cep;
$arr_enterprise['address_complement'] = isset($result_listing->address->complement)?$result_listing->address->complement:null;
$arr_enterprise['crawler_poisList'] = isset($result_listing->address->poisList)?json_encode($result_listing->address->poisList):null;
// Populo o array do empreendimento
$arr_enterprise['alias'] = $arr_enterprise['name'];
$arr_enterprise['enable'] = 0;
$arr_enterprise['videoTourLink'] = $result_listing->videoTourLink;
$arr_enterprise['unitTypes'] = $result_listing->unitTypes[0];
$arr_enterprise['comparator_status'] = "Backlog";
$arr_enterprise['crawler_type'] = 'vivareal';
$arr_enterprise['crawler_listing_id'] = $result_listing->id;
$arr_enterprise['crawler_listing_link'] = $result_link->href;
$arr_enterprise['crawler_portal'] = $result_listing->portal;
$arr_enterprise['created_by'] = 0;
$arr_enterprise['crawler_type_id'] = 1;
// Pego o ID do Estado e Cidade
$arr_enterprise['address_state_id'] = $address_state_id;
$arr_enterprise['address_city_id'] = $address_city_id;
// Verifico a data da entrega
$arr_enterprise['release_date'] = (isset($result_listing->deliveredAt)) ? substr($result_listing->deliveredAt, 0, 10) : '';
// Verifico se o Status do Empreendimento
$arr_enterprise['release_status'] = null;
if($result_listing->listingType == 'DEVELOPMENT')
{
switch($result_listing->constructionStatus)
{
case "PLAN_ONLY": $arr_enterprise['release_status'] = "Launch";
break;
case "UNDER_CONSTRUCTION": $arr_enterprise['release_status'] = "In Works";
break;
case "BUILT": $arr_enterprise['release_status'] = "Ready to move in";
break;
default: $arr_enterprise['release_status'] = null;
break;
}
}
else
{
if($arr_enterprise['release_date'])
{
if($arr_enterprise['release_date'] > date('Y-m-d'))
{
$arr_enterprise['release_status'] = "In Works";
}
else
{
$arr_enterprise['release_status'] = "Ready to move in";
}
}
}
// Pego o Link do Google para o empreendimento
if(isset($arr_enterprise['latitude']) && isset($arr_enterprise['longitude']) && !isset($arr_enterprise['link_google']))
{
$arr_enterprise['link_google'] = 'http://maps.google.com/maps?q='.$arr_enterprise['latitude'].','.$arr_enterprise['longitude'];
}
// Verifico se aceita permuta
if(isset($result_listing->acceptExchange))
{
$data['permute'] = $result_listing->acceptExchange == false?'No':'Yes';
}
else
{
$arr_enterprise['permute'] = 'Uninformed';
}
// Pego o Padrão do Empreendimento
if(isset($result_listing->pricingInfos[0]->businessType) && $result_listing->pricingInfos[0]->businessType == 'SALE' && isset($result_listing->pricingInfos[0]->price))
{
if($result_listing->pricingInfos[0]->price >= 1500000)
{
$arr_enterprise['module_imobles_enterprise_standard_id'] = 3;
}
elseif($result_listing->pricingInfos[0]->price < 1500000 && $result_listing->pricingInfos[0]->price >= 800000)
{
$arr_enterprise['module_imobles_enterprise_standard_id'] = 1;
}
elseif($result_listing->pricingInfos[0]->price < 800000 && $result_listing->pricingInfos[0]->price >= 300000)
{
$arr_enterprise['module_imobles_enterprise_standard_id'] = 2;
}
elseif($result_listing->pricingInfos[0]->price < 300000 && $result_listing->pricingInfos[0]->price >= 200000)
{
$arr_enterprise['module_imobles_enterprise_standard_id'] = 4;
}
elseif($result_listing->pricingInfos[0]->price < 200000)
{
$arr_enterprise['module_imobles_enterprise_standard_id'] = 5;
}
}
$arr_enterprise['obs'] = $obs_info;
// Salvo o empreendimento
$save = $modelEnterprises->createEnterprises($arr_enterprise);
if(is_numeric($save->id))
{
// echo "NOVO Empreendimento Cadastrado com Sucesso | ".$arr_enterprise['name'].".\n";
$enterprise_id = $save->id;
}
else
{
echo "OCORREU UM ERRO AO SALVAR O EMPREENDIMENTO";
var_dump($arr_enterprise);
exit;
}
// Cadastro as Torres
if(isset($result_listing->buildings) && $result_listing->buildings >= 1)
{
$towers = $result_listing->buildings;
}
else
{
$towers = 1;
}
$unit_tower_id = null;
for ($i = 0; $i < $towers; $i++)
{
$torre = $i + 1;
$tower = ORM::for_table('module_imobles_enterprise_towers')->create();
$tower->title = 'Torre '.$torre;
$tower->floors = isset($result_listing->floors[0])?$result_listing->floors[0]:null;
$tower->alias = 'torre_'.$torre;
$tower->stage =$arr_enterprise['release_status'];
$tower->module_imobles_enterprise_id = $enterprise_id;
$tower->unitsOnTheFloor = isset($result_listing->unitsOnTheFloor)?$result_listing->unitsOnTheFloor:null;
$tower->created_at = date('Y-m-d H:i:s');
$tower->updated_at = date('Y-m-d H:i:s');
$tower->save();
if($i == 0)
{
$unit_tower_id = $tower->id;
}
}
}
else
{
// Pego a Torre para cadastrar a unidade
$tower = ORM::for_table('module_imobles_enterprise_towers')->where('module_imobles_enterprise_id', $enterprise_id)->find_one();
if(isset($tower->id))
{
$unit_tower_id = $tower->id;
}
else
{
// Cadastro as Torres
$torre_place = 1;
$tower_place = ORM::for_table('module_imobles_enterprise_towers')->create();
$tower_place->title = 'Torre '.$torre_place;
$tower_place->alias = 'torre_'.$torre_place;
$tower_place->stage = 'Ready to move in';
$tower_place->module_imobles_enterprise_id = $enterprise_id;
$tower_place->created_at = date('Y-m-d H:i:s');
$tower_place->save();
$unit_tower_id = $tower_place->id;
}
}
/*
* FAÇO O CADASTRO DAS AMINITIES
*/
if($listing_id === null)
{
$arr_listing_amenities = $result_listing->amenities;
// Pego as Amenities do Empreendimento
$arr_enterprise_amenities = ORM::for_table('module_imobles_enterprise_entreprise_amenities')->where('module_imobles_enterprise_id', $enterprise_id)->find_many();
$amenitiModel = new Enterprise_amenitiesModel();
foreach ($arr_listing_amenities as $area)
{
if (!empty(trim($area))) {
$c = $amenitiModel->getOneCollum('alias', mb_strtoupper(trim($area)));
if ($c) {
$insert_amenitie = true;
foreach ($arr_enterprise_amenities as $i)
{
if($i->module_imobles_enterprise_amenities_id == $c->id)
{
$insert_amenitie = false;
}
}
if($insert_amenitie == true)
{
$a = ORM::for_table("module_imobles_enterprise_entreprise_amenities")->create();
$a->module_imobles_enterprise_id = $enterprise_id;
$a->module_imobles_enterprise_amenities_id = $c->id;
$a->save();
// echo "######## AMENITIE DO EMPREENDIMENTO CADASTRADA COM SUCESSO | ".mb_strtoupper(trim($area))."\n";
}
}
}
}
}
/*
* Verifico se está revisando um anúncio já cadastrado
*/
$now = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
$unit_unique = false;
$unit_type_unique = false;
$enterprise_unique = false;
if($listing_id)
{
$deleted_unit_type = false;
// Pego os dados do anúncio
$listing_aux = ORM::for_table("module_imobles_listings")->find_one($listing_id);
// Verifico se a Unidade está vinculada somente ao anúncio
$unit_unique = false;
$unit_type_unique = false;
$enterprise_unique = false;
$count_aux = ORM::for_table('module_imobles_listings')
->where("unit_id", $listing_aux->unit_id)
->count('id');
$enterprise_old = ORM::for_table('module_imobles_enterprise')
->find_one($listing_aux->entreprise_id);
if($count_aux <= 1)
{
$unit_unique = true;
$unit_old = ORM::for_table('module_imobles_enterprise_units')
->find_one($listing_aux->unit_id);
$unit_old->delete_at = $now->format('Y-m-d H:i:s');
$unit_old->delete_by = 0;
$unit_old->save();
// Verifico se o Tipo Unidade está vinculada somente ao anúncio
$count_aux = ORM::for_table('module_imobles_listings')
->where("unit_type_id", $listing_aux->unit_type_id)
->count('id');
if($count_aux <= 1)
{
$unit_unique = true;
$unit_type_old = ORM::for_table('module_imobles_enterprise_units_type')
->find_one($listing_aux->unit_type_id);
// Verifico se o Empreendimento está vinculado somente ao anúncio
$count_aux = ORM::for_table('module_imobles_listings')
->where("entreprise_id", $listing_aux->entreprise_id)
->count('id');
if($count_aux <= 1)
{
$enterprise_unique = true;
if($enterprise_old->google_place_id == null && $enterprise_old->crawler_enterprise_id == null && $enterprise_old->verified != 1)
{
$enterprise_old->delete_at = $now->format('Y-m-d H:i:s');
$enterprise_old->delete_by = 0;
$enterprise_old->save();
//Deleto a torre
$tower_old = ORM::for_table('module_imobles_enterprise_towers')
->where('module_imobles_enterprise_id', $enterprise_old->id)
->find_one();
$tower_old->deleted_at = $now->format('Y-m-d H:i:s');
$tower_old->deleted_by = 0;
$tower_old->save();
}
}
}
}
}
/*
* Verifico se o tipo de unidade já está cadastrado
*/
$arr_unit_type = array();
$arr_unit_type_id = array();
$unit_type_IsNew = true;
$count_planta = 0;
// pego os tipos de áreas úteis do anúncio
if(isset($result_listing->usableAreas) && count($result_listing->usableAreas) >= 1)
{
foreach ($result_listing->usableAreas as $planta)
{
$unit_type_aux = null;
$unit_type_id_aux = null;
$num_garagens = isset($result_listing->parkingSpaces[$count_planta])?$result_listing->parkingSpaces[$count_planta]:isset($result_listing->parkingSpaces[0])?$result_listing->parkingSpaces[0]:null;
$num_suites = isset($result_listing->suites[$count_planta])?$result_listing->suites[$count_planta]:isset($result_listing->suites[0])?$result_listing->suites[0]:null;
$num_banheiros = isset($result_listing->bathrooms[$count_planta])?$result_listing->bathrooms[$count_planta]:isset($result_listing->bathrooms[0])?$result_listing->bathrooms[0]:null;
$num_quartos = isset($result_listing->bedrooms[$count_planta])?$result_listing->bedrooms[$count_planta]:isset($result_listing->bedrooms[0])?$result_listing->bedrooms[0]:null;
if($isNewEnterprise == false)
{
$unit_type_aux = ORM::for_table('module_imobles_enterprise_units_type')
->where('number_rooms', $num_quartos)
->where('number_garage', $num_garagens)
->where('number_suite', $num_suites)
->where('module_imobles_enterprise_id', $enterprise_id)
->find_one();
}
if(isset($unit_type_aux->id) && $unit_type_aux->id > 0)
{
$isNew = false;
$arr_unit_type_id[] = $unit_type_aux->id;
$unit_type_id_aux = $unit_type_aux->id;
// Verifico se tem que excluir o tipo de unidade
if($unit_type_unique === true && $deleted_unit_type == false)
{
$unit_type_old->delete_at = $now->format('Y-m-d H:i:s');
$unit_type_old->save();
$deleted_unit_type = true;
}
}
else
{
// Se estiver revisando um anúncio, aponto o Tipo de Unidade para o novo Empreendimento
$insert_unit = true;
if(isset($listing_aux->id))
{
if($unit_type_unique === true && $deleted_unit_type == false)
{
$unit_type_old->module_imobles_enterprise_id = $enterprise_id;
$unit_type_old->save();
$deleted_unit_type = true;
$insert_unit = false;
}
}
if($insert_unit == true)
{
$arr_unit_type['title'] = $planta.'m² | '.$num_quartos.' Quartos'
.($num_suites > 0?' | '.$num_suites.' Suites':'')
.($num_banheiros > 0?' | '.$num_banheiros.' Banheiros':'')
.($num_garagens > 0?' | '.$num_garagens.' Garagens':'');
$arr_unit_type['desc'] = $arr_unit_type['title'];
$arr_unit_type['alias'] = $arr_unit_type['title'];
$arr_unit_type['area'] = $planta;
$arr_unit_type['number_rooms'] = $num_quartos;
$arr_unit_type['number_suite'] = $num_suites;
$arr_unit_type['number_garage'] = $num_garagens;
$arr_unit_type['number_bathroom'] = $num_banheiros;
$arr_unit_type['module_imobles_enterprise_id'] = $enterprise_id;
$save = $modelUnitType->createTypeunity($arr_unit_type);
if(is_numeric($save->id))
{
// echo "Tipo de Unidade Cadastrado com sucesso.\n";
$arr_unit_type_id[] = $save->id;
$unit_type_id_aux = $save->id;
}
else
{
echo "OCORREU UM ERRO AO SALVAR O TIPO DE UNIDADE";
return($arr_enterprise);
exit;
}
}
}
// Pego as Amenities do Tipo de Unidade
if($unit_type_id_aux && $listing_id == null)
{
$arr_unit_type_amenities = ORM::for_table('module_imobles_enterprise_units_type_amenities')->where('module_imobles_enterprise_units_type_id', $unit_type_id_aux)->find_many();
foreach ($arr_listing_amenities as $area)
{
if (!empty(trim($area))) {
$c = ORM::for_table('module_imobles_type_units_amenities')->where('alias', trim(mb_strtoupper($area)))->find_one();
if ($c)
{
$insert_amenitie = true;
foreach ($arr_unit_type_amenities as $i)
{
if($i->module_imobles_type_units_amenities_id == $c->id)
{
$insert_amenitie = false;
}
}
if($insert_amenitie == true)
{
$a = ORM::for_table("module_imobles_enterprise_units_type_amenities")->create();
$a->module_imobles_enterprise_units_type_id = $unit_type_id_aux;
$a->module_imobles_type_units_amenities_id = $c->id;
$a->save();
// echo "######## AMENITIE DO TIPO DE UNIDADE CADASTRADA COM SUCESSO | ".mb_strtoupper(trim($area))."\n";
}
}
}
}
}
$count_planta++;
}
}
/*
* Faço o cadastro d UNIDADE
* Crio uma unidade DUMMY pois não temos o número do apartamento
*/
$arr_unit = array();
$arr_unit_id = array();
$count_units = 0;
foreach ($arr_unit_type_id as $unit_type_id)
{
$unit_IsNew = true;
$unit_id_aux = null;
// Verifico se o Complemento informa o número da unidade
$unidade = null;
$complemento = $result_listing->address->complement;
$complemento = $this->cleanString(strtolower($complemento));
$pattern1 = '(unidade\.?|uni\.?|un\.?|apartamento\.?|apto\.?|ap\.?|apt\.?|apat\.?)+\s*';
$pattern2 = '[0-9]+';
preg_match('/' . $pattern1 . $pattern2 . '/', $complemento, $matches, PREG_OFFSET_CAPTURE);
if (isset($matches[0][0])) {
$unidade = $matches[0][0];
$unidade = preg_split('/' . $pattern1 . '/', $unidade);
$unidade = $unidade[1];
}
// verifico se o anúncio tem similaridade com algum outro.
if(isset($listing_similaridade['count_imgs']) && $listing_similaridade['count_imgs'])
{
if($listing_similaridade['count_imgs'] == count($result_medias))
{
$arr_unit_id[] = $listing_similaridade['unit_id'];
$unit_IsNew = false;
$unit_id_aux = $listing_similaridade['unit_id'];
}
}
if($unit_IsNew == true)
{
$now = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
$unit_aux = ORM::for_table('module_imobles_enterprise_units')->create();
$arr_unit['floor'] = isset($result_listing->unitFloor)?$result_listing->unitFloor:null;
$arr_unit['number_unity'] = $unidade;
$arr_unit['module_imobles_enterprise_towers_id'] = $unit_tower_id;
$arr_unit['module_imobles_enterprise_units_type_id'] = $unit_type_id;
$arr_unit['created_at'] = $now->format('Y-m-d H:i:s');
$arr_unit['created_by'] = 0;
$arr_unit['crawler_type_id'] = 1;
$save = $modelUnit->createEnterprise_unity($arr_unit);
if(is_numeric($save->id))
{
// echo "Unidade Cadastrado com sucesso.\n";
$arr_unit_id[] = $save->id;
$unit_id_aux = $save->id;
}
else
{
// echo "OCORREU UM ERRO AO SALVAR O TIPO DE UNIDADE";
return($arr_enterprise);
exit;
}
}
// Pego as Amenities da Unidade
if($unit_id_aux && $listing_id == null)
{
$arr_unit_amenities = ORM::for_table('module_imobles_enterprise_units_amenities')->where('module_imobles_enterprise_units_id', $unit_id_aux)->find_many();
foreach ($arr_listing_amenities as $area)
{
if (!empty(trim($area))) {
$c = ORM::for_table('module_imobles_units_amenities')->where('alias', trim(mb_strtoupper($area)))->find_one();
if ($c)
{
$insert_amenitie = true;
foreach ($arr_unit_amenities as $i)
{
if($i->module_imobles_units_amenities_id == $c->id)
{
$insert_amenitie = false;
}
}
if($insert_amenitie == true)
{
$a = ORM::for_table("module_imobles_enterprise_units_amenities")->create();
$a->module_imobles_enterprise_units_id = $unit_id_aux;
$a->module_imobles_units_amenities_id = $c->id;
$a->save();
// echo "######## AMENITIE DA UNIDADE CADASTRADA COM SUCESSO | ".mb_strtoupper(trim($area))."\n";
}
}
}
}
}
$count_units++;
}
/*
* Verifico se o anunciannte já está cadastrado
*/
if($listing_id == null)
{
$advertiser_aux = ORM::for_table('module_imobles_advertisers')
->where('crawler_advertiser_id', $result_listing->advertiserId)
->where('crawler_type', 'vivareal')
->where('crawler_portal', $result_listing->portal)
->find_one();
if(isset($advertiser_aux->id) && $advertiser_aux->id > 0)
{
$advertiser_id = $advertiser_aux->id;
}
else
{
$now = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
// $user = User::_info();
$advertiser_aux = ORM::for_table('module_imobles_advertisers')->create();
$advertiser_aux->name = $result_account->name;
$advertiser_aux->phones = isset($result_account->phones)?json_encode($result_account->phones):null;
$advertiser_aux->logoUrl = isset($result_account->logoUrl)?$result_account->logoUrl:null;
$advertiser_aux->licenseNumber = $result_account->licenseNumber;
$advertiser_aux->websiteUrl = isset($result_account->websiteUrl)?$result_account->websiteUrl:null;
$advertiser_aux->crawler_type = 'vivareal';
$advertiser_aux->crawler_createdDate = $result_account->createdDate;
$advertiser_aux->crawler_accountLink = $result_accountLink->href;
$advertiser_aux->crawler_advertiser_id = $result_account->id;
$advertiser_aux->crawler_listing_id = $result_listing->id;
$advertiser_aux->crawler_listing_link = $result_link->href;
$advertiser_aux->crawler_portal = $result_listing->portal;
$advertiser_aux->created_at = $now->format('Y-m-d H:i:s');
$advertiser_aux->created_by = 0;
$save = $advertiser_aux->save();
if($save)
{
// echo "Anunciante Cadastrado com sucesso.\n";
$advertiser_id = $advertiser_aux->id;
}
else
{
echo "OCORREU UM ERRO AO SALVAR O ANUNCIANTE";
return($arr_enterprise);
exit;
}
}
}
/*
* Verifico se o anúncio já está cadastrado
*/
if($listing_id == null)
{
$listing_aux = ORM::for_table('module_imobles_listings')
->where('crawler_listing_id', $result_listing->id)
->where('crawler_type', 'vivareal')
->where('crawler_portal', $result_listing->portal)
->find_one();
if(isset($listing_aux->id) && $listing_aux->id > 0)
{
$listing_id = $listing_aux->id;
}
else
{
$now = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
// $user = User::_info();
$listing_aux = ORM::for_table('module_imobles_listings')->create();
$listing_aux->entreprise_id = $enterprise_id;
$listing_aux->unit_type_id = isset($arr_unit_type_id[0])?$arr_unit_type_id[0]:null;
$listing_aux->unit_id = isset($arr_unit_id[0])?$arr_unit_id[0]:null;
$listing_aux->advertiser_id = $advertiser_id;
$listing_aux->listingType = $result_listing->listingType;
$listing_aux->description = $result_listing->description;
$listing_aux->title = $result_listing->title;
$listing_aux->crawler_type = 'vivareal';
$listing_aux->crawler_contractType = $result_listing->contractType;
$listing_aux->crawler_createdAt = $result_listing->createdAt;
$listing_aux->crawler_updatedAt = $result_listing->updatedAt;
$listing_aux->crawler_publicationType = $result_listing->publicationType;
$listing_aux->crawler_externalId = $result_listing->externalId;
$listing_aux->crawler_stamps = json_encode($result_listing->stamps);
$listing_aux->crawler_pricingInfos = json_encode($result_listing->pricingInfos);
$listing_aux->crawler_businessType = $result_listing->pricingInfos[0]->businessType;
$listing_aux->crawler_price = isset($result_listing->pricingInfos[0]->price)?$result_listing->pricingInfos[0]->price:null;
$listing_aux->crawler_status = $result_listing->status;
$listing_aux->crawler_whatsappNumber = $result_listing->whatsappNumber;
$listing_aux->crawler_listing_id = $result_listing->id;
$listing_aux->crawler_listing_link = $result_link->href;
$listing_aux->crawler_portal = $result_listing->portal;
$listing_aux->created_at = $now->format('Y-m-d H:i:s');
$listing_aux->crawler_json = json_encode($listings);
$listing_aux->merge_type = isset($listing_similaridade['merge_type'])?$listing_similaridade['merge_type']:null;
$listing_aux->created_by = 0;
$save = $listing_aux->save();
if($save)
{
// echo "ANÚNCIO Cadastrado com sucesso.\n";
$listing_id = $listing_aux->id;
//persist pricing obj
$price = $listing_aux->crawler_price;
$yearlyIptu = @$result_listing->pricingInfos[0]->yearlyIptu;
$monthlyCondoFee = @$result_listing->pricingInfos[0]->monthlyCondoFee;
$listing_id = $listing_aux->id;
$unit_type_id = $listing_aux->unit_type_id;
$rental = $listing_aux->crawler_businessType == "RENTAL" ? 1 : null;
$this->persistPricing($price, $yearlyIptu, $monthlyCondoFee, $listing_id, $unit_type_id, $rental);
}
else
{
echo "OCORREU UM ERRO AO SALVAR O ANÚNCIO";
return($arr_enterprise);
exit;
}
}
}
else
{
$listing_aux->entreprise_id = $enterprise_id;
$listing_aux->unit_type_id = isset($arr_unit_type_id[0])?$arr_unit_type_id[0]:null;
$listing_aux->unit_id = isset($arr_unit_id[0])?$arr_unit_id[0]:null;
$listing_aux->updated_at = $now->format('Y-m-d H:i:s');
$listing_aux->merge_type = isset($listing_similaridade['merge_type'])?$listing_similaridade['merge_type']:null;
$save = $listing_aux->save();
if($save)
{
// echo "ANÚNCIO Cadastrado com sucesso.\n";
$listing_id = $listing_aux->id;
}
else
{
echo "OCORREU UM ERRO AO SALVAR O ANÚNCIO";
return($arr_enterprise);
exit;
}
}
// Registro o has_listing do empreendimento
$enterprise_aux = ORM::for_table("module_imobles_enterprise")->find_one($enterprise_id);
$enterprise_aux->has_listing = 1;
$enterprise_aux->save();
/*
* TODO Faço o cadastro das imagens do anúncio
*/
if($listing_review === false)
{
if(!empty($listing_arr_images))
{
foreach ($listing_arr_images as $image)
{
$image_aux = $image['image'];
$ext = strtolower($image_aux->getimageformat());
$image_aux->setImageFormat ($ext);
if($ext == 'jpeg')
{
$ext = 'jpg';
}
$dir = 'application/plugins/module_imobles/uploads/enterprise/' . $enterprise_id . '/images';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$name_aux = $listing_id."_".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999);
$name = $name_aux.".".$ext;
file_put_contents ($dir."/".$name, $image_aux);
$d = ORM::for_table('module_imobles_enterprise_imgs')->create();
$d->src = $name;
// $d->name = $name;
$d->module_imobles_enterprise_id = $enterprise_id;
$d->listing_id = $listing_id;
$d->type = 'listing';
$d->created_at = date('Y-m-d H:i:s');
$d->created_by = 0;
$d->duplicated = $image['duplicated'];
$d->save();
// Crio a versão webp da imagem
if($ext != 'png')
{
$jpg=imagecreatefromjpeg($enterprise_dir."/".$name);
$w=imagesx($jpg);
$h=imagesy($jpg);
$webp=imagecreatetruecolor($w,$h);
imagecopy($webp,$jpg,0,0,0,0,$w,$h);
imagewebp($webp, $enterprise_dir.'/'.$name_aux.".webp", 80);
imagedestroy($jpg);
imagedestroy($webp);
}
}
}
else
{
foreach ($result_medias as $medias)
{
if($medias->type == 'IMAGE')
{
$url = $medias->url;
$url = str_replace('{width}', '870', $url);
$url = str_replace('{height}', '653', $url);
$url = str_replace('{action}', 'fit-in', $url);
if(is_file($url))
{
try
{
//TODO: imagick não funciona no ambiente local do LEONARDO LOPES
// $image = new imagick($url);
// $ext = strtolower($image->getimageformat());
// $image->setImageFormat ($ext);
$image = file_get_contents($url);
$ext = substr($url, strlen($url)-3);
if($ext != 'png')
{
$ext = 'jpg';
}
$dir = 'application/plugins/module_imobles/uploads/enterprise/' . $enterprise_id . '/images';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$name_aux = $listing_id."_".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999);
$name = $name_aux.".".$ext;
file_put_contents ($dir."/".$name, $image);
$d = ORM::for_table('module_imobles_enterprise_imgs')->create();
$d->src = $name;
$d->name = $url;
$d->module_imobles_enterprise_id = $enterprise_id;
$d->listing_id = $listing_id;
$d->type = 'listing';
$d->created_at = date('Y-m-d H:i:s');
$d->created_by = 0;
$d->save();
// Crio a versão webp da imagem
if($ext != 'png')
{
$jpg=imagecreatefromjpeg($enterprise_dir."/".$name);
$w=imagesx($jpg);
$h=imagesy($jpg);
$webp=imagecreatetruecolor($w,$h);
imagecopy($webp,$jpg,0,0,0,0,$w,$h);
imagewebp($webp, $enterprise_dir.'/'.$name_aux.".webp", 80);
imagedestroy($jpg);
imagedestroy($webp);
}
// echo $dir."/".$name."\n";
}
catch (Exception $ex)
{
// echo $ex->getMessage()."\n";
}
}
}
}
}
}
else
{
$imgs = ORM::for_table('module_imobles_enterprise_imgs')
->where('listing_id',$listing_id)
->find_many();
foreach($imgs as $d)
{
$origem = 'application/plugins/module_imobles/uploads/enterprise/' . $d->module_imobles_enterprise_id . '/images/'.$d->src;
if(!is_file($origem))
{
$d->module_imobles_enterprise_id = $enterprise_id;
$d->type = 'listing';
$d->delete_at = date('Y-m-d H:i:s');
$d->save();
}
elseif($d->module_imobles_enterprise_id != $enterprise_id)
{
$dir = 'application/plugins/module_imobles/uploads/enterprise/' . $enterprise_id . '/images';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
$destino = $dir. '/'.$d->src;
rename($origem, $destino);
$d->module_imobles_enterprise_id = $enterprise_id;
$d->type = 'listing';
$d->updated_at = date('Y-m-d H:i:s');
$d->updated_by = 0;
$d->save();
// Movo a versão webp da imagem
if(is_file($destino))
{
}
}
}
}
// echo "FIM DO CADASTRO DO ANÚNCIO\n##########################\n\n";
// exit;
if($listing_review == true)
{
$return = array("enterprise_new" => $compare_resut['enterprise'],
"match_type" => $compare_resut['similaridade']['type']);
return $return;
}
else
{
return $listing_id;
}
}
/*
* Função para comparar empreendimentos
*/
public function compareEnterprise(
$str_compare,
$address_state_id,
$address_city_id,
$address_cep = null,
$address_bairro = null,
$address_logradouro = null,
$address_number = null,
$listing_compare = null,
$listing_enterprise_id = null)
{
// Compara a string com as Empreendimentos já cadastrados
$enterprises = ORM::for_table('module_imobles_enterprise')
->select_many('id','name','alternative_names','verified','google_place_id','crawler_enterprise_id','address_log','address_number','address_neightborhood', 'address_log_sanitized', 'address_neighborhood_sanitized')
->where('address_city_id', $address_city_id)
->where('address_state_id', $address_state_id)
->where_null('delete_at');
if($address_bairro)
{
$enterprises->where('address_neighborhood_sanitized', $this->sanitizaLogradouro(trim($address_bairro)));
}
else
{
return false;
}
if($address_logradouro)
{
$enterprises->where('address_log_sanitized', $this->sanitizaLogradouro($address_logradouro));
}
else
{
// return false;
}
// Quebro a String de camparação
$arr_str_compare = explode(' @@@ ', $str_compare);
$str_compare_description = trim($arr_str_compare[0]);
$str_compare_title = trim($arr_str_compare[1]);
$arr_imgs_compare = array();
$arr_dummys = array();
$enterprises->order_by_asc('id');
$enterprises_aux = $enterprises->find_many();
// if($address_logradouro === null)
// {
// var_dump(count($enterprises_aux));
// foreach ($enterprises_aux as $enterprise)
// {
// var_dump($enterprise->address_log);
// var_dump($enterprise->name);
// var_dump($enterprise->alternative_names);
// }
// exit;
// }
if(count($enterprises_aux))
{
foreach ($enterprises_aux as $enterprise)
{
$dummy = true;
// TODO: usado para TESTES no crawler. Retirar no futuro.
if($enterprise->id != 91)
{
// continue;
}
// Verifico se o nome do empreendimento bate com o json do anúncio
if($enterprise->verified || $enterprise->google_place_id || $enterprise->crawler_enterprise_id)
{
$dummy = false;
if($enterprise->name)
{
// Monto o array de nomes do Empreendimento
$arr_names = array();
if($enterprise->alternative_names)
{
$arr_names = explode(';', $enterprise->alternative_names);
}
$arr_names[] = $enterprise->name;
$arr_exclude = array();
foreach ($arr_names as $name_aux)
{
$name = $this->cleanString(trim($name_aux));
$name = mb_strtolower($name.' ');
$name = preg_replace('/(residencial|edificio|condominio|'
. 'res\.+|ed\.+|c\.+|cd\.+|cond\.+|con\.+|co\.+|cod\.+|condo\.+|resid\.+|'
. 'Condominium|Residential|Building|Residence|Condominio do|Condominio de|Condominio da)\s+/i', '', $name);
$name = trim($name);
$name = str_replace('/', ' ', $name);
// Verifico se o nome do empreendimento é similar ao bairro
$arr_name_test = explode(' ', $name);
$arr_exclude_aux = ORM::for_table('module_imobles_crawler_forbidden_terms')->select('term')->find_many();
foreach ($arr_exclude_aux as $term)
{
$term_aux = $this->cleanString(mb_strtolower(trim($term->term)));
$arr_exclude[] = trim($term_aux);
}
$arr_exclude[] = $this->cleanString(mb_strtolower($address_bairro));
if(in_array($name, $arr_exclude) || strlen($name) < 5 || count($arr_name_test) < 2)
{
$pattern = '/((residencial|residence|edificio|condominio|res\.+|ed\.+|c\.+|'
. 'edf\.+|\.+edi\.+|cd\.+|cond\.+|con\.+|\.+co\.+|cod\.+|\.+condo\.+){1}\s+'
. '('.$name.'){1}|('.$name.'){1}\s+(residencial|residence|edificio|condominio|res\.+|ed\.+|'
. 'cd\.+|cond\.+)\s{1})/i';
}
else
{
$pattern = "/".$name."/i";
}
$str_compare = $this->cleanString(mb_strtolower(strip_tags($str_compare)));
if(empty($pattern) || empty($str_compare))
{
continue;
}
$matches = array();
try
{
preg_match_all($pattern, $str_compare, $matches, PREG_OFFSET_CAPTURE);
}
catch (Exception $ex)
{
echo $ex->getMessage();
}
if(count($matches) && !empty($matches[0]))
{
$similaridade = array(
'merge_type' => 'enterprise_name',
'type' => 'NOME EMPREENDIMENTO',
'arr_imgs' => null,
'count_imgs' => null,
'unit_type_id' => null,
'unit_id' => null
);
$return = array('enterprise' => $enterprise,
'arr_imgs' => $arr_imgs_compare,
'similaridade' => $similaridade);
return $return;
}
}
}
}
else
{
if($listing_enterprise_id)
{
continue;
}
}
// Comparo os Tipos de Unidade do Empreendimento com o Anúncio
if($address_logradouro)
{
$arr_unit_types_enterprise = ORM::for_table('module_imobles_enterprise_units_type')
->where('module_imobles_enterprise_id', $enterprise->id)
->find_many();
foreach ($arr_unit_types_enterprise as $unit_types_obj)
{
$result_listing = $listing_compare->listing;
if(isset($result_listing->usableAreas) && count($result_listing->usableAreas) >= 1)
{
$count_planta = 0;
foreach ($result_listing->usableAreas as $area)
{
$num_garagens = isset($result_listing->parkingSpaces[$count_planta])?$result_listing->parkingSpaces[$count_planta]:isset($result_listing->parkingSpaces[0])?$result_listing->parkingSpaces[0]:null;
$num_suites = isset($result_listing->suites[$count_planta])?$result_listing->suites[$count_planta]:isset($result_listing->suites[0])?$result_listing->suites[0]:null;
$num_banheiros = isset($result_listing->bathrooms[$count_planta])?$result_listing->bathrooms[$count_planta]:isset($result_listing->bathrooms[0])?$result_listing->bathrooms[0]:null;
$num_quartos = isset($result_listing->bedrooms[$count_planta])?$result_listing->bedrooms[$count_planta]:isset($result_listing->bedrooms[0])?$result_listing->bedrooms[0]:null;
if($area <= $unit_types_obj->area + 3 && $area >= $unit_types_obj->area - 3)
{
if($num_quartos == $unit_types_obj->number_rooms)
{
if($num_garagens == $unit_types_obj->number_garage)
{
if($num_suites == $unit_types_obj->number_suite)
{
// echo "MATCH TYPE: PLANTA: ".$enterprise->name."\n";
$similaridade = array(
'merge_type' => 'unit_type',
'type' => 'TIPO DE UNIDADE',
'arr_imgs' => null,
'count_imgs' => null,
'unit_type_id' => $unit_types_obj->id,
'unit_id' => null
);
$return = array('enterprise' => $enterprise,
'arr_imgs' => $arr_imgs_compare,
'similaridade' => $similaridade);
return $return;
}
}
}
}
$count_planta++;
}
}
}
// Verifico se é a mesma rua e número
$address_logradouro_sanit = $this->sanitizaLogradouro($address_logradouro);
$enterprise_address_sanit = $enterprise->address_log_sanitized;
// Pego o bairro sanitizado
$address_bairro_sanit = $this->sanitizaLogradouro($address_bairro);
if(intval($address_number) > 10
&& $address_number == $enterprise->address_number
&& $address_logradouro_sanit == $enterprise_address_sanit
&& $address_bairro_sanit == $enterprise->address_neighborhood_sanitized)
{
$similaridade = array(
'merge_type' => 'adrress',
'type' => 'ENDEREÇO'
);
$return = array('enterprise' => $enterprise,
'arr_imgs' => $arr_imgs_compare,
'similaridade' => $similaridade);
return $return;
}
// Pego todos os anúncios vinculados ao empreendimento
$listings = ORM::for_table('module_imobles_listings')
->where('entreprise_id', $enterprise->id)
->find_many();
if(count($listings))
{
foreach ($listings as $listing)
{
$description = $listing->description;
$title = $listing->title;
// Comparo a descrição
similar_text(mb_strtolower($description), mb_strtolower($str_compare_description), $sim_description);
// Comparo o título
similar_text(mb_strtolower($title), mb_strtolower($str_compare_title), $sim_title);
if(strlen($description) > 500 && $sim_description >= 95)
{
$similaridade = array(
'merge_type' => 'desc',
'type' => 'text',
'title' => $sim_title,
'description' => $sim_description,
'unit_type_id' => $listing->unit_type_id,
'unit_id' => $listing->unit_id
);
$return = array('enterprise' => $enterprise,
'arr_imgs' => $arr_imgs_compare,
'similaridade' => $similaridade);
return $return;
}
//TODO: pulo a comparação por imagem
continue;
// Baixo todas as imagens do anúncio que está sendo cadastrado
if(empty($arr_imgs_compare))
{
foreach ($listing_compare->medias as $media_compare)
{
if($media_compare->type == 'IMAGE')
{
$url = $media_compare->url;
$url = str_replace('{width}', '870', $url);
$url = str_replace('{height}', '653', $url);
$url = str_replace('{action}', 'fit-in', $url);
try
{
$image = new imagick($url);
$arr_imgs_compare[] = array('image' => $image,
'url' => $url,
'duplicated' => 0);
}
catch (Exception $ex)
{
echo $ex->getMessage()."\n";
}
}
}
}
// comparo as imagens do anuncio
$json_listing = json_decode($listing->crawler_json);
$count_imgs = 0;
$arr_imgs = array();
$arr_imgs_aux = ORM::for_table('module_imobles_enterprise_imgs')
->where('listing_id',$listing->id)
->where('duplicated',0)
->find_many();
if(!empty($arr_imgs_aux))
{
foreach ($arr_imgs_aux as $medias)
{
$url = 'application/plugins/module_imobles/uploads/enterprise/' . $enterprise->id . "/images/".$medias->src;
try
{
$image = new imagick($url);
foreach($arr_imgs_compare as $key => $img_compare)
{
$img_match = false;
$result = $image->compareImages($img_compare['image'], Imagick::METRIC_MEANSQUAREERROR);
if($result[1] <= 0.005)
{
$count_imgs++;
$arr_imgs[] = $url;
$img_match = true;
$arr_imgs_compare[$key]['duplicated'] = 1;
}
if($count_imgs >= 2)
{
$similaridade = array(
'merge_type' => 'img',
'type' => 'image',
'arr_imgs' => $arr_imgs,
'count_imgs' => $count_imgs,
'unit_type_id' => $listing->unit_type_id,
'unit_id' => $listing->unit_id
);
$return = array('enterprise' => $enterprise,
'arr_imgs' => $arr_imgs_compare,
'similaridade' => $similaridade);
return $return;
}
}
// echo $json_listing->listing->id." | RESULT: ".$result[1].($img_match?" | MATCH":null)." | ".$url."\n";
}
catch (Exception $ex)
{
echo $ex->getMessage()."\n";
}
}
}
}
}
}
}
}
$return = array('enterprise' => false,
'arr_imgs' => $arr_imgs_compare);
return $return;
}
/**
* cleanString
* Remove todos dos caracteres especiais do texto e os acentos
*
* @param string $texto
* @return string Texto sem caractere especiais
*/
public function cleanString($texto = '')
{
$texto = trim($texto);
$aFind = array('&','á','à','ã','â','é','ê','í','ó','ô','õ','ú','ü',
'ç','Á','À','Ã','Â','É','Ê','Í','Ó','Ô','Õ','Ú','Ü','Ç');
$aSubs = array('e','a','a','a','a','e','e','i','o','o','o','u','u',
'c','A','A','A','A','E','E','I','O','O','O','U','U','C');
$novoTexto = str_replace($aFind, $aSubs, $texto);
$novoTexto = preg_replace("/[^a-zA-Z0-9 @,-.;:\/]/", "", $novoTexto);
return $novoTexto;
}
/*
* Função para sanitizar o Logradouro do anúncio e realizar a comparação com Google Place
*/
public function sanitizaLogradouro($string)
{
$sanit = $this->cleanString(mb_strtolower(trim($string)));
$sanit = preg_replace('/[^a-zA-Z0-9\']/', '', $sanit);
return $sanit;
}
/**
* Calculates the distance between two points, given their
* latitude and longitude, and returns an array of values
* of the most common distance units
*
* @param {coord} $lat1 Latitude of the first point
* @param {coord} $lon1 Longitude of the first point
* @param {coord} $lat2 Latitude of the second point
* @param {coord} $lon2 Longitude of the second point
* @return {array} Array of values in many distance units
*/
function getDistanceBetweenPoints($lat1, $lon1, $lat2, $lon2) {
$theta = $lon1 - $lon2;
$miles = (sin(deg2rad($lat1)) * sin(deg2rad($lat2))) + (cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$feet = $miles * 5280;
$yards = $feet / 3;
$kilometers = $miles * 1.609344;
$meters = $kilometers * 1000;
return compact('miles','feet','yards','kilometers','meters');
}
/*
* Função para consultar a API NEAR BY do Google e procurar empreendimentos
* próximos do local do anúncio
*/
public function googlePlaces($address_encoded_query,
$geo_address_number,
$geo_address_log,
$geo_address_neighborhood,
$geo_address_encoded,
$listings, $modelEnterprises)
{
// Inicio as variáveis de controle
$continue = true;
$page_token = null;
$count = 0;
$arr_return = array();
$arr_results = array();
$count_repetidos = 0;
$geocode_lat = null;
$geocode_lng = null;
while($continue === true)
{
// $url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
// . 'location='.$geocode_lat.','.$geocode_lng
// . '&keyword=tower|premier|home|garden|living|privilege|condomínio|edifício|residencial|'
// . 'Complexo+de+Condomínio|'
// . 'Edifício+de+Apartamentos'
// . '&key=AIzaSyC0vUVt5Cy1kR1mP0BmRf94EBXS4_odsi0'
// . '&pagetoken='.$page_token
// . '&rankby=distance';
// $address_encoded_query = $this->cleanString($address_encoded_query);
$address_encoded_query = urlencode($address_encoded_query);
$url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"
. "query=Residencial|Edificio|Condominio|"
. $address_encoded_query
. "&key=AIzaSyC0vUVt5Cy1kR1mP0BmRf94EBXS4_odsi0"
. "&type=establishment"
. "&pagetoken=".$page_token;
$json_google = curl_init($url);
curl_setopt($json_google, CURLOPT_RETURNTRANSFER, true);
$json_response = curl_exec($json_google);
$result = json_decode($json_response);
if(!isset($result->results))
{
var_dump($result);
echo '%%%%%%%%%%%%%%%%% ERRO %%%%%%%%%%%%%%\n\n\n';
exit;
}
else
{
// Verifico a quantidade de anúncios para encerrar a paginação
$count_results = count($result->results);
$arr_results = array_merge($arr_results, $result->results);
if($count_results < 20 || $count_repetidos >= 5)
{
$continue = false;
}
if(isset($result->next_page_token))
{
$page_token = $result->next_page_token;
}
else
{
$continue = false;
}
foreach ($result->results as $empreendimentos)
{
$count++;
$arr_teste = ['lawyer','beauty_salon', 'night_club', 'general_contractor',
'shopping_mall','dentist', 'health', 'store',
'place_of_worship', 'church', 'school', 'home_goods_store', 'florist', 'accounting',
'finance', 'gym', 'clothing_store', 'park', 'travel_agency', 'car_repair',
'hospital', 'doctor', 'route', 'street_address',
'meal_takeaway', 'restaurant', 'food', 'insurance_agency', 'electrician',
'bar', 'sublocality_level_1', 'sublocality', 'political',
'premise', 'pharmacy', 'drugstore', 'university', 'laundry', 'supermarket', 'grocery_or_supermarket', 'liquor_store', 'pet_store', 'veterinary_care'];
$exclude_type = false;
foreach ($empreendimentos->types as $type)
{
if(in_array($type, $arr_teste))
{
$exclude_type = true;
continue;
}
}
if($exclude_type === true)
{
continue;
}
if(empty($geocode_lat) || empty($geocode_lng))
{
$geocode_lat = $empreendimentos->geometry->location->lat;
$geocode_lng = $empreendimentos->geometry->location->lng;
}
// inicio as variáveis
$arr_enterprise = array();
$arr_unitType = array();
$arr_unit = array();
$arr_listing = array();
/*
* Verifico se o empreendimento já foi cadastrado
*/
$enterprise_id = null;
$enterprise_aux = ORM::for_table('module_imobles_enterprise')
->where('google_place_id', $empreendimentos->place_id)
->find_one();
if(isset($enterprise_aux->id) && $enterprise_aux->id > 0)
{
$enterprise_id = $enterprise_aux->id;
$count_repetidos ++;
if($count_repetidos >= 5)
{
$continue = false;
}
// echo "##################### GOOGLE MAPS - EMPREENDIMENTO JÁ CADASTRADO ".$empreendimentos->name." ###################\n\n";
continue;
}
/*
*
* CADASTRO DO EMPREENDIMENTO
*
*/
$url = 'https://maps.googleapis.com/maps/api/place/details/json?'
. 'key=AIzaSyC0vUVt5Cy1kR1mP0BmRf94EBXS4_odsi0'
. '&place_id='.$empreendimentos->place_id;
$json_google = curl_init($url);
curl_setopt($json_google, CURLOPT_RETURNTRANSFER, true);
$json_response = curl_exec($json_google);
$result_details = json_decode($json_response);
if(!isset($result_details->result))
{
continue;
}
$place_details = $result_details->result;
// var_dump($place_details);exit;
// Trato os dados do endereço
$address_number = null;
$address_log = null;
$address_zipcode = null;
$arr_address = isset($place_details->address_components)?$place_details->address_components:array();
foreach($arr_address as $address)
{
if(in_array('street_number', $address->types))
{
$address_number = intval($address->long_name);
if($address_number != $address->long_name)
{
$address_number = null;
}
}
if(in_array('postal_code', $address->types))
{
$address_zipcode = preg_replace('/\D/', '', $address->long_name);
}
if(in_array('administrative_area_level_1', $address->types))
{
$address_state = $address->short_name;
}
if(in_array('administrative_area_level_2', $address->types))
{
$address_city = $address->long_name;
}
if(in_array('sublocality_level_1', $address->types))
{
$address_neighborhood = $address->long_name;
}
if(in_array('route', $address->types))
{
$address_log = $address->long_name;
}
}
// Se não tem endereço completo com o número, tratamos o endereço formatado
if($address_number == null)
{
// Verifico se tem o Número no campo formatted_address
$formatted_address = $place_details->formatted_address;
$arr_log = explode(',', $formatted_address);
$logradouro = $arr_log[0];
$discard_place = true;
if(isset($arr_log[1]) && !empty($arr_log[1]))
{
$end_number_aux = trim(strtolower($arr_log[1]));
$end_number_aux = preg_replace('/^(número|numero|num\.?|nu\.?|nu\.?|n\.?)?(º)?\s+/', '', $end_number_aux);
$pattern = '/^[0-9]+(\s+|\-+)?/';
preg_match($pattern, $end_number_aux, $matches, PREG_OFFSET_CAPTURE);
if(!empty($matches[0]))
{
$arr_number_aux = preg_split('/(\s+|\-+)+/',$end_number_aux);
$end_number_aux = trim($arr_number_aux[0]);
if(intval($end_number_aux) == $end_number_aux && $end_number_aux > 0)
{
$address_number = $end_number_aux;
if($address_log == null)
{
$address_log = $arr_log[0];
}
$discard_place = false;
}
}
}
if($discard_place == true)
{
// continue;
}
}
$arr_address_gp = array(
'address_state' => $address_state,
'address_city' => $address_city,
'address_neighborhood' => $address_neighborhood,
'address_zipcode' => $address_zipcode,
'address_log' => $address_log,
'address_number' => $address_number
);
// Verifico se o endereço bate com o do Empreendimento
if($address_number &&
$geo_address_number == $address_number &&
$this->sanitizaLogradouro($geo_address_log) == $this->sanitizaLogradouro($address_log) &&
$this->sanitizaLogradouro($geo_address_neighborhood) == $this->sanitizaLogradouro($address_neighborhood))
{
$result_details->result->arr_address_gp = $arr_address_gp;
$arr_return = $result_details->result;
continue;
}
elseif(empty ($arr_return))
{
// Monta a string de comparação
$description = $listings->listing->description;
$title = $listings->listing->title;
$complement = $listings->listing->address->complement;
$codigo_ext = $listings->listing->externalId;
$str_compare = $description.' @@@ '.$title.' @@@ '.$complement.' @@@ '.$codigo_ext;
$arr_exclude = array();
// Verifico se o nome do empreendimento aparece no anúncio
$compare_name = $this->searchEnterpriseNames($place_details->name, $str_compare, $address_neighborhood);
if($compare_name)
{
$result_details->result->arr_address_gp = $arr_address_gp;
$arr_return = $result_details->result;
continue;
}
}
// Pesquiso pelo endereço
$enterprise_aux = null;
if($address_number)
{
$enterprise_aux = ORM::for_table('module_imobles_enterprise')
// ->where('address_zip', $address_zipcode)
->where('address_log_sanitized', $this->sanitizaLogradouro($address_log))
->where('address_number', $address_number)
->where('address_neighborhood_sanitized', $this->sanitizaLogradouro($address_neighborhood))
->find_one();
}
if(isset($enterprise_aux->id) && $enterprise_aux->id > 0)
{
if(empty($enterprise_aux->google_place_id))
{
// Atualizo os dados com o Google
$enterprise_aux->name = $place_details->name;
$enterprise_aux->latitude = $place_details->geometry->location->lat;
$enterprise_aux->longitude = $place_details->geometry->location->lng;
$enterprise_aux->google_geometry = json_encode($place_details->geometry);
$enterprise_aux->google_phone = isset($place_details->formatted_phone_number)?$place_details->formatted_phone_number:null;
$enterprise_aux->google_place_id = $place_details->place_id;
$enterprise_aux->google_plus_code = isset($place_details->plus_code)?json_encode($place_details->plus_code):null;
$enterprise_aux->google_rating = isset($place_details->rating)?$place_details->rating:null;
$enterprise_aux->google_reference = $place_details->reference;
$enterprise_aux->google_reviews = isset($place_details->reviews)?json_encode($place_details->reviews):null;
$enterprise_aux->google_user_ratings_total = isset($place_details->user_ratings_total)?$place_details->user_ratings_total:null;
$enterprise_aux->google_json = json_encode($place_details);
$enterprise_aux->link_google = $place_details->url;
$enterprise_aux->updated_at = date('Y-m-d H:i:s');
$enterprise_aux->save();
}
}
else
{
// Populo o array do empreendimento
$arr_enterprise['name'] = $place_details->name;
$arr_enterprise['alias'] = $arr_enterprise['name'];
$arr_enterprise['enable'] = 0;
// $arr_enterprise['comparator_status'] = "Backlog";
// $arr_enterprise['created_by'] = 0;
// Endereço
$arr_enterprise['address_log'] = $address_log;
$arr_enterprise['address_log_sanitized'] = $this->sanitizaLogradouro($address_log);
$arr_enterprise['address_number'] = $address_number;
$arr_enterprise['address_neightborhood'] = $address_neighborhood;
$arr_enterprise['address_neighborhood_sanitized'] = $this->sanitizaLogradouro($address_neighborhood);
$arr_enterprise['address_zip'] = $address_zipcode;
$arr_enterprise['latitude'] = $place_details->geometry->location->lat;
$arr_enterprise['longitude'] = $place_details->geometry->location->lng;
$arr_enterprise['link_google'] = $place_details->url;
$arr_enterprise['google_geometry'] = json_encode($place_details->geometry);
$arr_enterprise['google_phone'] = isset($place_details->formatted_phone_number)?$place_details->formatted_phone_number:null;
$arr_enterprise['google_place_id'] = $place_details->place_id;
$arr_enterprise['google_plus_code'] = isset($place_details->plus_code)?json_encode($place_details->plus_code):null;
$arr_enterprise['google_rating'] = isset($place_details->rating)?$place_details->rating:null;
$arr_enterprise['google_reference'] = $place_details->reference;
$arr_enterprise['google_reviews'] = isset($place_details->reviews)?json_encode($place_details->reviews):null;
$arr_enterprise['google_user_ratings_total'] = isset($place_details->user_ratings_total)?$place_details->user_ratings_total:null;
$arr_enterprise['google_json'] = json_encode($place_details);
// Pego o ID do Estado
if($address_state)
{
$c = ORM::for_table("state")->where("uf_state", $address_state)->find_one();
if($c)
{
$arr_enterprise['address_state_id'] = $c->id;
// Pego o ID da Cidade
if($address_city)
{
$c = ORM::for_table("city")
->where("city_name", $address_city)
->where("id_state", $c->id)
->find_one();
if ($c) {
$arr_enterprise['address_city_id'] = $c->id;
}
}
}
}
$arr_enterprise['obs'] = null;
// Salvo o empreendimento
$save = $modelEnterprises->createEnterprises($arr_enterprise);
if(is_numeric($save->id))
{
// echo "GOOGLE - NOVO Empreendimento Cadastrado com Sucesso.\n";
$enterprise_id = $save->id;
}
else
{
echo 'OCORREU UM ERRO AO SALVAR O EMPREENDIMENTO';
var_dump($arr_enterprise);
exit;
}
// Cadastro as Torres
$torre = 1;
$tower = ORM::for_table('module_imobles_enterprise_towers')->create();
$tower->title = 'Torre '.$torre;
// $tower->floors = isset($result_listing->floors[0])?$result_listing->floors[0]:null;
$tower->alias = 'torre_'.$torre;
$tower->stage = 'Ready to move in';
$tower->module_imobles_enterprise_id = $enterprise_id;
// $tower->unitsOnTheFloor = isset($result_listing->unitsOnTheFloor)?$result_listing->unitsOnTheFloor:null;
$tower->created_at = date('Y-m-d H:i:s');
$tower->save();
}
}
}
}
// Registro a pesquisa na API NEARBY do Google
$google_nearby = ORM::for_table('module_imobles_google_nearby')->create();
$google_nearby->address_encoded = $geo_address_encoded;
$google_nearby->latitude = $geocode_lat;
$google_nearby->longitude = $geocode_lng;
$google_nearby->google_json = json_encode($arr_results);
$google_nearby->save();
return $arr_return;
}
/*
* Geração de um número randomico
*/
function getRandom(){
// return strtotime(date('Y-m-d H:i:s')).rand(1111,9999).rand(11,99).rand(111,999);
$x = _raid().time();
return $x;
}
/*
* searchEnterpriseNames
* Função para verificar se o nome de um empreendimento está na descrição textual do anúncio
*/
public function searchEnterpriseNames($name, $str_compare, $address_bairro)
{
var_dump($name);
$name = $this->cleanString(trim($name));
$name = mb_strtolower($name.' ');
$name = preg_replace('/(residencial|edificio|condominio|'
. 'res\.+|ed\.+|c\.+|cd\.+|cond\.+|con\.+|co\.+|cod\.+|condo\.+|resid\.+|'
. 'Condominium|Residential|Building|Residence|Condominio do|Condominio de|Condominio da)\s+/i', '', $name);
$name = trim($name);
$name = str_replace('/', ' ', $name);
// Verifico se o nome do empreendimento é similar ao bairro
$arr_name_test = explode(' ', $name);
$arr_exclude_aux = ORM::for_table('module_imobles_crawler_forbidden_terms')->select('term')->find_many();
foreach ($arr_exclude_aux as $term)
{
$term_aux = $this->cleanString(mb_strtolower(trim($term->term)));
$arr_exclude[] = trim($term_aux);
}
$arr_exclude[] = $this->cleanString(mb_strtolower($address_bairro));
if(in_array($name, $arr_exclude) || strlen($name) < 5 || count($arr_name_test) < 2)
{
$pattern = '/((residencial|residence|edificio|condominio|res\.+|ed\.+|c\.+|'
. 'edf\.+|\.+edi\.+|cd\.+|cond\.+|con\.+|\.+co\.+|cod\.+|\.+condo\.+){1}\s+'
. '('.$name.'){1}|('.$name.'){1}\s+(residencial|residence|edificio|condominio|res\.+|ed\.+|'
. 'cd\.+|cond\.+)\s{1})/i';
}
else
{
$pattern = "/".$name."/i";
}
$str_compare = $this->cleanString(mb_strtolower(strip_tags($str_compare)));
var_dump($pattern);
var_dump($str_compare);
if(empty($pattern) || empty($str_compare))
{
return false;
}
$matches = array();
try
{
preg_match_all($pattern, $str_compare, $matches, PREG_OFFSET_CAPTURE);
}
catch (Exception $ex)
{
return false;
}
if(count($matches) && !empty($matches[0]))
{
return true;
}
else
{
return false;
}
}
function persistPricing($price, $yearlyIptu, $monthlyCondoFee, $listing_id, $unit_type_id, $rental = null)
{
$insert_price = false;
$pricing_aux = ORM::for_table('module_imobles_listings_prices')->where('listing_id', $listing_id)->order_by_desc('id')->find_one();
if(isset($pricing_aux->id))
{
if($pricing_aux->price != $price || $pricing_aux->yearly_iptu != $yearlyIptu || $pricing_aux->condo_fee != $monthlyCondoFee)
{
$insert_price = true;
}
}
else
{
$insert_price = true;
}
if($insert_price === true)
{
$pricing_aux = ORM::for_table('module_imobles_listings_prices')->create();
$pricing_aux->listing_id = $listing_id;
$pricing_aux->unit_type_id = $unit_type_id;
$pricing_aux->rental = $rental;
$pricing_aux->price = $price;
$pricing_aux->yearly_iptu = $yearlyIptu;
$pricing_aux->condo_fee = $monthlyCondoFee;
$save = $pricing_aux->save();
}
return true;
}
public function resizeImg($file, $width = 800, $height = 800)
{
// redimensiono a imagem
$larguraMaxima = $width;
$alturaMaxima = $height;
$arquivo = $file;
$t = explode(".", $arquivo);
$tipoImagem = $t[count($t)-1];
if($tipoImagem == "gif")
{
$imagemOriginal = imagecreatefromgif($arquivo);
}
else if($tipoImagem == "jpg" || $tipoImagem == "jpeg" || $tipoImagem == "JPG" || $tipoImagem == "JPEG")
{
$imagemOriginal = imagecreatefromjpeg($arquivo);
}
else if($tipoImagem == "png" || $tipoImagem == "PNG")
{
$imagemOriginal = imagecreatefrompng($arquivo);
}
else
{
echo "Tipo de Arquivo Invalido";
return false;
}
list($larguraOriginal, $alturaOriginal) = getimagesize($arquivo);
if($larguraOriginal > $larguraMaxima || $alturaOriginal > $alturaMaxima)
{
if ($larguraOriginal == $alturaOriginal)
{
$largura = $larguraMaxima;
$altura = $alturaMaxima;
}
else if ($larguraOriginal > $alturaOriginal)
{
$proporcao = 100 * $larguraMaxima / $larguraOriginal;
$largura = $larguraMaxima;
$altura = $alturaOriginal * $proporcao / 100;
}
else if ($larguraOriginal < $alturaOriginal)
{
$proporcao = 100 * $alturaMaxima / $alturaOriginal;
$altura = $alturaMaxima;
$largura = $larguraOriginal * $proporcao / 100;
}
$imagemRedimensionada = imagecreatetruecolor($largura, $altura);
imagecopyresampled($imagemRedimensionada, $imagemOriginal, 0, 0, 0, 0, $largura, $altura, $larguraOriginal, $alturaOriginal);
imagedestroy($imagemOriginal);
if($tipoImagem == "gif" || $tipoImagem == "GIF")
{
imagegif($imagemRedimensionada,$arquivo);
}
else if($tipoImagem == "jpg" || $tipoImagem == "jpeg" || $tipoImagem == "JPG" || $tipoImagem == "JPEG")
{
imagejpeg($imagemRedimensionada,$arquivo,100);
}
else if($tipoImagem == "png")
{
imagepng($imagemRedimensionada,$arquivo,9);
}
imagedestroy($imagemRedimensionada);
}
return true;
}
/*
* Insert Enterprise Images
*/
public function insertEnterpriseImg($url, $enterprise_id, $type, $tags, $thumb = false, $description = null, $resize = true)
{
$image = file_get_contents($url);
if($image)
{
try
{
$enterprise_dir = 'application/plugins/module_imobles/uploads/enterprise/' . $enterprise_id . '/images';
if (!is_dir($enterprise_dir))
{
mkdir($enterprise_dir, 0755, true);
}
$ext = substr($url, strlen($url)-3);
if($ext != 'png')
{
$ext = 'jpg';
}
// Salvo a imagem
$name_aux = "_".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999);
$name = $name_aux.".".$ext;
$file_img = $enterprise_dir.'/'. $name;
file_put_contents($file_img, $image);
// Redimensiono a imagem
$resize_img = $this->resizeImg($file_img, 1200, 800);
if($resize == true)
{
// Crio a miniatura da imagem
$arr_img_size["xxl"] = array("w" => 1152,"h" => 768);
$arr_img_size["xlg"] = array("w" => 840,"h" => 560);
$arr_img_size["lrg"] = array("w" => 600,"h" => 400);
$arr_img_size["med"] = array("w" => 450,"h" => 300);
$arr_img_size["sml"] = array("w" => 300,"h" => 200);
$arr_img_size["xsm"] = array("w" => 120,"h" => 80);
if($thumb === true)
{
$arr_img_size["thumb"] = array("w" => 120,"h" => 80);
}
foreach ($arr_img_size as $k => $v)
{
if(!is_dir($enterprise_dir.'/'.$k))
{
mkdir($enterprise_dir.'/'.$k, 0755, true);
}
$file_img_cp = $enterprise_dir.'/'.$k.'/'.basename($file_img);
copy($file_img, $file_img_cp);
$resize_img = $this->resizeImg($file_img_cp, $v["w"], $v["h"]);
}
// Criou um thumb (104x80)
if($thumb === true)
{
$this->cropImg($enterprise_dir.'/thumb/'.basename($file_img), 104, 80);
}
}
// Registro a imagem da planta para o empreendimento
$d = ORM::for_table('module_imobles_enterprise_imgs')->create();
$d->src = $name;
$d->name = $url;
$d->module_imobles_enterprise_id = $enterprise_id;
$d->type = $type;
$d->created_at = date('Y-m-d H:i:s');
$d->created_by = 0;
$d->tags = json_encode($tags);
$d->description = $description;
$d->save();
// Crio a versão webp da imagem
if($ext != 'png')
{
$jpg=imagecreatefromjpeg($file_img);
$w=imagesx($jpg);
$h=imagesy($jpg);
$webp=imagecreatetruecolor($w,$h);
imagecopy($webp,$jpg,0,0,0,0,$w,$h);
imagewebp($webp, $enterprise_dir."/".$name_aux.".webp", 80);
imagedestroy($jpg);
imagedestroy($webp);
}
}
catch (Exception $ex)
{
echo "ERROR ##### ".$ex->getMessage().$url." | "."\n";
}
}
else
{
return false;
}
return true;
}
public function cropImg($arquivo, $width = 500, $height = 500)
{
// redimensiono a imagem
$t = explode(".", $arquivo);
$tipoImagem = strtolower($t[count($t)-1]);
if($tipoImagem == "gif")
{
$imagemOriginal = imagecreatefromgif($arquivo);
}
else if($tipoImagem == "jpg" || $tipoImagem == "jpeg" || $tipoImagem == "JPG" || $tipoImagem == "JPEG")
{
$imagemOriginal = imagecreatefromjpeg($arquivo);
}
else if($tipoImagem == "png" || $tipoImagem == "PNG")
{
$imagemOriginal = imagecreatefrompng($arquivo);
}
else
{
echo "Tipo de Arquivo Invalido";
return false;
}
$im2 = imagecrop($imagemOriginal, ['x' => 0, 'y' => 0, 'width' => $width, 'height' => $height]);
if ($im2 !== FALSE)
{
if($tipoImagem == "gif" || $tipoImagem == "GIF")
{
imagecreatefromgif($im2, $arquivo);
}
else if($tipoImagem == "jpg" || $tipoImagem == "jpeg" || $tipoImagem == "JPG" || $tipoImagem == "JPEG")
{
imagejpeg($im2, $arquivo);
}
else if($tipoImagem == "png")
{
imagepng($im2, $arquivo);
}
imagedestroy($im2);
}
imagedestroy($imagemOriginal);
return true;
}
}