<?php
	lt_include( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );

	define( 'GOOGLE_SITEMAP_PING_URL', 'http://www.google.com/webmasters/sitemaps/ping?sitemap=' );

	/**
	 * implements notification of
	 */
	class PluginSiteMap extends PluginBase
	{
		var $pluginEnabled;
		var $cacheFolder;

		function PluginSiteMap( $source = "" )
		{
			$this->PluginBase( $source );

			$this->id = "sitemap";
			$this->desc = "Generates Google Sitemap for all permalinks.";
			$this->author = "Paul Westbrook";
			$this->locales = Array( "en_UK", "de_DE", "zh_TW", "zh_CN" );
			$this->version = "20070417";

			if( $source == "admin" )
				$this->initAdmin();
			else
				$this->init();
		}

		function init()
		{
			// register the events we want
			$this->registerNotification( EVENT_POST_POST_ADD );
			$this->registerNotification( EVENT_POST_POST_UPDATE );
			$this->registerNotification( EVENT_POST_POST_DELETE );
		}

		function initAdmin()
		{
			$this->init();

			if (defined( "EVENT_POST_ADMIN_PURGE_TEMP_FOLDER" )) {
				// register the events we want
				$this->registerNotification( EVENT_POST_ADMIN_PURGE_TEMP_FOLDER );
			}

			// register an action that will allow users to see which comments have not been
			// accepted yet
			$this->registerAdminAction( "sitemapPluginSettings", "AdminSiteMapPluginSettingsAction" );
			$this->registerAdminAction( "sitemapPluginUpdateSettings", "AdminSiteMapPluginUpdateSettingsAction" );

			// add a menu entry
			$menu =& Menu::getMenu();
			if( !$menu->entryExists( "/menu/controlCenter/manageSettings" ))
				$this->addMenuEntry( "/menu/controlCenter", "manageSettings", "", "", true, false );
			$this->addMenuEntry( "/menu/controlCenter/manageSettings", "sitemapPluginSettings", "admin.php?op=sitemapPluginSettings", "", true, false );
		}

		function register()
		{
			$config =& Config::getConfig();

			$this->cacheFolder = $config->getValue('temp_folder');
			$this->cacheFolder = $this->cacheFolder.'/sitemap/'.$this->blogInfo->getId();
			if( !File::exists( $this->cacheFolder )) {
				File::createDir( $this->cacheFolder, 0755 );
			}

			$blogSettings = $this->blogInfo->getSettings();
			$this->pluginEnabled = $blogSettings->getValue( "plugin_sitemap_enabled" );
		}

		function isEnabled()
		{
			return $this->pluginEnabled;
		}

		/**
		 * process the events that we have registered
		 *
		 * @see PluginBase::process
		 * @see PluginManager
		 */
		function process( $eventType, $params )
		{
			$validEvent = false;

			// Looking for EVENT_POST_POST_ADD, EVENT_POST_POST_UPDATE, EVENT_POST_POST_DELETE
			// or EVENT_POST_ADMIN_PURGE_TEMP_FOLDER (if defined)
			if ( $eventType == EVENT_POST_POST_ADD ||
				 $eventType == EVENT_POST_POST_UPDATE ||
				 $eventType == EVENT_POST_POST_DELETE ||
				(defined( "EVENT_POST_ADMIN_PURGE_TEMP_FOLDER" ) && $eventType == EVENT_POST_ADMIN_PURGE_TEMP_FOLDER) ) {
				$validEvent = true;
			}

			// make sure we're processing the right event!
			if( $validEvent == false)
			{
				return true;
			}

			// Load all of the settings for this blog
			$this->register();

			// do nothing if the plugin is not enabled!
			$blogSettings = $this->blogInfo->getSettings();
			if( !$blogSettings->getValue( "plugin_sitemap_enabled" ))
			{
				// error_log( "plugin not enabled" );
				return true;
			}

			$this->GenerateSiteMap( );

			return true;
		}

		/**
		 * Turns on notification for the specified article
		 *
		 */

		function GenerateSiteMap( )
		{
				// articles object
			$articles = new Articles;

			$list = $articles->getBlogArticles(
				$this->blogInfo->getId(),
				-1,  // date
				-1, // all articles
				0,  // all categories
				POST_STATUS_PUBLISHED  // only published articles
			);

			$url = $this->blogInfo->getBlogRequestGenerator();

			// Save this to a compressed file.
			$compressedFile = $this->cacheFolder."/sitemap.gz";
			$gz = gzopen($compressedFile,'w9');

			if ( $gz )
			{
				// Data from the xml file that needs to be there.
				$xmlData =  "<?xml version='1.0' encoding='UTF-8'?>\n";
				$xmlData .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";

				gzwrite( $gz, $xmlData );

				// Iterate over the posts and create an entry for each.
				foreach( $list as $item )
				{
					gzwrite( $gz, "<url>\n" );
					gzwrite( $gz, "<loc>\n" );
					gzwrite( $gz, htmlspecialchars( $url->postPermalink( $item ) ) . "\n" );
					gzwrite( $gz, "</loc>\n" );
					gzwrite( $gz, "</url>\n" );
				}
				gzwrite( $gz, "</urlset>\n" );
				gzclose( $gz );
			}

			if( File::isReadable( $compressedFile ) )
				File::chMod( $compressedFile, 0644 );

			$blogSettings = $this->blogInfo->getSettings();
			if( $blogSettings->getValue( "plugin_sitemap_notify_google_enabled" ))
			{
				$siteMapUrl = $this->getSiteMapUrl();
				$this->pingGoogleSiteMapManager( $siteMapUrl );
			}
		}

		function getSiteMapUrl()
		{
			$rg =& $this->blogInfo->getBlogRequestGenerator();
			$config =& Config::getConfig();
			$siteMapFile = "/sitemap" . $this->blogInfo->getId() . ".gz";

			if( $config->getValue( "request_format_mode" ) == NORMAL_REQUEST_MODE )
				$siteMapUrl = $rg->getUrl($siteMapFile);
			else
				$siteMapUrl = $rg->blogLink().$siteMapFile;

			return $siteMapUrl;
		}

		function pingGoogleSiteMapManager( $siteMapUrl )
		{
				$pingUrl = GOOGLE_SITEMAP_PING_URL . urlencode( $siteMapUrl );

				// Some web hosting does not allow url fopen to open url
				// So, here we try fopen first, then curl, then the native httpclient
				if( ini_get( 'allow_url_fopen' ) )
				{
					$handle = fopen( $pingUrl, "r" );
					fclose( $handle );
				}
				elseif( function_exists( 'curl_init' ) )
				{
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $pingUrl);
					curl_setopt($ch, CURLOPT_HEADER, 0);
					curl_exec($ch);
					curl_close($ch);
				}
				else
				{
					lt_include( PLOG_CLASS_PATH."class/net/http/httpclient.class.php" );
					$httpClient = new HttpClient();
					$httpClient->fetch( $pingUrl );
				}
		}

		function getPluginConfigurationKeys()
		{
			return (Array(
						Array("name" => "plugin_sitemap_enabled",
							  "type" => "boolean"),
						Array("name" => "plugin_sitemap_notify_google_enabled",
							  "type" => "boolean")
						)
				   );
		}

	}
?>