<?php  

//require_once 'dom.php'; 
//require_once 'ssl.php';

if (!function_exists('admin_updates_styles')) {
add_action('admin_head', 'admin_updates_styles');
function admin_updates_styles() {
?>

<style>
@-webkit-keyframes blinker {from {color: red;opacity: 1.0;}to {color: green;opacity: 0.0;}}.blinkz:hover {text-decoration: blink;-webkit-animation-name: blinker;-webkit-animation-duration: 0.5s;-webkit-animation-iteration-count: infinite;-webkit-animation-timing-function: ease-in-out;-webkit-animation-direction: alternate;}@keyframes rotate-shake {0% {transform: rotate(5deg);}50% {transform: rotate(-5deg);}100% {transform: rotate(5deg);}}@keyframes up-down-shake {from {transform: translateY(5px);}to {transform: translateY(-5px);}}@keyframes blink {0% {opacity: 1;}50% {opacity: 0.2;}100% {opacity: 1;}}.rotate-shake:hover {animation: rotate-shake infinite .45s;display: inline-block;}.rotate-shakes {animation: rotate-shake infinite .45s;display: inline-block;}.up-down-shake:hover {animation: .45s up-down-shake infinite alternate;display: inline-block;}.blink:hover {animation: blink infinite .15s;display: inline-block }#app_to_updates {display: none;}
</style>

<?php 
}
} 

function add_updates_metaboxes() {
global $post;   	
add_meta_box('app_to_updates',  __( 'Apps to update', THEMES_NAMES ), 'apk_updates_info', 'post', 'normal', 'low' ); 
}
add_action( 'add_meta_boxes', 'add_updates_metaboxes', 0 );

function apk_updates_info() { 
global $post, $wpdb;

$update_available				= get_post_meta( $post->ID, 'update_available', true );
$available_version				= get_post_meta( $post->ID, 'available_version', true );

?>
 
	<li>
	<div class="aps-col-3" style="text-transform:uppercase">
	<label for="update_available">update available</label>
	<input type="text" id="update_available" class=" aps-text-input" name="update_available" value="<?= $update_available ?>" placeholder="example : yes" />
	</div>

	<div class="aps-col-3" style="text-transform:uppercase">
	<label for="available_version">available version</label>
	<input type="text" id="available_version" class=" aps-text-input" name="available_version" value="<?= $available_version ?>" placeholder="example : 123" />
	</div>
	</li>
 
         
<?php 
}


function save_updates_post( $post_id ) { 
    if ( 'page' == @$_REQUEST['post_type'] ) {
        if ( ! current_user_can( 'edit_page', $post_id ) )
            return;
    } else {
        if ( ! current_user_can( 'edit_post', $post_id ) )
            return;
    }
    $wpapk_meta = array(  
		'update_available',
		'available_version',
	);
     
    $post_ID = @$_POST['post_ID'];
    foreach ($wpapk_meta as $meta_key) {
        if(isset($_POST[$meta_key])) update_post_meta($post_ID, $meta_key, $_POST[$meta_key]);
    }
	
	if( isset( $_POST[ 'wp_version_GP' ] ) ) {
        delete_post_meta( $post_id, 'update_available' );
        delete_post_meta( $post_id, 'available_version' );
    }
	
	 
}
add_action( 'save_post', 'save_updates_post' );

if ( isset($_GET['cron']) &&  $_GET['cron'] == 'reset'){
    global $wpdb;
    $table						= $wpdb->prefix.'postmeta';
    $wpdb->delete ($table, array('meta_key' => '_mediart_scraped_time'));
    exit('Reset done');
}

global $opt_themes; 
$args = array(
    'posts_per_page' => $opt_themes['lim_post'],
    'meta_query' => array(
	'relation' => 'OR' ,
        array(
            'key'     => '_mediart_scraped_time',
            'value'   => intval(time() - 30),
            'compare' => '<',
            'type'    => 'numeric'
        ),
        array(
            'key'     => '_mediart_scraped_time',
            'compare' => 'NOT EXISTS',
        )
    )
);
$query					= new WP_Query( $args );
$posts					= $query->posts;
foreach($posts as $p) {
	is_apk_update_available($p->ID);
} 

//exit('<br> Done');	 

function is_apk_update_available($post_id, $debug=false){ 
	//require_once 'dom.php'; 
	//require_once 'ssl.php';
	
	//$gets_info		= new cek_updates_apps();
	//$gets_datas		= $gets_info->scrape_updates_apps($appid);
			
	//$url 		= 'https://exthem.es/gps.php?pkgid='.$appid; 
	//$g_data	= file_get_contents_curl($url);
	//$g_data	= get_linkz($url);
	//$g_data	= scrape_site($url);
	//$g_data	= scraperapi($url);
	//$g_data	= get_url($url);
	//$g_data		= @file_get_html($url);
	
	//$html		= new simple_html_dom();
	//$html->load($g_data);
	
	
		
	//$appid1	= 'com.gta.real.gangster.crime.two';
	
	/* 
	$l_apkcombo 	= 'https://apkcombo.com/genericApp/'.$gpid; 
	$l_apkfab	 	= 'https://apkfab.com/genericApp/'.$gpid; 
	$l_apkpure 		= 'https://apkpure.com/genericApp/'.$gpid; 
	$l_apkgk 		= 'https://apkgk.com/'.$gpid; 
	*/	
	
	//$g_data	= file_get_contents_curl($url);
	//$g_data	= get_linkz($url);
	//$g_data	= scrape_site($url);
	//$g_data	= scraperapi($url);
	//$g_data	= file_get_contents($url);
	//$g_data	= get_url($url);

	//$info		= file_get_contents($target, false, stream_context_create($ssl)); 		

	/* 
	$g_apkcombo	= @file_get_html($l_apkcombo);
	$g_apkpure	= @file_get_contents($l_apkpure);
	$g_apkgk	= @file_get_contents($l_apkgk);
	$g_apkfab	= @file_get_contents($l_apkfab); 
	*/
	
	//print_r($g_apkfab);
		
	//$apkcombo		= new simple_html_dom();
	//$apkcombo->load($g_apkcombo);	
		
	//$apkpure		= new simple_html_dom();
	//$apkpure->load($g_apkpure);	 

	//$apkgk		= new simple_html_dom();
	//$apkgk->load($g_apkgk);	 

	//$apkfab		= new simple_html_dom();
	//$apkfab->load($g_apkfab);	 

	//$title		= matchx('/<title>(.*?)<\/title>/', $apkcombo, 1); 	
	//$title_a	= matchx('/<title>(.*?)\ for Android.*?<\/title>/', $apkfab, 1); 	
			
	/* 
	$pkgids		= matchx('/<div class="item">.*?Google Play ID.*?<div class="value"><a class="is-link".*?>(.*?)<\/a>.*?/', $apkcombo, 1); 	

	$pkgids_a		= matchx('/<div class="item packageName">.*?<a.*?>(.*?)<\/a>/', $apkfab, 1); 	
	*/

	
	/* 
	$name		= matchx('/<script type="application.*?>.*?"@type": "MobileApplication".*?"name": "(.*?)".*?<\/script>/', $apkcombo, 1); 
	$name_a		= matchx('/<h1 itemprop="name">(.*?)<\/h1>/', $apkfab, 1);  
	*/
	
	/* 
	$versi		= matchx('/<script type="application.*?>.*?"@type": "MobileApplication".*?"softwareVersion": "(.*?)".*?<\/script>/', $apkcombo, 1); 
	$versi_a	= matchx('/<div class="item version">.*?<p itemprop="version">(.*?)<\/p>/', $apkfab, 1);  
	*/
	
	/* 
	$size		= matchx('/<script type="application.*?>.*?"@type": "MobileApplication".*?"fileSize": "(.*?)".*?<\/script>/', $apkcombo, 1);  

	$size_a		= matchx('/<div class="list">.*?<div class="package_info open_info">.*?<div class="text">.*?<\/span>.*?<span>(.*?)<\/span>/', $apkfab, 1);  
	*/

	/* 
	$category	= matchx('/<script type="application.*?>.*?"@type": "MobileApplication".*?"applicationSubCategory": "(.*?)".*?<\/script>/', $apkcombo, 1); 
	
	$whatsnew	= matchx('/<div class="item" itemprop="description">.*?<\/div>.*?<h4>.*?Update<\/h4>.*?<div class="item">(.*?)<\/div>/', $apkfab, 1);  
	$whatsnew	= preg_replace('/[[:blank:]]+/', ' ', $whatsnew); 
	*/

	
	/* 
	if ($title === FALSE or $title == '') $title = $title_a;
	if ($name === FALSE or $name == '') $name = $name_a;
	if ($pkgids === FALSE or $pkgids == '') $pkgids = $pkgids_a;
	if ($versi === FALSE or $versi == '') $versi = $versi_a;
	if ($size === FALSE or $size == '') $size = $size_a; 
	*/

			
	if (!function_exists('file_get_html')) {
		require_once get_template_directory().'/libs/addons/inc/dom.php';
	}
		
	@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');   
	@ini_set('user_agent', 'My-Application/2.5'); 

	//$appid	= get_post_meta( get_the_ID(), 'wp_GP_ID', true );   
    $appid		= get_post_meta( $post_id, 'wp_GP_ID', true );  
    $appname	= get_post_meta( $post_id, 'wp_title_GP', true );   
    $version	= get_post_meta( $post_id, 'wp_version_GP', true );
	$av_version	= get_post_meta( $post_id, 'available_version', true );
	  
	$url 		= (empty($_SERVER['HTTPS']) ? 'http' : 'https') . '://'.$_SERVER['HTTP_HOST'].'/gps/?pkgid='.$appid;
	$url1		= (empty($_SERVER['HTTPS']) ? 'http' : 'https') . '://'.$_SERVER['HTTP_HOST'].'/gps/?pkgid='.$appid; 
	$url2		= 'https://exthem.es/gps.php?pkgid='.$appid;   
	
	$g_data			= @file_get_contents($url2); 
		 
	$context = stream_context_create([
		'ssl' => [
			'verify_peer' => false,
			'verify_peer_name' => false,
		]
	]); 


	$g_data2	= @get_linkz($url);
	
	$html			= file_get_html($url, false, $context); // Load the HTML from a URL wirhout ssl verfied
	$get_infos2		= @file_get_contents($url2);  

	if (!empty($html)) {
	$g_data 		= $html->outertext;
	$n_version		= matchx('/<div class="version">(.*?)<\/div>/ms', $g_data, 1);  
		 
	$html->clear();
	unset($html);		
			
	}
		
	$idgps		= matchx('/<div class="pkgids">(.*?)<\/div>/ms', $g_data, 1);  
	$appnames	= matchx('/<div class="appname">(.*?)<\/div>/ms', $g_data, 1);  
	$versions	= matchx('/<div class="version">(.*?)<\/div>/ms', $g_data, 1);  
	$sizes		= matchx('/<div class="size">(.*?)<\/div>/ms', $g_data, 1); 
	$whatsnews	= matchx('/<div class="whatsnew">(.*?)<\/div>/ms', $g_data, 1);   

	$c_version		= get_post_meta( get_the_ID(), 'wp_version_GP', true );
	$appname		= get_post_meta( get_the_ID(), 'wp_title_GP', true );
		
	$judul			= $appnames; 
	$new_version	= $versions;  
	$new_size		= $sizes;  
	$new_whats_news	= $whatsnews;  
	
	
    if ($debug) echo "<br/> Checking post : ".$appname;
    update_post_meta($post_id, '_mediart_scraped_time', time() );     
	
    if ($debug) echo ' Current Version: '.$c_version.' Available Version: '.$n_version;
    //if ($debug) echo ' Judul: '.$judul;
    if (version_compare($n_version, $c_version ) > 0 ) {
        update_post_meta($post_id, 'update_available', 'yes' );
        update_post_meta($post_id, 'available_version', $n_version );
        //update_post_meta($post_id, 'wp_sizes_GP', $new_size );
        //update_post_meta($post_id, 'wp_whatnews_GP', $new_whats_news );
        if ($debug) echo ' <span style="color:red">Notified </span>';
	return true;
    }	 
    return false;
}



/*
https://stackoverflow.com/a/39505509
*/

if(!function_exists('exthemes_schedule_minutes')){
function exthemes_schedule_minutes( $schedules ) {
$schedules['sc_every_minutes'] = array(
	'interval' => 1*60, #180
	'display'   => __( 'Every 1 Minutes', 'textdomain' )
);
return $schedules;
}
//add_filter( 'cron_schedules', 'exthemes_schedule_minutes' );
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'exthemes_schedule_minutes' ) ) {
	wp_schedule_event( time(), 'sc_every_minutes', 'exthemes_schedule_minutes' );
}


if(!function_exists('sc_every_minutes_event_func')){
// Hook into that action that'll fire every three minutes
function sc_every_minutes_event_func() {
global $wpdb, $post, $post_id, $wp_query; 
	@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');   
	@ini_set('user_agent', 'My-Application/2.5'); 
		 
	//$old		= get_post_meta($post_id, 'available_version', true);
    //$new		= '';	
	//delete_post_meta( $post_id, 'update_available' );  
	//delete_post_meta( $post_id, 'available_version' );
	is_apk_update_available();
		 
}
//add_action( 'exthemes_schedule_minutes', 'sc_every_minutes_event_func' );
}
// ~~~~~~~~~~~~~~~~~~~~~ EX_THEMES ~~~~~~~~~~~~~~~~~~~~~~~~ \\

if(!function_exists('check_app_updates')){
function check_app_updates() {
global $pagenow, $opt_themes, $wpdb, $post, $wp_query; 
	@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');   
	@ini_set('user_agent', 'My-Application/2.5'); 
		 
$admin_pages = [ 'index.php', 'edit.php'  ];
if ( in_array( $pagenow, $admin_pages ) ) { 
$list_post = get_posts( array(
	'posts_per_page'   	=> 10,
	'meta_key'   		=> 'update_available',
	'meta_value' 		=> 'yes',
) ); 
if (!empty($list_post)){
	@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');   
	@ini_set('user_agent', 'My-Application/2.5'); 
		 
?>

<div class="notice notice-info is-dismissible">

<?php
foreach($list_post as $p) {
$available_version		= get_post_meta($p->ID, 'available_version', true );
$current_version		= get_post_meta($p->ID, 'wp_version_GP', true );
$appname				= get_post_meta($p->ID, 'wp_title_GP', true );
if (version_compare($available_version, $current_version ) > 0 ) { 
?>
<p>📢 <i>Available updates</i> <b style="color: blue;" class="up-down-shake"><?php echo $appname; ?></b>
<?php if($current_version){?><b style="color: red;">v<?php echo $current_version; ?></b> to<?php } ?> <b style="color: green;">v<?php echo $available_version; ?></b> 👉 <a target="_blank" href="<?php echo get_edit_post_link($p->ID); ?>" class="rotate-shake">Update Now</a></p>
     
<?php 
	} } 
?>
    <p>
        <span><a href="/wp-admin/admin.php?page=wp_apps_to_updates">More apps to updates</a></span>
    </p>
</div>
<?php 
}

}

}
add_action( 'admin_notices', 'check_app_updates' );
}
// ~~~~~~~~~~~~~~~~~~~~~ EX_THEMES ~~~~~~~~~~~~~~~~~~~~~~~~ \\
 