<?php
date_default_timezone_set('America/Sao_Paulo');
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

function conexaoBD()
{
	$conexao = mysqli_connect('15.204.245.134', 'root', 'Airpost@site123', 'airpost');
	if (!$conexao) {
	    echo "Error: Unable to connect to MySQL." . PHP_EOL;
	    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
	    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
	    exit;
	}
	mysqli_set_charset($conexao,'utf8mb4');
	//mysqli_query($conexao,"SET time_zone = '-3:00';");
	return $conexao;
}
function conexaoBdPDO(){
    // $dbh = new PDO('mysqli:host=181.215.4.76;dbname=airpage_base', 'externo', 'Airpage@site123');
    // return $dbh;
}
function conexaoBDsubPaginas()
{
	// $conexao = mysqli_connect('181.215.4.76', 'externo', 'Airpage@site123', 'airpage_pagina');
	// if (!$conexao) {
	//     echo "Error: Unable to connect to MySQL." . PHP_EOL;
	//     echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
	//     echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
	//     exit;
	// }
	// mysqli_set_charset($conexao,'utf8mb4');
	// //mysqli_query($conexao,"SET time_zone = '-3:00';");
	// return $conexao;
}
function has_ssl( $domain ) {
    $ssl_check = @fsockopen( 'ssl://' . $domain, 443, $errno, $errstr, 2 );
    $res = !! $ssl_check;
    if ( $ssl_check ) { fclose( $ssl_check ); }
    return $res;
}

function existeConf($dominio){
    $ok = false;
    $sslconf =  $dominio.'-le-ssl.conf';
    $sslconfpaste = '/etc/httpd/conf.modules.d/'.$sslconf;
    $comandoshell = '(ls '.$sslconfpaste.' && echo yes) || echo no';
    $sslok = shell_exec($comandoshell);

    $sslok2 = str_replace($sslconfpaste,'',$sslok);
    $sslok2 = trim($sslok2, " \t\n\r");

    if (strpos($sslok2, "yes") !== false) 
        $ok = true;

        //echo $comandoshell . ' ';

    return $ok;
}
function existeDnsA($dominio){
    $sucesso = false;
    $lstDns = dns_get_record($dominio, DNS_A);
    //print_r($lstDns);
    foreach($lstDns as $dns){
        if($dns['type'] == "A"){
            //print_r($dns);
            //$r .=  $dns['type'].' '.$dns['ip'].'<br />';
            if($dns['ip'] == '181.215.4.76' && $dns['host'] == $dominio)
                $sucesso = true;
        }
    }
    if(!$sucesso){
        $lstDns = dns_get_record($dominio, DNS_CNAME);
        //print_r($lstDns);
        foreach($lstDns as $dns){
            if($dns['type'] == "CNAME"){
                //print_r($dns);
                //$r .=  $dns['type'].' '.$dns['ip'].'<br />';
                if($dns['target'] == 'airpage.com.br' && $dns['host'] == $dominio)
                    $sucesso = true;
            }
        }
    }
    return $sucesso;
}
function existeDnsMX($dominio){ 
    $sucesso = false;
    $lstDns = dns_get_record($dominio, DNS_MX);
    //print_r($lstDns);
    foreach($lstDns as $dns){
        if($dns['type'] == "A"){
            //print_r($dns);
            //$r .=  $dns['type'].' '.$dns['ip'].'<br />';
            if($dns['ip'] == '181.215.4.76' && $dns['host'] == $dominio)
                $sucesso = true;
        }
    }
    return $sucesso;
}
function geraSSL($dominio){
    $sucesso = false;
    $confExiste = existeConf($dominio.'-le-ssl.conf');

    if(!$confExiste){
        //Cria arquivo VirtualHost
        $filename = $dominio.'.conf';
        $myfile   = fopen($filename, "w");
        $template = '<VirtualHost *:80> 
            Protocols h2 http/1.1
            ServerName '.$dominio.'
            DocumentRoot /var/www/html 
        </VirtualHost>';

        fwrite($myfile, $template );
        fclose($myfile);

        $cmd = 'mv ' . $filename . ' /etc/httpd/conf.modules.d';
        shell_exec($cmd);

        //Instala SLL
        $cmd = "sudo certbot --apache -d ".$dominio." -m jonatas@brainex.com.br 2>&1; 2";
        $ssl = shell_exec($cmd);
        if (strpos($ssl, "Congratulations") !== false)
            $sucesso = true;
        else
            $sucesso = false;
    }
    return $sucesso;
}

function vsftpdExec($a){
    // $cmd = "vsftpd";
    // $ssl = shell_exec($cmd);
    return 'vsftpd';
}

function gerarHttpd($dominio){

    //Cria arquivo VirtualHost
    $filename = $dominio.'.conf';
    $myfile   = fopen($filename, "w");
    $template = '<VirtualHost *:80> 
        Protocols h2 http/1.1
        ServerName '.$dominio.'
        DocumentRoot /var/www/html/'.$dominio.'
    </VirtualHost>';

    fwrite($myfile, $template );
    fclose($myfile);

    $cmd = 'mv ' . $filename . ' /etc/httpd/conf.modules.d';
    shell_exec($cmd);
}


function arrayCount($resultado){
	// Se o retorno é um array de arrays (múltiplas linhas)
    if (is_array($resultado) && isset($resultado[0])) {
        return count($resultado);
    } 
    // Se o retorno é um array associativo de uma única linha
    elseif (is_array($resultado)) {
        return 1;
    }
    
    // Caso não seja um 
}

function css($arquivo){
	return "comum/css/" . $arquivo . ".css";
}
function js($arquivo){
	return "comum/js/" . $arquivo . ".js";
}
function img($arquivo){
	return "comum/img/" . $arquivo;
}

function compress($source, $destination, $quality) {
 
    $info = getimagesize($source);
 
    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);
 
    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);
 
    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);
 
    imagejpeg($image, $destination, $quality);
 
    return $destination;
}

function valor($valor){
	return number_format($valor, 2, ',', '');
}

function anti_injection($sql){
   $sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"), "" ,$sql);
   $sql = trim($sql);
   $sql = strip_tags($sql);
   $sql = (get_magic_quotes_gpc()) ? $sql : addslashes($sql);
   return $sql;
}

function urlDinamica($str, $replace=array(), $delimiter='-') {
	setlocale(LC_ALL, 'en_US.UTF8');
    if( !empty($replace) ) {
        $str = str_replace((array)$replace, ' ', $str);
    }
 
    $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
    $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
    $clean = strtolower(trim($clean, '-'));
    $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
 
    return $clean;
}

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[Rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
function httpPost($url, $data){
    $postfields = $data;//array('pageid'=>'112');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    // Edit: prior variable $postFields should be $postfields;
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
    $result = curl_exec($ch);
    return $result;
}

$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';

// echo $user_agent;

function getOS() { 
    global $user_agent;
    $os_platform    =   "Não indentificado";
    $os_array       =   array(
                            '/windows nt 6.2/i'     =>  'Windows 8',
                            '/windows nt 6.1/i'     =>  'Windows 7',
                            '/windows nt 6.0/i'     =>  'Windows Vista',
                            '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                            '/windows nt 5.1/i'     =>  'Windows XP',
                            '/windows xp/i'         =>  'Windows XP',
                            '/windows nt 5.0/i'     =>  'Windows 2000',
                            '/windows me/i'         =>  'Windows ME',
                            '/win98/i'              =>  'Windows 98',
                            '/win95/i'              =>  'Windows 95',
                            '/win16/i'              =>  'Windows 3.11',
                            '/macintosh|mac os x/i' =>  'Mac OS X',
                            '/mac_powerpc/i'        =>  'Mac OS 9',
                            '/linux/i'              =>  'Linux',
                            '/ubuntu/i'             =>  'Ubuntu',
                            '/iphone/i'             =>  'iPhone',
                            '/ipod/i'               =>  'iPod',
                            '/ipad/i'               =>  'iPad',
                            '/android/i'            =>  'Android',
                            '/blackberry/i'         =>  'BlackBerry',
                            '/webos/i'              =>  'Mobile'
                        );

    foreach ($os_array as $regex => $value) { 

        if (preg_match($regex, $user_agent)) {
            $os_platform    =   $value;
        }

    }   
    return $os_platform;
}
 // '/mobile/i'     =>  'Handheld Browser'
function getBrowser() {

    global $user_agent;

    $browser        =   "Não indentificado";

    $browser_array  =   array(
                            '/msie/i'       =>  'Internet Explorer',
                            '/firefox/i'    =>  'Firefox',
                            '/safari/i'     =>  'Safari',
                            '/chrome/i'     =>  'Chrome',
                            '/opera/i'      =>  'Opera',
                            '/netscape/i'   =>  'Netscape',
                            '/maxthon/i'    =>  'Maxthon',
                            '/konqueror/i'  =>  'Konqueror'
                           
                        );

    foreach ($browser_array as $regex => $value) { 

        if (preg_match($regex, $user_agent)) {
            $browser    =   $value;
        }

    }

    return $browser;

}

function inputUnic($titulo, $id, $acao, $valor){
	$r = '   <div class="inpt-container" data-id="'.$id.'" data-acao="'.$acao.'">';
	$r .= '     <label>'.$titulo.'</label>';
	$r .= '     <input class="inpt-edicao inpt-01" value="'.$valor.'">';
	$r .= '     <div class="btn-save-item btn-01"><i class="fas fa-check"></i></div>';
	$r .= '   </div>';
	return $r;
}
function textareaUnic($titulo, $id, $acao, $valor){
	$r = '   <div class="inpt-container" data-id="'.$id.'" data-acao="'.$acao.'">';
	$r .= '     <label>'.$titulo.'</label>';
	$r .= '     <textarea class="inpt-edicao inpt-01 not-editor">'.$valor.'</textarea>';
	$r .= '     <div class="btn-save-item btn-01"><i class="fas fa-check"></i></div>';
	$r .= '   </div>';
	return $r;
}

function slugify($text)
{
    // Strip html tags
    $text=strip_tags($text);
    // Replace non letter or digits by -
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    // Transliterate
    setlocale(LC_ALL, 'en_US.utf8');
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    // Remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);
    // Trim
    $text = trim($text, '-');
    // Remove duplicate -
    $text = preg_replace('~-+~', '-', $text);
    // Lowercase
    $text = strtolower($text);
    // Check if it is empty
    if (empty($text)) { return 'n-a'; }
    // Return result
    return $text;
}
function whois_query($domain)
{
 
 // fix the domain name:
 $domain = strtolower(trim($domain));
 $domain = preg_replace('/^http:\/\//i', '', $domain);
 $domain = preg_replace('/^www\./i', '', $domain);
 $domain = explode('/', $domain);
 $domain = trim($domain[0]);
 
 // split the TLD from domain name
 $_domain = explode('.', $domain);
 $lst = count($_domain)-1;
 $ext = $_domain[$lst];
 
 // the list of whois servers
 // most taken from www.iana.org/domains/root/db/
 $servers = array(
  "biz" => "whois.neulevel.biz",
  "com" => "whois.internic.net",
  "us" => "whois.nic.us",
  "coop" => "whois.nic.coop",
  "info" => "whois.nic.info",
  "name" => "whois.nic.name",
  "net" => "whois.internic.net",
  "gov" => "whois.nic.gov",
  "edu" => "whois.internic.net",
  "mil" => "rs.internic.net",
  "int" => "whois.iana.org",
  "ac" => "whois.nic.ac",
  "ae" => "whois.uaenic.ae",
  "at" => "whois.ripe.net",
  "au" => "whois.aunic.net",
  "be" => "whois.dns.be",
  "bg" => "whois.ripe.net",
  "br" => "whois.registro.br",
  "bz" => "whois.belizenic.bz",
  "ca" => "whois.cira.ca",
  "cc" => "whois.nic.cc",
  "ch" => "whois.nic.ch",
  "cl" => "whois.nic.cl",
  "cn" => "whois.cnnic.net.cn",
  "cz" => "whois.nic.cz",
  "de" => "whois.nic.de",
  "fr" => "whois.nic.fr",
  "hu" => "whois.nic.hu",
  "ie" => "whois.domainregistry.ie",
  "il" => "whois.isoc.org.il",
  "in" => "whois.ncst.ernet.in",
  "ir" => "whois.nic.ir",
  "mc" => "whois.ripe.net",
  "to" => "whois.tonic.to",
  "tv" => "whois.tv",
  "ru" => "whois.ripn.net",
  "org" => "whois.pir.org",
  "aero" => "whois.information.aero",
  "nl" => "whois.domain-registry.nl",
  "uk" => "whois.nic.uk",
  "us" => "whois.nic.us",
  "travel" => "whois.nic.travel",
  "gov" => "whois.dotgov.gov",
  "it" => "whois.nic.it"
 );
 
 if (!isset($servers[$ext])) {
  return 'Error: No matching whois server found!';
 }
 
 $nic_server = $servers[$ext];
 
 $output = '';
 
 // connect to whois server:
 if ($conn = fsockopen($nic_server, 43)) {
  fwrite($conn, $domain."\r\n");
  while (!feof($conn)) {
   $output .= fgets($conn, 128);
  }
  fclose($conn);
 } else {
  die('Error: Could not connect to ' . $nic_server . '!');
  //$output = 0;
 }
 return $output;
}
function dominioCompleto($page){
    $forceDomainAirpage = false;
    if($_SERVER['SERVER_NAME'] ==  'preview.airpage.com.br')
        $forceDomainAirpage = true;

    $dominioTxt = $_SERVER['SERVER_NAME'].'/'.$page['NomeDominio'];
    $preDominioTxt = 'https://';
    $dominioAll = '';
    if(strlen($page['DominioProprio']) > 0 && !$forceDomainAirpage){
        if(!($page['DominioProprioSSL']==1))
        $preDominioTxt = 'http://';
        $dominioTxt = $page['DominioProprio'];
    }
    $dominioAll = $preDominioTxt.$dominioTxt;
    return $dominioAll;
}
function dominioSemSSL($page){
    $dominioTxt = 'airpage.com.br/'.$page['NomeDominio'];
    $preDominioTxt = 'https://';
    $dominioAll = '';
    if(strlen($page['DominioProprio']) > 0){
        if(!($page['DominioProprioSSL']==1))
        $preDominioTxt = 'http://';
        $dominioTxt = $page['DominioProprio'];
    }
    $dominioAll = $preDominioTxt.$dominioTxt;
    return $dominioTxt;
}
function containsString($stringAll, $string){
    $retorno = false;
    if (strpos($stringAll, $string) !== false)
        $retorno = true;
    else
        $retorno = false;
    return $retorno;
}

function siteHeaderMenuFontes($pageID){
    $retorno = ""; 
    //return 'newpageid'.$pageID;

    $lstFonte = pesquisar("SELECT * FROM page_fonte WHERE PageID = ".$pageID);
    foreach($lstFonte as $fonte){
        $link = '';
        $fontFamlily = '';
        $fontElem = '';
        if(containsString($fonte['Url'], '<link '))
            $link = $fonte['Url'];
        else
            $link = '<link href="'.$fonte['Url'].'" rel="stylesheet">';

        if(containsString($fonte['FontFamily'], 'font-family:'))
            $fontFamlily = $fonte['FontFamily'];
        else
            $fontFamlily = 'font-family: '.$fonte['FontFamily'].'';

        $fontElemSepara = '';
        if($fonte['h1']){
            $fontElem .= 'h1';
            $fontElemSepara = ',';
        }
        if($fonte['h2']){
            $fontElem .= $fontElemSepara.'h2';
            $fontElemSepara = ',';
        }
        if($fonte['h3']){
            $fontElem .= $fontElemSepara.'h3';
            $fontElemSepara = ',';
        }
        if($fonte['h4']){
            $fontElem .= $fontElemSepara.'h4';
            $fontElemSepara = ',';
        }
        if($fonte['Paragrafo']){
            $fontElem .= $fontElemSepara.'p';
            $fontElemSepara = ',';
        }
        $fontElem =  '<style> '.$fontElem.'{ '.$fontFamlily.' } </style>';

        $retorno .= $link;
        $retorno .= $fontElem;
    }
    return $retorno;
}

$user_os        =   getOS();
$user_browser   =   getBrowser();
