<?php
/**
* Generates a sitemap.org compatible XML file, for use with Google and other search engines.
*
* Renders the file if the gallery root is called with "?sitemap" in the URL.
*
* @author Tim O'Brien
* @version 1.0.3
* @package plugins
*/

$plugin_description = gettext( 'Generates a sitemap.org compatible XML file, for use with Google and other search engines. Based on plugin by Jeppe Fihl Toustrup (Tenzer) : http://tenzer.dk/open-source/zenphoto-sitemap' );
$plugin_author = 'Tim O\'Brien';
$plugin_version = '1.0.3';
$plugin_URL = "http://t413.com/news/zenphoto-site-map-seo";

// Check if we should render the sitemap.
if( !isset( $_GET['sitemap'] ) ) {
	// We are not going to create the sitemap - Exit this script.
	return;
}

/**
* At this point we are going to try to create the sitemap!
*/

// Check if we are creating a sitemap index or not.
if( empty( $_GET['sitemap'] ) ) {
	header( 'Content-Type: text/xml;charset=utf-8' );
	echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
	echo '<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

	echo "	<sitemap>\n";
	echo '		<loc>' . FULLWEBPATH ."/?sitemap=main</loc>\n";
	echo "	</sitemap>\n";


	///////////// /////////// ///////////////
	///////////// list albums ///////////////
	$sqlQuery = 'SELECT id,date FROM ' . prefix( 'albums' ) . ' WHERE `show` = 1 AND `password` = ""';
	$albums = query_full_array( $sqlQuery );

	foreach( $albums as $album ) {
		if ($album['date']){	//check if date is in the album metadata
			$date = strtotime($album['date']);
		}
		else {			//if it isn't, get the latest image's date
			$sqlQuery = 'SELECT albumid,date FROM '.prefix('images').' WHERE `albumid`='.$album['id'].' ORDER BY `date`  DESC LIMIT 1';
			$result = query_full_array($sqlQuery);
			$date = strtotime($result[0][date]);
		}
		echo "	<sitemap>\n";
		echo '		<loc>' . FULLWEBPATH . "/?sitemap=".$album['id']."</loc>\n";
		if($date)
		echo '		<lastmod>' . date(DATE_W3C,$date). "</lastmod>\n";
		echo "	</sitemap>\n";
	}

	// End by printing the ending tag for the XML file.
	echo "</sitemapindex>\n";
} else {
	// We are creating a sitemap, start by outputting the headers for the XML file.

	// Find out if it should be the root or an album sitemap.
	if( $_GET['sitemap'] == 'main' ) {	// We are creating a sitemap for the frontpage.

		// Send out the content-type and charset.
		header( 'Content-Type: text/xml;charset=utf-8' );

		// get the latest changed thing in the gallery.. newest date in images, comments, pages, or pages
		$commTime = query_full_array( 'SELECT `date` FROM '.prefix('comments').' ORDER BY `date`  DESC LIMIT 1' );
		$commTime = strtotime($commTime[0]['date']);
		$latestChange = $commTime;
		$pageTime = query_full_array( 'SELECT `date` FROM '.prefix('zenpage_pages').' ORDER BY `date`  DESC LIMIT 1' );
		$pageTime = strtotime($pageTime[0]['date']);
		if ($pageTime > $latestChange) $latestChange = $pageTime;
		$newsTime = query_full_array( 'SELECT `date` FROM '.prefix('zenpage_news').' ORDER BY `date`  DESC LIMIT 1' );
		$newsTime = strtotime($newsTime[0]['date']);
		if ($newsTime > $latestChange) $latestChange = $newsTime;
		$imageTime = query_full_array( 'SELECT `date` FROM '.prefix('images').' ORDER BY `date`  DESC LIMIT 1' );
		$imageTime = strtotime($imageTime[0]['date']);
		if ($imageTime > $latestChange) $latestChange = $imageTime;
		
		// Output the headers for the XML file.
		echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
		echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
		echo "	<url>\n";
		echo '		<loc>' . FULLWEBPATH . "/</loc>\n";
		echo '		<lastmod>' . date(DATE_W3C,$latestChange) . "</lastmod>\n";
		echo "	</url>\n";

		///////////// ////////// ///////////////
		///////////// list pages ///////////////
		$sqlQuery = 'SELECT id,titlelink,date,lastchange FROM ' . prefix( 'zenpage_pages' ) . ' WHERE `show` = 1';
		$pages = query_full_array( $sqlQuery );
		foreach( $pages as $page ) {
		$pageDate = strtotime($page['date']);
		$page_Change_Date = strtotime($page['lastchange']);
		$pageUrl = FULLWEBPATH . "/pages/" . urlencode( $page['titlelink'] );
		echo "\t<url>\n";
		echo "\t\t<loc>" .$pageUrl. "</loc>\n";
		if ($page_Change_Date > 100)
			echo "\t\t<lastmod>" . date(DATE_W3C,$page_Change_Date). "</lastmod>\n";
		else if ($pageDate>100)
			echo "\t\t<lastmod>" . date(DATE_W3C,$pageDate). "</lastmod>\n";
		echo "\t\t<changefreq>monthly</changefreq>\n";
		echo "\t\t<priority>0.9</priority>\n";
		echo "\t</url>\n";
		}

		///////////// ///////// ///////////////
		///////////// list news ///////////////
		$sqlQuery = 'SELECT id,titlelink,date,lastchange FROM ' . prefix( 'zenpage_news' ) . ' WHERE `show` = 1';
		$articles = query_full_array( $sqlQuery );

		foreach( $articles as $article ) {
			$articleDate = strtotime($article['date']);
			$article_Change_Date = strtotime($article['lastchange']);
			$articleUrl = FULLWEBPATH . "/news/" . urlencode( $article['titlelink'] );
			echo "\t<url>\n";
			echo "\t\t<loc>" .$articleUrl. "</loc>\n";
			if ($article_Change_Date > $articleDate)
				echo "\t\t<lastmod>" . date(DATE_W3C,$article_Change_Date). "</lastmod>\n";
			else if ($articleDate>100)
				echo "\t\t<lastmod>" . date(DATE_W3C,$articleDate). "</lastmod>\n";
			echo "\t\t<changefreq>monthly</changefreq>\n";
			echo "\t\t<priority>0.9</priority>\n";
			echo "\t</url>\n";
		}
		
 }
	else {
		// Create a sub-index for the provided album ID.
		// Check if the ID passed to us, can be used at all.
		$albumID = sanitize_numeric( $_GET['sitemap'] );
		if( empty( $albumID ) ) {
			die( 'Album ID passed is not valid.' );
		}

		// Get the album path.
		$sqlQuery = 'SELECT folder,date FROM ' . prefix( 'albums' ) . ' WHERE `id` = ' . $albumID . ' AND `show` = 1 AND `password` = "";';
		$albums = query_full_array( $sqlQuery );
		if( 0 == count( $albums ) ) {
			// The album was not found, or it is not public available.
			die( 'Album either not found or not public available.' );
		}

		// Split the album path into an array of folders.
		$albumPathArray = explode( '/', $albums[0]['folder'] );
		foreach( $albumPathArray as $folder ) {
			// URL encode each folder path.
			$albumPathArrayEncoded[] = urlencode( $folder );
		}

		// Assemble the array to a string again after the encoding.
		$albumPath = implode( '/', $albumPathArrayEncoded );
		
		if ($albums[0]['date']){	//check if date is in the album metadata
			$date = strtotime($albums[0]['date']);
		}
		else {			//if it isn't, get the latest image's date
			$sqlQuery = 'SELECT albumid,date FROM '.prefix('images').' WHERE `albumid`='.$albumID.' ORDER BY `date`  DESC LIMIT 1';
			$result = query_full_array($sqlQuery);
			$date = strtotime($result[0][date]);
		}
	

		// Send out the content-type and charset.
		header( 'Content-Type: text/xml;charset=utf-8' );

		// Print the XML header and album root.
		echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
		echo '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
		echo "	<url>\n";
		echo '		<loc>' . FULLWEBPATH . "/$albumPath/</loc>\n";
if($date>100)echo '		<lastmod>' . date(DATE_W3C,$date). "</lastmod>\n";
		echo '		<priority>0.8</priority>';
		echo "	</url>\n";

		// Get the images in the album, we don't care about the order of the images.
		$sqlQuery = 'SELECT filename,date FROM ' . prefix( 'images' ) . ' WHERE `albumid` = ' . $albumID . ' AND `show` = 1';
		$images = query_full_array( $sqlQuery );

		// Check if mod_rewrite is enabled.
		if( 1 == getOption( 'mod_rewrite' ) ) {
			// mod_rewrite is enabled. Create nice links.
			// Parse the list and output the XML code for it.
			foreach( $images as $image ) {
				$filename = $image['filename'];
				$imageUrl = FULLWEBPATH . "/$albumPath/" . urlencode( $filename . getOption( 'mod_rewrite_image_suffix' ) );
				$date = strtotime($image['date']);
				echo "	<url>\n";
				echo "		<loc>$imageUrl</loc>\n";
				if($date>100)
				echo '		<lastmod>' . date(DATE_W3C,$date). "</lastmod>\n";
				echo '		<priority>0.6</priority>';
				echo "	</url>\n";
			}
		} else {
			// mod_rewrite is not enabled. Make the ugly links.
			// Parse the list and output the XML code for it.
			foreach( $images as $image ) {
				$filename = $image['filename'];
				$imageUrl = FULLWEBPATH . "/?album=$albumPath&amp;image=" . urlencode( $filename );
				echo "	<url>\n";
				echo "		<loc>$imageUrl</loc>\n";
				echo "	</url>\n";
			}
		}
	}

	// End by printing the ending tag for the XML file.
	echo '</urlset>' . "\n";
}

// Stop the execution, in order to prevent the rest of Zenphoto from being rendered.
exit( );
?>