<?php
/// debug ///
/*ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);*/
///////////////////////////////


// OPTION TO SET CUSTOM ITEMS BASE-URL

include_once(__DIR__ .'/classes/static/gg_static.php');
include_once(__DIR__ .'/classes/static/gg_gall_static.php');

ob_start();


// load WP functions
$curr_path = dirname(__FILE__);
$curr_path_arr = explode(DIRECTORY_SEPARATOR, $curr_path);

$true_path_arr = array();
foreach($curr_path_arr as $part) {
	if($part == 'wp-content') {break;}
	$true_path_arr[] = $part;
}	
$true_path = implode('/', $true_path_arr);


// main functions
if(!file_exists($true_path . '/wp-load.php')) {die('<p>wordpress - wp-load.php file not found</p>');}
else {require_once($true_path . '/wp-load.php');}

if(!function_exists('get_filesystem_method')) {
	// wp-admin/includes/file.php - for wp_filesys
	if(!file_exists(ABSPATH . 'wp-admin/includes/file.php')) {die('<p>wordpress - file.php file not found</p>');}
	else {require_once(ABSPATH . 'wp-admin/includes/file.php');}	
}

/////////////////////////////////////////////////////////////////////////////////////



ob_end_clean();
header("Content-type: text/xml");


echo 
'<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';
    
	
	// retrieve galleries
    $args = array(
        'post_type' 		=> 'gg_galleries', 
        'post_status' 		=> 'publish', 
        'posts_per_page' 	=> -1, 
		'fields' 			=> 'ids', 
        'meta_query' => array(
			array(
			 'key' 		=> 'gg_type',
			 'value' 	=> array('wp', 'wp_cat', 'cpt_tax', 'gg_album', 'rml', 'ngg'),
			 'compare' 	=> 'IN'
		   ),
		),
    );
    $query = new WP_Query($args);	
	
	
    if(is_array($query->posts)) {
        foreach($query->posts as $gid) {
			
			$type 		= get_post_meta($gid, 'gg_type', true);
			$images 	= gg_gall_static::frontend_img_prepare($gid, $type);
			
			$url 		= get_post_meta($gid, 'gg_sitemap_page_url', true);
			$lastmod 	= get_the_modified_date('Y-m-d', $gid);
			
			if(empty($images) || !filter_var($url, FILTER_VALIDATE_URL)) {
				continue;
			}
			
			foreach($images as $img) {
				echo '
				<url> 
				  <loc>'. $url .'</loc> 
				  <lastmod>'. $lastmod  .'</lastmod>
				  <image:image>
					 <image:loc>'. str_replace(array('&', '='), array('%26', '%3D'), gg_static::img_url_on_type($img['img_src'], $type)) .'</image:loc>
					 <image:title>'. str_replace(array('&', '='), array('%26', '%3D'), strip_tags($img['title'])) .'</image:title>
					 <image:caption>'. str_replace(array('&', '='), array('%26', '%3D'), strip_tags($img['descr'])) .'</image:caption>
				  </image:image>
				</url>';	
			}
        }
    }
  ?>

</urlset>