<?php
function cron_add_ten_minuts( $schedules ) { 
$schedules['tenminuts'] = array( 
    'interval' => 600, 
    'display' => __( 'Once Every Ten Minuts' ) ); 
    return $schedules; 
}
add_filter( 'cron_schedules', 'cron_add_ten_minuts' );

function drk_online_meta_activation() {
	if( !wp_next_scheduled( 'online_meta_job' ) ) {  
	   wp_schedule_event( time(), 'tenminuts', 'online_meta_job' );  
	}
}

add_action('wp', 'drk_online_meta_activation');

function drk_ping_sites() {
	$post_types = array(
        'markets'
    );

    foreach($post_types as $type){
        $args = array( 
            'post_type' => $type
        );
        $posts = new WP_Query( $args );
        while ( $posts->have_posts() ){
            $posts->the_post();
            $id = get_the_ID();

            $site_url = get_post_meta($id, '_market_site', true);
            update_post_meta( $id, '_isOnline', isSiteAvailible($site_url) );
        }
        
        wp_reset_postdata( );
    }


}

add_action ('online_meta_job', 'drk_ping_sites');

function drk_online_meta_deactivate() {	

	$timestamp = wp_next_scheduled ('online_meta_job');
	
	wp_unschedule_event ($timestamp, 'online_meta_job');
} 

register_deactivation_hook (__FILE__, 'drk_online_meta_deactivate');

function isSiteAvailible($url) {
    if(!filter_var($url, FILTER_VALIDATE_URL)){
      return false;
    }
    $curlInit = curl_init($url);
    curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
    curl_setopt($curlInit,CURLOPT_HEADER,true);
    curl_setopt($curlInit,CURLOPT_NOBODY,true);
    curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
    $response = curl_exec($curlInit);

    curl_close($curlInit);
    return $response ? true : false;
  }