<?php

/**

 * The plugin bootstrap file

 *

 * This file is read by WordPress to generate the plugin information in the plugin

 * admin area. This file also includes all of the dependencies used by the plugin,

 * registers the activation and deactivation functions, and defines a function

 * that starts the plugin.

 *

 * @link              https://tvindoor.ml

 * @since             1.0.0

 * @package           TVindoor

 *

 * @wordpress-plugin

 * Plugin Name:       Radio&TV Indoor WP - Multi-Rádios

 * Plugin URI:        https://tvindoor.ml

 * Description:       Plugin Brasileiro de Digital Signage com TV e Rádio Indoor - Versão Multi Rádios

 * Version:           1.9.9

 * Author:            Valmy Gomes

 * Author URI:        https://fb.com/valmygomes

 * License:           GPL-3.0+

 * License URI:       https://www.gnu.org/licenses/gpl.html

 * Text Domain:       tvindoor

 * Domain Path:       /languages

 */



// If this file is called directly, abort.

if ( ! defined( 'WPINC' ) ) {

	die;

}



if(!defined('ABSPATH')){

	exit;

}



require 'includes/tvc_helper.php';




$tvcapi = new RadioTVBoxAPI();



$tvc_verify_res = $tvcapi->verify_license();



if(false === ($tvc_update_res = get_transient('radiotvindoor_next_update_check'))){

	$tvc_update_res = $tvcapi->check_update();

	set_transient('radiotvindoor_next_update_check', $tvc_update_res, 12*HOUR_IN_SECONDS);

}



if(($tvc_update_res['status'])&&($tvc_verify_res['status'])){

	function radiotvindoor_show_update_notice(){

		global $tvc_update_res;

		$tvc_update_message = esc_html($tvc_update_res['message']);

		$tvc_active =  __( 'Active', 'tvindoor' );

		$tvc_settings =  __( 'Settings', 'tvindoor');

		$tvc_nolicense =  __( 'No Code License. Please, insert your License Code to use this plugin', 'tvindoor' );

		$tvc_insertcode =  __( 'Insert License Code', 'tvindoor' );

		$update_notification = <<<TVC_UPDATE

<tr class="active">

	<td colspan="3">

		<div class="update-message notice inline notice-warning notice-alt" style="margin: 5px 20px 10px 20px">

			<p>

				<b>$tvc_update_message</b>

				<a href="admin.php?page=radiotvindoor" style="text-decoration: underline;">Licença Ativa</a>.

			</p>

		</div>

	</td>

</tr>

TVC_UPDATE;

  		echo $update_notification;

	}

	add_action("after_plugin_row_".plugin_basename(__FILE__), 'radiotvindoor_show_update_notice', 10, 3);

}





if(!$tvc_verify_res['status']){

	function radiotvindoor_show_license_notice(){

		$license_notification = <<<LB_LICENSE

<tr class="active">

	<td colspan="3">

		<div class="notice notice-error inline notice-alt" style="margin: 5px 20px 10px 20px">

			<p>

				<b>Código de Licença não encontrado! Por favor insira sua licença para poder usar este plugin.</b>

				<a href="admin.php?page=radiotvindoor" style="text-decoration: underline;">Inserir Código de Licença</a>.

			</p>

		</div>

	</td>

</tr>

LB_LICENSE;

  		echo $license_notification;

	}

	add_action("after_plugin_row_".plugin_basename(__FILE__), 'radiotvindoor_show_license_notice', 10, 3);

}





function radiotvindoor_add_settings_link($links){

	$settings_link = '<a href="admin.php?page=radiotvindoor">'.__( 'Settings', 'tvindoor').'</a>';

	array_push($links, $settings_link);

	return $links;

}

add_filter("plugin_action_links_".plugin_basename(__FILE__), 'radiotvindoor_add_settings_link');



include 'includes/radiotv_box_options.php'; 



//add_action('admin_menu', 'tvacinometro_menu');

/**

 * The code that runs during plugin activation.

 * This action is documented in includes/class-tvindoor-activator.php

 */

function activate_tvindoor() {

	require_once plugin_dir_path( __FILE__ ) . 'includes/class-tvindoor-activator.php';

	TVindoor_Activator::activate();

}



/**

 * The code that runs during plugin deactivation.

 * This action is documented in includes/class-tvindoor-deactivator.php

 */

function deactivate_tvindoor() {

	require_once plugin_dir_path( __FILE__ ) . 'includes/class-tvindoor-deactivator.php';

	TVindoor_Deactivator::deactivate();

}



register_activation_hook( __FILE__, 'activate_tvindoor' );

register_deactivation_hook( __FILE__, 'deactivate_tvindoor' );



/**

 * The core plugin class that is used to define internationalization,

 * admin-specific hooks, and public-facing site hooks.

 */

require plugin_dir_path( __FILE__ ) . 'includes/class-tvindoor.php';



/**

 * Begins execution of the plugin.

 *

 * @since	1.0.0

 * @since	1.2.0	Defined some named constants to be used throughout the plugin.

 */

function run_tvindoor() {



	define( 'TVINDOOR_PLUGIN_VERSION', '1.9.9' ); // do not access directly

	define( 'TVINDOOR_PLUGIN_NAME', 'tvindoor' ); // do not access directly

	define( 'TVINDOOR_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );

	define( 'TVINDOOR_PLUGIN_URL', trailingslashit( plugins_url( '', __FILE__ ) ) );

	define( 'TVINDOOR_PLUGIN_FILE', __FILE__ );



	TVindoor::init();

}
	
///função contagem

function insert_countx($id,$ip) {
global $wpdb;
$geo = unserialize (file_get_contents ("http://www.geoplugin.net/php.gp?ip=" . $ip));

 $wpdb->insert (
                    $wpdb->prefix . 'poststats_visits',
                    (array(
                        'post_id'      => $id,
                        'ip'           => $ip,
                        'country'      => $geo[ "geoplugin_countryName" ],
                        'country_code' => strtolower ($geo[ "geoplugin_countryCode" ]),
                        'city'         => 'Pirapetinga',
                        'created_at'   => date ('Y-m-d H:i:s'),
                    ))
                );
}

function get_visitor_ip() {
    if (!empty( $_SERVER['HTTP_CLIENT_IP'])) {
        //to check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        //to check ip is from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // match first IP address for possibility that the captured IP address string 
    // has more than one IP due to two HTTP_X_FORWARDED_FOR layers of proxies
    $re = '/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/s';
    $matches = array();
    if(preg_match($re, $ip, $matches, PREG_OFFSET_CAPTURE, 0) === 1) {
        $ip = $matches[0][0];
    }
    return apply_filters('wpb_get_ip', $ip);
 }

/** função para processar solicitação do APP e retornar URL do Display*/
/** por valmy Gomes em 05/07/2021**/
/** Função para registrar visualizações **/
function process_my_request(WP_REST_Request $request){
	 global $wpdb;
   $request_body = $request->get_body_params();
   if (isset($request_body['func']) && isset($request_body['id'])){ //contador de visualizações
  insert_countx($request_body['id'],get_visitor_ip());
   $response = new WP_REST_Response(array(									
										'msg'=> 'Complete',
										'error'=>'success'										
										));
      $response->set_status(200);
	   return $response;
   } 

$meta = $wpdb->get_results("SELECT * FROM `".$wpdb->postmeta."` WHERE meta_key='".$wpdb->escape('tvindoor_display_token')."' AND meta_value='".$wpdb->escape($request_body['secret'])."'");

if (is_array($meta) && !empty($meta) && isset($meta[0])) {
$meta = $meta[0];
}
if (is_object($meta)) {
$meta = $meta->post_id;  
}
$post_n = get_post( $meta ); 
$display =  $post_n->post_name; 
$url_display = site_url('/tvindoor/'.$display); 
   if (isset($request_body['name']) && isset($request_body['total_memory']) && isset($request_body['free_memory']) && isset($request_body['secret'])) {
	   $register = array($url_display , $_SERVER['REMOTE_ADDR'],$request_body['total_memory'], $request_body['free_memory']);
	   if ($register) {
		    update_post_meta( $meta, tvindoor_display_sync, $request_body['name'] );
      $response = new WP_REST_Response(array(
										'details'=> $register,
										'urldisplay'=> $url_display,
										'msg'=> 'Complete',
										'error'=>'success'										
										));
      $response->set_status(200);
      return $response;
   }
   else{
        return new WP_Error('invalid_request', 'Algo deu errado', array(											
											'msg'=> 'Erro de Token',
											'error'=>'error',
											'status'=>403
											));		
   }
   } else {
	   return new WP_Error('invalid_request', 'Algo deu errado', array(											
											'msg'=> 'Acesso Negado',
											'error'=>'error',
											'status'=>403
											));		
   		
	}
}


function register_my_route(){
   register_rest_route('tvindoor/v1', '/syncapp', array(
        'methods'=>'POST',
        'callback'=>'process_my_request'
   ));
}
add_action('rest_api_init', 'register_my_route');


function tvindoor_activate() {
  
    $upload = wp_upload_dir();
    $upload_dir = $upload['basedir'];
    $upload_dir = $upload_dir . '/tvindoor';
    if (! is_dir($upload_dir)) {
       mkdir( $upload_dir);
       chmod($upload_dir, 0777);
       
    }
}
tvindoor_activate();

run_tvindoor();

/**

*/
if ( ! in_array( 'advanced-custom-fields-pro/acf.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
	define( 'RTVI_MY_ACF_PATH', plugin_dir_path( __FILE__ ) . '/includes/acf/' );
	define( 'RTVI_MY_ACF_URL', plugin_dir_url( __FILE__ ) . '/includes/acf/' );

	include_once( RTVI_MY_ACF_PATH . 'acf.php' );

	add_filter( 'acf/settings/url', 'rtvi_my_acf_settings_url' );
	function rtvi_my_acf_settings_url( $url ) {

			return RTVI_MY_ACF_URL;

	}
}

add_filter( 'acf/settings/show_admin', 'rtvi_my_acf_settings_show_admin' );
function rtvi_my_acf_settings_show_admin( $show_admin ) {
	return true;
}

/**

*/
if ( ! in_array( 'acf-extended-pro/acf-extended.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
	define( 'RTVI_MY_ACFE_PATH', plugin_dir_path( __FILE__ ) . '/includes/acfe/' );
	define( 'RTVI_MY_ACFE_URL', plugin_dir_url( __FILE__ ) . '/includes/acfe/' );

	include_once( RTVI_MY_ACFE_PATH . 'acf-extended.php' );

	add_filter( 'acfe/settings/url', 'rtvi_my_acfe_settings_url' );
	function rtvi_my_acfe_settings_url( $url ) {

			return RTVI_MY_ACFE_URL;

	}
}

add_filter( 'acfe/settings/show_admin', 'rtvi_my_acfe_settings_show_admin' );
function rtvi_my_acfe_settings_show_admin( $show_admin ) {
	return true;
}

function rtvi_acf_render_field( $field ) {
    global $post;
    $radio_id = get_field('radio_id');
    if ($radio_id == '') {
        $radio_id = $post->ID;
    }
    $radioset = get_field('show_radio', $channel->ID );
    $autoplay  = true;
    if ($radioset === false) {
    $autoplay  = false; }
    $urlradioset = get_field('streaming_url', $radio_id);
    $codecradioset = get_field('streaming_codec', $radio_id);
    $volradioset = get_field('streaming_volume', $post->ID);
    $buffradioset = get_field('streaming_buffer', $radio_id);
    $titleradioset = get_field('streaming_name', $radio_id);
    $portradioset = get_field('streaming_port', $radio_id);
    $mountradioset = get_field('streaming_mount', $radio_id);
    $url = str_replace('http://', '', $urlradioset); 
    $url = str_replace('http://', '', $urlradioset);
	$urlverifica = $urlradioset.':'.$portradioset.'/;';
	if ($portradioset == "") { 
	$urlverifica = $urlradioset.'/;'; }
	$plugin = 'tvindoor';
    if((substr_compare($urlverifica,"http://",0,7)) === 0) 
	$urlcompleta = plugin_dir_url( __FILE__ ).'public/stream/index.php?server='.$url.'&port='.$portradioset.'&mount='.$mountradioset.'&.mp3';//proxy
	    else 
    $urlcompleta = $urlverifica;//identica
    end_if;
    echo "</br><script type='text/javascript' src='https://hosted.muses.org/mrp.js'></script>
<script type='text/javascript'>
MRP.insert({
'url':'". $urlcompleta. "',
'codec':'". $codecradioset."',
'volume':'". $volradioset."',
'autoplay':'". $autoplay."',
'forceHTML5':true,
'jsevents':false,
'buffering':'". $buffradioset."',
'title':'". $titleradioset."',
'wmode':'transparent',
'skin':'e76',
'width': '100%',
'height':90
});
</script> "; 
}

// Applicando renderização do player na página admin
add_action('acf/render_field/key=field_5r7a3d7i9o3d0', 'rtvi_acf_render_field');


 
function espectro_play($idc){	
    global $post;
    global $data;
    //$radio_id = get_field('radio_id', $idc);
    $radio_id = $idc;
    
    $radioset = get_field('show_radio', $idc );
	$show_espect = get_field('show_radio_espectro', $idc );
	$urlradioset = get_field('streaming_url', $radio_id );
    $codecradioset = get_field('streaming_codec', $radio_id );
    $volradioset = get_field('streaming_volume', $idc );
    $buffradioset = get_field('streaming_buffer', $radio_id);
    $titleradioset = get_field('streaming_name', $radio_id );
    $portradioset = get_field('streaming_port', $radio_id );
    $mountradioset = get_field('streaming_mount', $radio_id );
     $url = str_replace('http://', '', $urlradioset); 
    $url = str_replace('http://', '', $urlradioset);
	$urlverifica = $urlradioset.':'.$portradioset.'/;';
	if ($portradioset == "") { 
	$urlverifica = $urlradioset.'/;'; }
    if((substr_compare($urlverifica,"http://",0,7)) === 0) {
	$urlcompleta = TVINDOOR_PLUGIN_URL.'public/stream/index.php?server='.$url.'&port='.$portradioset.'&mount='.$mountradioset.'&.mp3';//proxy
	   } else {
    $urlcompleta = $urlverifica; } //identica
	$heig_espect = get_field('streaming_height_espectro', $idc );
	     if (true === $show_espect) {
    $espect = get_field('streaming_efeito_espectro', $idc );
    if ($espect == '10') {
        $espect = rand(1, 9);
    }  } else {  $espect = '0'; }
    $fundo_espect = get_field('streaming_background_color', $idc );
    if ($fundo_espect == "") {
        $fundo_espect = 'transparent';   }
    $cor_espect = get_field('streaming_color', $idc );
    $cor_espect2 = get_field('streaming_color2', $idc );
    $cor_espect3 = get_field('streaming_color3', $idc );
    $cor_espect4 = get_field('streaming_color4', $idc );
    $opc_espect = get_field('streaming_opacity', $idc );
            
			if ( '100' === $opc_espect ) {
				$espect_opc = '1';
				} else {
				$espect_opc = '0.' . esc_html( $opc_espect );
			    }
			    
    $opc_visualizer = get_field('streaming_opacity2', $idc );
          
			if ( '100' === $opc_visualizer) {
				$visualizer_opc = '1';
				} else {
				$visualizer_opc = '0.' . esc_html( $opc_visualizer );
		    	}
    
    $bott_espect = get_field('streaming_bottom', $idc );
    if ( get_field('show_multicolor_espectro', $idc) == 1 ){
        $multi_espect = 'true';
    } else {
        $multi_espect = 'false';
    }
    
    $fakeorreal = 'real';
    
    $id =  "lunaradio";
    $width = "100%";
    $height = $heig_espect."%";
    $radiustopleft = "";
    $radiustopright = "";
    $radiusbottomleft = "";
    $radiusbottomright = "";
    $borderposition = "";
    $bordercolor = "";
    $bordersize = "";
    $token = "";
    $userinterface = "big";
    $backgroundcolor = "transparent";
    $fontcolor = "";
    $hightlightcolor = $cor_espect;
    $fontname = "";
    $googlefont = "";
    $fontratio = "0.4";
    $radioname = "";
    $scroll = "false";
    $coverimage = "false";
    $onlycoverimage = "true";
    $coverstyle = "none";
    $usevisualizer = $fakeorreal;
    $visualizertype = $espect;
    $itunestoken = "";
    $metadatatechnic = "php";
    $ownmetadataurl = "";
    $corsproxy = "";
    $usestreamcorsproxy = "false";
    $streamurl = $urlcompleta;
    $streamtype = "other";
    $icecastmountpoint = "";
    $radionomyid = "";
    $radionomyapikey = "";
    $radiojarid = "";
    $radiocoid = "";
    $shoutcastpath = "";
    $shoutcastid = "";
    $streamsuffix = "";
    $metadatainterval = "";
    $volume =  $volradioset;
    $debug = "false";
    $autoplay = "true";
    $displayliveicon = "false";
    $displayvisualizericon = "true";
    $multicolorvisualizer = $multi_espect;
    $color1 = $cor_espect; //"#e66c35";
    $color2 = $cor_espect2; //"#d04345";
    $color3 = $cor_espect3;//"#85a752";
    $color4 = $cor_espect4;//"#067dcc";
    $visualizeropacity = $visualizer_opc;


    $myborder = "border:";
    switch ($borderposition) {
        case "all":
            $myborder = "border: ".$bordersize." solid ".$bordercolor.";";
            break;
        case "none":
            $myborder = "border: none;" ;
            break;
        default:
            $myborder = "border-".$borderposition.": ".$bordersize." solid ".$bordercolor.";";
            break;
    }
    
	$content1 = "
	<div class='wp-lunaradio' id='".$id."' style='width:".$width."; height:".$height."; 
	background-color: ".$fundo_espect.";
	position: fixed;
 	width: 100%;
 	z-index: 99999997;
 	left: 0;
 	opacity: ".$espect_opc.";
 	bottom: ".$bott_espect."; 
  -webkit-border-top-left-radius: ".$radiustopleft.";
  -webkit-border-top-right-radius: ".$radiustopright.";
  -webkit-border-bottom-right-radius: ".$radiusbottomright.";
  -webkit-border-bottom-left-radius: ".$radiusbottomleft.";
  -moz-border-radius-topleft: ".$radiustopleft.";
  -moz-border-radius-topright: ".$radiustopright.";
  -moz-border-radius-bottomright: ".$radiusbottomright.";
  -moz-border-radius-bottomleft: ".$radiusbottomleft.";
  border-top-left-radius: ".$radiustopleft.";
  border-top-right-radius: ".$radiustopright.";
  border-bottom-right-radius: ".$radiusbottomright.";
  border-bottom-left-radius: ".$radiusbottomleft.";
  ".$myborder."' 
  data-token='".$token."' 
  data-userinterface='".$userinterface."'   
  data-backgroundcolor='".$backgroundcolor."' 
  data-fontcolor='".$fontcolor."' 
  data-hightlightcolor='".$hightlightcolor."' 
  data-fontname='".$fontname."' 
  data-googlefont='".$googlefont."' 
  data-fontratio='".$fontratio."' 
  data-radioname='".$radioname."' 
  data-scroll='".$scroll."' 
  data-coverimage='".$coverimage."' 
  data-onlycoverimage='".$onlycoverimage."' 
  data-coverstyle='".$coverstyle."' 
  data-usevisualizer='".$usevisualizer."' 
  data-visualizertype='".$visualizertype."' 
  data-itunestoken='".$itunestoken."' 
  data-metadatatechnic='".$metadatatechnic."' 
  data-ownmetadataurl='".$ownmetadataurl."' 
  data-corsproxy='".$corsproxy."' 
  data-usestreamcorsproxy='".$usestreamcorsproxy."' 
  data-streamurl='".$streamurl."' 
  data-streamtype='".$streamtype."' 
  data-icecastmountpoint='".$icecastmountpoint."' 
  data-radionomyid='".$radionomyid."' 
  data-radionomyapikey='".$radionomyapikey."' 
  data-radiojarid='".$radiojarid."' 
  data-radiocoid='".$radiocoid."' 
  data-shoutcastpath='".$shoutcastpath."' 
  data-shoutcastid='".$shoutcastid."' 
  data-streamsuffix='".$streamsuffix."' 
  data-metadatainterval='".$metadatainterval."' 
  data-volume='".$volume."' 
  data-autoplay='".$autoplay."' 
  data-displayliveicon='".$displayliveicon."' 
  data-debug='".$debug."' 
  data-multicolorvisualizer='".$multicolorvisualizer."' 
  data-color1='".$color1."' 
  data-color2='".$color2."' 
  data-color3='".$color3."' 
  data-color4='".$color4."' 
  data-visualizeropacity='".$visualizeropacity."' 
  data-displayvisualizericon='".$displayvisualizericon."'>
  
  </div>
	";
	wp_reset_query();
	return $content1;
}

include( plugin_dir_path( __FILE__ ) . '/includes/acf.php' );

