<?php

//****************************************************************************************
// FotoPlayer RSS Feeder FP_RSS v1.0
// Author : Dhinakaran Annamalai
// Protected under Creative Commons License. Attribution 2.0 United Kingdom
// Please refer readme.txt file for the usage details.
//****************************************************************************************

error_reporting(E_ALL ^ E_NOTICE);

if (!ini_get('safe_mode') || strtolower(ini_get('safe_mode')) == 'off' ) {
	ini_set("memory_limit","30M");
}
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
@date_default_timezone_set(@date_default_timezone_get());


global $albumpath,$itemcounts,$searchtag,$writeind,$descstart,$slidenavigation,$thumbsmode;


$slidenavigation="Y"; $thumbsmode = "N";

if (isset($_REQUEST["folder"])) {
	$albumpath = strip_tags($_REQUEST['folder'])."/";
	if ($_REQUEST['folder'] == "") $albumpath ="";
  $albumpath = stripslashes($albumpath);
}
else {
	$albumpath = "all/";
}

if (isset($_REQUEST["items"])) {
	$itemcounts = strip_tags($_REQUEST['items']);
}
else {
	$itemcounts = 10;
}

if (isset($_REQUEST["tag"])) {
	$searchtag = explode(",",strip_tags($_REQUEST['tag']));
}
else {

	$searchtag = "";
}

if (isset($_REQUEST["sort"])) {
	$sortresults=$_REQUEST["sort"];
}
else {
	$sortresults="Y";
}

if (isset($_REQUEST["includesubfolders"])) {
	$includesubfolders=$_REQUEST["includesubfolders"];
}
else {
	$includesubfolders="N";
}


if (isset($_REQUEST["tmode"])) {
	$thumbsmode=$_REQUEST["tmode"];
}
else {
	$thumbsmode="N";
}

//****************************************************************************************************************
function startElement($parser, $name, $attrs)
{

   global $depth, $albumpath, $itemarray,$searchtag,$writeind,$imagetag,$descstart,$slidenavigation,$thumbsmode;
   global $currentTag, $currentAttribs;
   $currentTag = $name;
   $currentAttribs = $attribs;

   for ($i = 0; $i < $depth[$parser]; $i++) {
       echo "  ";
   }
   if ($name == "IMAGE") {

   	     $writeind ="Y";
	     if (isset($itemarray)) {
 	 	     reset($itemarray);
		     unset($itemarray);
	     }

	     if ($searchtag != "") {
			$matchfound="N";
			foreach($searchtag as $value){
					if ($value != "")  {
						if ( preg_match("/".$value."/i", $attrs['TAGS'])  ) $matchfound="Y";
					}
			}
			if ($matchfound=="N") {
			    $writeind ="N";
				return;
			}
	     }

	    if ( preg_match("/youtube/i",$attrs['IMG'])  ) {
			    $writeind ="N";
				return;
	    }
	    $imagetag = $attrs['TAGS'];
	    global $itemarray;
  	    $itemarray = array();
	    $THIS_URL = 'http://' . $_SERVER['SERVER_NAME'];
	    if (strlen(dirname($_SERVER['PHP_SELF'])) != 1)
			    $THIS_URL.= dirname($_SERVER['PHP_SELF'])."/";
	    else
			    $THIS_URL.= "/";


	    $BASE_URL = $THIS_URL;

	    if ($albumpath != "") {
		$THIS_URL = $THIS_URL.$albumpath;
	    }

	    if (isset($_REQUEST["debug"])) echo "\r\n". "processing image: ".$albumpath.$attrs['IMG']. "\r\n";

	    $imgdate  = date("D, d M Y H:i:s",filemtime($albumpath.$attrs['IMG']));
	    $imgdate  =  $imgdate. " GMT";
//	    $sortdate = date("dmyHis",filemtime($albumpath.$attrs['IMG']));
			$searchyear = substr($attrs['DT'],0,4);	$searchmonth = substr($attrs['DT'],5,2);$searchdays = substr($attrs['DT'],8,2); 
			$sortdate = $searchyear.$searchmonth.$searchdays;	    
	    
    	array_push($itemarray,$sortdate);
  	  array_push($itemarray,"<item>");
  	  array_push($itemarray,"<title><![CDATA[". strip_tags(trim($attrs['TITLE']))  ."]]></title>");
	    array_push($itemarray,"<link>". $THIS_URL .$attrs['IMG']."</link>");
	    array_push($itemarray,"<pubDate>".$imgdate."</pubDate>");
	    array_push($itemarray,"<guid>". $THIS_URL .$attrs['IMG']."</guid>");
	    
	    if ($albumpath == "") {
		 					$category = "root";
	    }
	    else {
		 					$category = $albumpath;
	    }
	    array_push($itemarray,"<category>".$category."</category>");	    
      array_push($itemarray,"<description>");
      
//*********************************************//
			 if ($slidenavigation == "Y") {
					//Use Slide image navigator
	  	  	array_push($itemarray,"&lt;a title=\"". $attrs['IMG'] ." ".  htmlspecialchars($attrs['TAGS']) ." ". strip_tags(trim($attrs['TITLE'])) . "\"   href=\"".$BASE_URL."slidenav.php?folder=".$albumpath."&amp;amp;file=".$attrs['IMG']. "\"&gt;&lt;img alt=\"". $attrs['IMG'] ." ".  htmlspecialchars($attrs['TAGS']) ." ". strip_tags(trim($attrs['TITLE'])) . "\"  src=\"". $THIS_URL .$attrs['THMB']. "\" width=\"" .$attrs['THUMBW']. "\" height=\"" .$attrs['THUMBH']. "\"&gt;&lt;/a&gt;&lt;br&gt;");
		   }
		   else {
					//Link directly to slide
			    array_push($itemarray,"&lt;a title=\"". $attrs['IMG'] ." ".  htmlspecialchars($attrs['TAGS']) ." ". strip_tags(trim($attrs['TITLE'])) . "\"   href=\"".$THIS_URL.$attrs['IMG']. "\"&gt;&lt;img alt=\"". $attrs['IMG'] ." ".  htmlspecialchars($attrs['TAGS']) ." ". strip_tags(trim($attrs['TITLE'])) . "\"  src=\"". $THIS_URL .$attrs['THMB']. "\" width=\"" .$attrs['THUMBW']. "\" height=\"" .$attrs['THUMBH']. "\"&gt;&lt;/a&gt;&lt;br&gt;");
	    }
//*********************************************//
			 if ($thumbsmode == "N") {
				    array_push($itemarray,"Date:".$imgdate."&lt;br&gt;");
  	  			array_push($itemarray,"Album Category:".$category."&lt;br&gt;");
  			}
		if ( strpos($attrs['IMG'],"slides") === 0)  { $slideremoved= substr($attrs['IMG'],7);}
		else { $slideremoved =$attrs['IMG'];}
		
			if ($thumbsmode == "N") {
	    		array_push($itemarray,"&lt;a href=\"".$BASE_URL."index.html?folder=".$albumpath."&amp;amp;file=".$slideremoved."\"&gt;Click here&lt;/a&gt; to view album containing this image.&lt;br&gt;");
			}
   };
   if ($name == "DESCRIPTION") {
	     if (isset($itemarray)) {
		  $descstart="y";
  		  array_push($itemarray,"<![CDATA[");
		}

   }


   $depth[$parser]++;
}

//****************************************************************************************************************

function endElement($parser, $name)
{
   global $depth, $currentTag, $currentAttribs, $itemarray, $mainsort,$writeind,$thumbsmode;
   $depth[$parser]--;

   $currentTag = "";
   $currentAttribs = "";
   if ($name == "IMAGE" && $writeind=="Y") {
	     if (isset($itemarray)) {
		     array_push($itemarray,"</item>");
		     array_push($mainsort,$itemarray);
	     }

   };

   if ($name == "DESCRIPTION" && $writeind=="Y") {
	     if (isset($itemarray)) {
		     array_push($itemarray,"]]></description>");
	     }
   };

}
//****************************************************************************************************************
function characterData($parser, $data)
     {
         global $currentTag, $itemarray,$writeind,$imagetag,$descstart,$thumbsmode;
          switch ($currentTag) {
         case "DESCRIPTION":
         	if ($writeind=="Y" && $thumbsmode=="N") {
							if ($descstart=="y") {
										if ($imagetag != "") 
											array_push($itemarray, "Tags: ".$imagetag."<br> Description: ".strip_tags($data)  );
										else
											array_push($itemarray,"Description: ".strip_tags($data)  );		
										$descstart="n";
							}
						else {
									array_push($itemarray, strip_tags($data)  );
						}
					}
           break;
         default:
             break;
         }
     }

//****************************************************************************************************************
function processalbum($file,$folpath) {
	global $depth, $mainsort,$itemcounts,$albumpath,$sortresults,$thumbsmode;
	$albumpath = $folpath ;
	$depth = array();
	$fp = "";$data ="";$mainsort= array();
	$xml_parser = xml_parser_create();
	xml_set_element_handler($xml_parser, "startElement", "endElement");
	xml_set_character_data_handler($xml_parser, "characterData");
	if (!($fp = fopen($file, "r"))) {
	   die("could not open XML input");
	}

	while ($data = fread($fp, 4096)) {
		$data = urldecode($data);
	   	if (!xml_parse($xml_parser, $data, feof($fp))) {
	   			echo "File: ".$file. " ";
          die('XML error '. 'String :'.xml_error_string(xml_get_error_code($xml_parser)) . ' at line '. xml_get_current_line_number($xml_parser) .' column: '. xml_get_current_column_number($xml_parser). '  Data: ' . htmlentities($data));

   		}
	}


	if ($sortresults=="Y")	usort($mainsort, 'compare');


	$tempcount=count($mainsort);
	if ($itemcounts < $tempcount) {
		$tempcount=$itemcounts;
	};

	for ( $row = 0; $row < $tempcount; $row++ ) {

		 for ( $column = 1; $column < count($mainsort[$row]); $column++ ) {
//			 if (function_exists('iconv')) 	 echo iconv( "iso-8859-1", "utf-8",  $mainsort[$row][$column]  );
//			 else echo utf8_encode($mainsort[$row][$column]) ;
			 echo $mainsort[$row][$column] ;
			 
		};
	 };

	fclose($fp);
	xml_parser_free($xml_parser);

}  //processalbum function ends here
//****************************************************************************************************************

	function compare($x, $y)
	{
	 if ( $x[0] == $y[0] )
	  return 0;
	 else if ( $x[0] < $y[0] )
	  return 1;
	 else
	  return -1;
	}

//****************************************************************************************************************

$URL_IMG = 'http://' . $_SERVER['SERVER_NAME'];
if (strlen(dirname($_SERVER['PHP_SELF'])) != 1)
$URL_IMG.= dirname($_SERVER['PHP_SELF']);


$tm=time(); $tm=date("D, d M Y H:i:s",$tm);
$tm=$tm. " GMT"; // you can add your format

if (isset($_REQUEST["debug"]))
	header("Content-Type: text/txt; charset=UTF-8");
else
{
	header("Content-Type: text/xml; charset=utf-8");
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	echo("<rss version=\"2.0\">");
	echo("<channel>");
	echo("<title>FotoPlayer.com RSS feeder</title>");
	echo("<link>http://www.fotoplayer.com</link>");
	echo("<copyright>2005 fotoplayer.com Allrights reserved. Photos may not be copied without author's permission</copyright>");
	echo("<managingEditor>dhinakar.com@gmail.com</managingEditor>");
	echo("<webMaster>dhinakar.com@gmail.com</webMaster>");
	echo("<description>RSS feed</description>");
	echo("<category>Photo album</category>");
	echo("<pubDate>".$tm."</pubDate>");
	echo("<generator>FP_RSS 0.1</generator>");
	echo("<ttl>60</ttl>");
	echo("<image>");
	echo("<title>FP_RSS 0.1</title>");
	echo("<url>".$URL_IMG."/res/fotoplayer.gif"."</url>");
	echo("<link>http://www.fotoplayer.com</link>");
	echo("</image>");
}

global $mainsort;
$mainsort = array();

if ($albumpath != "" && $albumpath != "all/") {
	$xmlpath = $albumpath."photos.xml";
      if (file_exists($xmlpath)) {
  				processalbum($xmlpath,$albumpath);
  				if ($includesubfolders=="Y") map_dirs($albumpath);
      }

}
if ($albumpath == "" ) {
	$xmlpath = "photos.xml";
	if (file_exists($xmlpath)) {
		if (isset($_REQUEST["debug"])) echo "\r\n". "processing folder: root \r\n";
		processalbum($xmlpath,$albumpath);
	}

}

if ($albumpath == "all/") {
	$albumpath ="";	$xmlpath = "photos.xml";
	if (file_exists($xmlpath)) {
		processalbum($xmlpath,$albumpath);
	}
	map_dirs(".");

}


function map_dirs($path) {

       if(is_dir($path)) {
               if($contents = opendir($path)) {
                       while(($node = readdir($contents)) !== false) {
				$subalbumfound="n";

				if ($path==".") {
					$folpath = $node."/";
					if (isset($_REQUEST["debug"])) echo "\r\n processing path " . $path . " Node: " . $node;
					if ( is_dir($folpath) && @file_exists($folpath."res/") ) $subalbumfound="y";					
				}
				else {
					$folpath = $path."/".$node."/";
					$folpath = ltrim($folpath,'./');
					if ( is_dir($folpath) && @file_exists($folpath."res/") ) $subalbumfound="y";
				}

			       if( substr($node,0,1)!="."  && substr($node,0,4)!="_vti" && $node!="res" && file_exists($folpath."photos.xml") && $subalbumfound=="n" && $node !="images" && $node != "slides" && $node !="thumbs" && $node !="rss_styles" && $node!= "." && $node!= ".." ) {
						if (isset($_REQUEST["debug"])) echo "\r\n". "processing folder: ".$folpath. "\r\n";
						processalbum($folpath."photos.xml",$folpath);
                                    map_dirs("$path/$node");
                         }

                       }
               }
       }
}



echo("</channel>");
echo("</rss>");


?>


