*/ session_start(); define('BASEPATH', true); date_default_timezone_set("America/Sao_Paulo"); include('system/config.php'); require "../vendor/autoload.php"; require "./system/Integracao.php"; error_reporting(E_ALL ^E_NOTICE ^E_WARNING); //error_reporting(E_ALL); ini_set('display_errors', 1); $url_sistema = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http') . "://" . $_SERVER['SERVER_NAME']; // echo $url_sistema . "\r\n"; if ($_GET["idbtn"]) { $btnid = $_GET["idbtn"]; if (strpos($btnid, "?") !== false) { $btnid = str_replace("?", "&", $btnid); header("Location: " . $url_sistema.'/fb/connect.php?idbtn='.$btnid); } $existe = $db->Query("SELECT * FROM vw_app_grp_btn_user WHERE botao_id = ".$btnid." LIMIT 1"); if ($db->GetNumRows($existe) > 0) { $data = $db->FetchArrayAll($existe)[0]; //print_r($data); //die(); $app_id = $data['fb_app_id']; $app_secret = $data['fb_app_secret']; $fb = new \Facebook\Facebook([ 'app_id' => $app_id, 'app_secret' => $app_secret, //'default_graph_version' => 'v2.10', ]); // $helper = new FacebookRedirectLoginHelper(); $helper = $fb->getRedirectLoginHelper(); // Se a pessoa cancelar a autorização do App if ($_GET["error"] == "access_denied" && $_GET["error_reason"] == "user_denied") { if ((isset($data['urlrecusa_botao']) && $data['urlrecusa_botao'] != "") || (isset($data['urlrecusa_grupo']) && $data['urlrecusa_grupo'] != "") || (isset($data['urlrecusa_default']) && $data['urlrecusa_default'] <> "")) { $db->Close(); $redirecionar = (($data['urlrecusa_botao'] != "") ? $data['urlrecusa_botao'] : (($data['urlrecusa_grupo'] != "") ? $data['urlrecusa_grupo'] : (($data['urlrecusa_default'] != "") ? $data['urlrecusa_default'] : ""))); $redirecionar = str_replace("fbresponder.com.br", $_SERVER['SERVER_NAME'], str_replace("www.fbresponder.com.br", $_SERVER['SERVER_NAME'], $redirecionar)); //echo "Location: ". $redirecionar . "\r\n"; header("Location: ".$redirecionar); //header("Location: ".(($data['urlrecusa_botao'] != "") ? $data['urlrecusa_botao'] : (($data['urlrecusa_grupo'] != "") ? $data['urlrecusa_grupo'] : (($data['urlrecusa_default'] != "") ? $data['urlrecusa_default'] : "")))); die(); } $db->Close(); header("Location: ".$url_sistema."/site/naoautorizado"); die(); } if ($_GET["fb_source"] == "notification") { if (($_GET["idcon"] || $_GET["idcont"]) && ($_GET["idbtn"])) { $db->Query("INSERT INTO boasvindas_clique (contato_id, botao_id) VALUES (".($_GET["idcon"] != "" ? $_GET["idcon"] : $_GET["idcont"]).", ".$_GET["idbtn"].")"); } $db->Close(); ?> Close(); die(); } } else { echo utf8_encode("Não foi informado o ID do App!"); $db->Close(); die(); } $url = "idbtn=".$btnid; if ($_GET["ref"]) $url .= "&ref=".$_GET["ref"]; try { $accessToken = $helper->getAccessToken(); } catch(Facebook\Exceptions\FacebookSDKException $e) { // There was an error communicating with Graph echo $e->getMessage(); exit; } if (isset($accessToken)) { try { if ($_GET["logout"] == 1) { session_unset(); session_destroy(); $db->Close(); header("Location: ".$url_sistema."/fb/connect.php?".$url); } } catch (Exception $e) { //echo "session logout\r\n"; //print_r($e); } try { $_SESSION['fb_token'] = (string) $accessToken; $response = $fb->get('/me?fields=first_name,email,gender,last_name,name,middle_name,link,timezone,locale', $accessToken); $graphObject = $response->getGraphUser()->asArray(); $graphObject["accessToken"] = (string) $accessToken; print_r($graphObject); } catch (Exception $e) { echo "
blabla";
		print_r($e);
		die();
	}
	// Passo o email do contato pras URLs
	$data['urlnotificacao_botao'] = str_replace("{email}", $graphObject["email"], $data['urlnotificacao_botao']);
	$data['urlsucesso_botao'] = str_replace("{email}", $graphObject["email"], $data['urlsucesso_botao']);
	$data['urlsucesso_grupo'] = str_replace("{email}", $graphObject["email"], $data['urlsucesso_grupo']);
	$data['urlsucesso_default'] = str_replace("{email}", $graphObject["email"], $data['urlsucesso_default']);

	// Passo o primeiro nome do contato pras URLs
	$data['urlnotificacao_botao'] = str_replace("{name}", $graphObject["first_name"], str_replace("{nome}", $graphObject["first_name"], $data['urlnotificacao_botao']));
	$data['urlsucesso_botao'] = str_replace("{name}", $graphObject["first_name"], str_replace("{nome}", $graphObject["first_name"], $data['urlsucesso_botao']));
	$data['urlsucesso_grupo'] = str_replace("{name}", $graphObject["first_name"], str_replace("{nome}", $graphObject["first_name"], $data['urlsucesso_grupo']));
	$data['urlsucesso_default'] =str_replace("{name}", $graphObject["first_name"],  str_replace("{nome}", $graphObject["first_name"], $data['urlsucesso_default']));

	// Passo o último nome do contato pras URLs
	$data['urlnotificacao_botao'] = str_replace("{lastname}", $graphObject["last_name"], str_replace("{sobrenome}", $graphObject["last_name"], $data['urlnotificacao_botao']));
	$data['urlsucesso_botao'] = str_replace("{lastname}", $graphObject["last_name"], str_replace("{sobrenome}", $graphObject["last_name"], $data['urlsucesso_botao']));
	$data['urlsucesso_grupo'] = str_replace("{lastname}", $graphObject["last_name"], str_replace("{sobrenome}", $graphObject["last_name"], $data['urlsucesso_grupo']));
	$data['urlsucesso_default'] =str_replace("{lastname}", $graphObject["last_name"],  str_replace("{sobrenome}", $graphObject["last_name"], $data['urlsucesso_default']));

	// Passo o facebook id do contato pras URLs
	$data['urlnotificacao_botao'] = str_replace("{fbid}", $graphObject["id"], $data['urlnotificacao_botao']);
	$data['urlsucesso_botao'] = str_replace("{fbid}", $graphObject["id"], $data['urlsucesso_botao']);
	$data['urlsucesso_grupo'] = str_replace("{fbid}", $graphObject["id"], $data['urlsucesso_grupo']);
	$data['urlsucesso_default'] = str_replace("{fbid}", $graphObject["id"], $data['urlsucesso_default']);

	$sql = $db->Query("SELECT * FROM fbcontatos WHERE user_app_id=".$data["appid"]." AND fb_id='".$graphObject["id"]."' LIMIT 1");
	if ($db->GetNumRows($sql) == 0) {
		$sql2 = "INSERT INTO fbcontatos (user_id, user_app_id, fb_id, fb_name, fb_fname, fb_mname, fb_lname, fb_email, fb_link, fb_gender, fb_token, fb_birthday, fb_timezone, fb_locale, fb_location, fb_city, fb_state, fb_country, fb_zip, fb_latitude, fb_longitude, ip_inscricao) VALUES (".$data["user_id"].", ".$data["appid"].", '".$graphObject["id"]."', '".addslashes(utf8_decode($graphObject["name"]))."', '".addslashes(utf8_decode($graphObject["first_name"]))."', '".addslashes(utf8_decode($graphObject["middle_name"]))."', '".addslashes(utf8_decode($graphObject["last_name"]))."', '".$graphObject["email"]."', '".$graphObject["link"]."', '".$graphObject["gender"]."', '".$graphObject["accessToken"]."', '".$graphObject["birthday"]."', '".$graphObject["timezone"]."', '".$graphObject["locale"]."', '".$graphObject["location"]."', '".$graphObject["city"]."', '".$graphObject["state"]."', '".$graphObject["country"]."', '".$graphObject["zip"]."', '".$graphObject["latitude"]."', '".$graphObject["longitude"]."', '".VisitorIP()."')";
		$db->Query($sql2);
		$contato = $db->QueryFetchArray("SELECT LAST_INSERT_ID()");
		$id_contato = $contato["LAST_INSERT_ID()"];
	}
	else {
		$contato = $db->FetchArrayAll($sql)[0];
		$id_contato = $contato["id"];
		if ($contato["ativo"] != 1) {
			//echo "Usuário Inativo!
\r\n"; $ativar = $db->Query("UPDATE fbcontatos SET ativo = 1, ip_inscricao = '".VisitorIP()."', dh_inclusao = CURRENT_TIMESTAMP() WHERE id=".$id_contato." LIMIT 1", 0, true); } if ($contato["ip_inscricao"] == "") $ativar = $db->Query("UPDATE fbcontatos SET ip_inscricao = '".VisitorIP()."', dh_inclusao = CURRENT_TIMESTAMP() WHERE id=".$id_contato." LIMIT 1"); /*else $ativar = $db->Query("UPDATE fbcontatos SET dh_inclusao = CURRENT_TIMESTAMP() WHERE id=".$id_contato." LIMIT 1");*/ if ($contato["email"] != $graphObject["fb_email"]) $ativar = $db->Query("UPDATE fbcontatos SET fb_email = '".$graphObject["email"]."' WHERE id=".$id_contato." LIMIT 1"); } $tags_integracao = array(); if ($_GET["ref"] && $_GET["ref"] <> "notif") { $tag_ref = "ref_".$_GET["ref"]; $sql_tag = $db->Query("SELECT * FROM tags WHERE tag='".$tag_ref."' AND user_id=".$data["user_id"]." LIMIT 1"); if ($db->GetNumRows($sql_tag) == 0) { $db->Query("INSERT INTO tags (user_id, tag) VALUES (".$data["user_id"].", '".$tag_ref."')"); $tag = $db->QueryFetchArray("SELECT LAST_INSERT_ID()"); $id_tag = $tag["LAST_INSERT_ID()"]; } else { $tag = $db->FetchArrayAll($sql_tag)[0]; $id_tag = $tag["id"]; } array_push($tags_integracao, $tag_ref); $db->Query("INSERT INTO x_contato_tag (contato_id, tag_id) VALUES (".$id_contato.", ".$id_tag.")"); } $tags = $db->QueryFetchArrayAll("SELECT x_botao_tag.tag_id tag_id, tags.tag tag FROM x_botao_tag INNER JOIN tags ON tags.id = x_botao_tag.tag_id WHERE botao_id=".$btnid); if (count($tags) > 0) { foreach ($tags as $tag) { if ($id_contato > 0) { $db->Query("INSERT INTO x_contato_tag (contato_id, tag_id) VALUES (".$id_contato.", ".$tag["tag_id"].")"); array_push($tags_integracao, $tag["tag"]); } } } if (($data["envioautomatico"] == 1 && isset($data["mensagem_grupo"]) && trim($data["mensagem_grupo"]) <> "") || (isset($data["mensagem_botao"]) && trim($data["mensagem_botao"]) <> "")) { try { // $request = new FacebookRequest($session, 'POST', '/'.$graphObject["id"].'/notifications', ); // $response = $request->execute(); $data_notificacao = array( 'template' => substr(str_replace("{fbid}", $graphObject["id"], str_replace("{email}", $graphObject["email"], str_replace("{nome}", $graphObject["first_name"], str_replace("{name}", $graphObject["first_name"], str_replace("{sobrenome}", $graphObject["last_name"], str_replace("{lastname}", $graphObject["last_name"], utf8_encode(((trim($data["mensagem_botao"]) != "") ? $data["mensagem_botao"] : $data["mensagem_grupo"])))))))), 0, 180), 'href' => 'connect.php?'.$url."&idcont=".$id_contato, ); $response = $fb->post('/'.$graphObject["id"].'/notifications', $data_notificacao, $app_id."|".$app_secret); $graphObject2 = $response->getGraphObject()->asArray(); } catch (Exception $e) { //echo "Ocorreu um erro ao tentar enviar a notificação!\r\n"; //print_r($e); //$db->Close(); //die(); } } if ($graphObject["email"] != "") { $envio = new Integracao(); $nivel = 999999; $vinculo_botao_grupo_app = $db->Query("SELECT DISTINCT appid, grupo_id, botao_id, user_id FROM vw_app_grp_btn_user WHERE botao_id = ".$btnid." LIMIT 1"); if ($db->GetNumRows($vinculo_botao_grupo_app) > 0) { $vinculo_botao_grupo_app = $db->FetchArrayAll($vinculo_botao_grupo_app)[0]; //print_r($vinculo_botao_grupo_app); $vinculo_botao_integracao = $db->Query("SELECT *, CASE tipo_local WHEN 'botao' THEN 1 WHEN 'botao_grupo' THEN 2 WHEN 'app' THEN 3 WHEN 'geral' THEN 4 ELSE 0 END ordem FROM x_integracao_local WHERE ((local_id = ".$vinculo_botao_grupo_app["botao_id"]." AND tipo_local = 'botao') OR (local_id = ".$vinculo_botao_grupo_app["grupo_id"]." AND tipo_local = 'botao_grupo') OR (local_id = ".$vinculo_botao_grupo_app["appid"]." AND tipo_local = 'app') OR (local_id = 0 AND tipo_local = 'geral')) AND user_id = ".$vinculo_botao_grupo_app["user_id"]." ORDER BY CASE tipo_local WHEN 'botao' THEN 1 WHEN 'botao_grupo' THEN 2 WHEN 'app' THEN 3 WHEN 'geral' THEN 4 ELSE 0 END"); if ($db->GetNumRows($vinculo_botao_integracao) > 0) { $integracoes = $db->FetchArrayAll($vinculo_botao_integracao); //print_r($integracoes); foreach($integracoes as $integracao) { if ($integracao["ordem"] == 0) { break; } else { if ($integracao["ordem"] < $nivel) { $integracao_final = $integracao; $nivel = $integracao["ordem"]; } break; } } //print_r($integracao_final); $pegar_integracao = $db->Query("SELECT * FROM integracao WHERE id = ".$integracao_final["integracao_id"]." LIMIT 1"); if ($db->GetNumRows($pegar_integracao) > 0) { $pegar_integracao = $db->FetchArrayAll($pegar_integracao)[0]; //print_r($pegar_integracao); $fb_id = $graphObject["id"]; $fb_name = $graphObject["name"]; $fb_fname = $graphObject["first_name"]; $fb_lname = $graphObject["last_name"]; $fb_email = $graphObject["email"]; switch ($pegar_integracao["sistema"]) { case "ac": $activecampaign_api_url = $pegar_integracao["campo1"]; $activecampaign_api_key = $pegar_integracao["campo2"]; $activecampaign_list_id = $pegar_integracao["campo3"]; $tags = implode(",", $tags_integracao); if ($activecampaign_api_url != "" && $activecampaign_api_key != "" && $activecampaign_list_id != "") $envio->send_ac($activecampaign_api_url, $activecampaign_api_key, $activecampaign_list_id, $fb_fname, $fb_lname, $fb_email, $tags); break; case "ar": $ar_url = $pegar_integracao["campo1"]; $envio->send_ar($ar_url, $fb_fname, $fb_lname, $fb_email); break; case "aw": $aweber_integracao = $integracao_final["integracao_id"]; $aweber_listname = $pegar_integracao["campo1"]; $aweber_formulario = $pegar_integracao["campo_texto"]; $botao_integrado = $btnid; //echo "$aweber_integracao, $aweber_listname, $aweber_formulario, $botao_integrado, $fb_name, $fb_email\r\n"; $envio->send_aw($aweber_integracao, $aweber_listname, $aweber_formulario, $botao_integrado, $fb_name, $fb_email); break; case "bf": $bft_url = $pegar_integracao["campo1"]; $bft_list_id = $pegar_integracao["campo2"]; $envio->send_bf($bft_url, $bft_list_id, $fb_name, $fb_email); break; case "eg": $egoi_api_key = $pegar_integracao["campo1"]; $egoi_list_id = $pegar_integracao["campo2"]; $envio->send_eg($egoi_api_key, $egoi_list_id, $fb_fname, $fb_lname, $fb_email); break; case "gr": $getresponse_campaign_id = $pegar_integracao["campo1"]; $getresponse_campaign_apikey = $pegar_integracao["campo2"]; $getresponse_list_name = $pegar_integracao["campo3"]; //echo "GR\r\n"; if ($getresponse_campaign_id != "") { $getresponse_campaign_id_novo = $envio->send_gr($getresponse_campaign_id, $getresponse_campaign_apikey, $getresponse_list_name, $fb_name, $fb_email); //echo $getresponse_campaign_id_novo . "\r\n"; if (strcmp($getresponse_campaign_id_novo, $getresponse_campaign_id) != 0) $ativar = $db->Query("UPDATE integracao SET campo1 = '".$getresponse_campaign_id_novo."', campo4 = 1 WHERE id = ".$integracao_final["integracao_id"]." LIMIT 1"); } break; case "gn": $gn_url = $pegar_integracao["campo1"]; $fbobject = $graphObject; $fbobject["tags"] = $tags_integracao; $envio->send_gn($gn_url, $fbobject); break; case "gv": $gvo_campaign_code = $pegar_integracao["campo1"]; $gvo_form_id = $pegar_integracao["campo2"]; $gvo_affiliate_name = $pegar_integracao["campo3"]; $envio->send_gv($gvo_campaign_code, $gvo_form_id, $gvo_affiliate_name, $fb_fname, $fb_lname, $fb_email); break; case "is": $infusionsoft_app_name = $pegar_integracao["campo1"]; $infusionsoft_api_key = $pegar_integracao["campo2"]; $tags = implode(",", $tags_integracao); if ($infusionsoft_app_name != "" && $infusionsoft_api_key != "") $envio->send_is($infusionsoft_app_name, $infusionsoft_api_key, $fb_fname, $fb_lname, $fb_email, $tags); break; case "km": $km_form_id = $pegar_integracao["campo1"]; $envio->send_km($km_form_id, $fb_fname, $fb_email); break; case "ll": $llm_machine_id = $pegar_integracao["campo1"]; $llm_pid = $pegar_integracao["campo2"]; $envio->send_ll($llm_machine_id, $llm_pid, $fb_name, $fb_email); break; case "mc": $mailchimp_url = $pegar_integracao["campo1"]; $mailchimp_apikey = $pegar_integracao["campo2"]; $mailchimp_listid = $pegar_integracao["campo3"]; $mailchimp_url_novo = $envio->send_mc($mailchimp_url, $mailchimp_apikey, $mailchimp_listid, $fb_fname, $fb_lname, $fb_email); if (strcmp($mailchimp_url_novo, $mailchimp_url) != 0) $ativar = $db->Query("UPDATE integracao SET campo1 = '".$mailchimp_url_novo."', campo4 = 1 WHERE id = ".$integracao_final["integracao_id"]." LIMIT 1"); break; case "mm": $mm_formid = $pegar_integracao["campo1"]; $mm_wpnonce = $pegar_integracao["campo2"]; $mm_referer = $pegar_integracao["campo3"]; $mm_url = $pegar_integracao["campo4"]; $envio->send_mm($mm_url, $mm_formid, $mm_wpnonce, $mm_referer, $fb_fname, $fb_email); break; case "rm": $rm_list_id = $pegar_integracao["campo1"]; $rm_url = $pegar_integracao["campo3"]; $envio->send_rm($rm_url, $rm_list_id, $fb_id, $fb_fname, $fb_email); break; case "rs": $rs_token = $pegar_integracao["campo1"]; $rs_identificador = $pegar_integracao["campo2"]; $tags = implode(",", $tags_integracao); $envio->send_rs($rs_token, $rs_identificador, $fb_name, $fb_email, $tags); break; case "sr": $sr_list_id = $pegar_integracao["campo1"]; $envio->send_sr($sr_list_id, $fb_name, $fb_email); break; case "se": break; case "tw": $trafficwave_trwvid = $pegar_integracao["campo1"]; $trafficwave_series = $pegar_integracao["campo2"]; $trafficwave_subscrurl = $pegar_integracao["campo3"]; $trafficwave_confirmurl = $pegar_integracao["campo4"]; $envio->send_tw($trafficwave_trwvid, $trafficwave_series, $trafficwave_subscrurl, $trafficwave_confirmurl, $fb_name, $fb_email); break; } } } } } $db->Close(); //echo "Location: ".(($data['urlsucesso_botao'] != "") ? $data['urlsucesso_botao'] : (($data['urlsucesso_grupo'] != "") ? $data['urlsucesso_grupo'] : (($data['urlsucesso_default'] != "") ? $data['urlsucesso_default'] : ""))) . "\r\n"; if ((isset($data['urlsucesso_botao']) && $data['urlsucesso_botao'] != "") || (isset($data['urlsucesso_grupo']) && $data['urlsucesso_grupo'] != "") || (isset($data['urlsucesso_default']) && $data['urlsucesso_default'] <> "")) { $redirecionar = (($data['urlsucesso_botao'] != "") ? $data['urlsucesso_botao'] : (($data['urlsucesso_grupo'] != "") ? $data['urlsucesso_grupo'] : (($data['urlsucesso_default'] != "") ? $data['urlsucesso_default'] : ""))); $redirecionar = str_replace("fbresponder.com.br", $_SERVER['SERVER_NAME'], str_replace("www.fbresponder.com.br", $_SERVER['SERVER_NAME'], $redirecionar)); header("Location: ".$redirecionar); } else { header("Location: ".$url_sistema."/"); } } else { $db->Close(); $permissions = ['email']; header("Location: ".$helper->getLoginUrl($url_sistema.'/fb/connect.php?'.$url, $permissions)); //echo 'Login'; } $db->Close(); ?>