toDB($_GET['cat']);
	$rss_type 		= intval(varset($_GET['type'],0));
	$topic_id 		= $tp->toDB($_GET['topic'],'');
}
elseif(e_QUERY)
{
	$tmp = explode('.', e_QUERY);
	$content_type 	= $tp->toDB($tmp[0]);
	$rss_type		= intval(varset($tmp[1],0));
	$topic_id 		= $tp->toDB($tmp[2],'');
}
else
{
	$content_type 	= false;
	$topic_id 		= false;
}
// List available rss feeds
if (empty($rss_type))
{	
	// Display list of all feeds
	require_once(HEADERF);
	require_once(e_PLUGIN.'rss_menu/rss_shortcodes.php');
	$sc = e107::getScBatch('rss_menu', true);
	$sc->wrapper('rss/page');
	if(!$sql->select('rss', '*', "`rss_class` = 0 AND `rss_limit` > 0 AND `rss_topicid` NOT REGEXP ('\\\*') ORDER BY `rss_name`"))
	{
		$ns->tablerender(LAN_ERROR, RSS_LAN_ERROR_4);
	}
	else
	{
		if($template = e107::getTemplate('rss_menu', 'rss', 'page'))
		{
			$RSS_LIST_HEADER    = $template['start'];
			$RSS_LIST_TABLE     = $template['item'];
			$RSS_LIST_FOOTER    = $template['end'];
		}
		else
		{
			// Get Legacy template
			if (is_readable(THEME.'rss_template.php'))
			{
				require_once(THEME.'rss_template.php');
			}
			else
			{
				require_once(e_PLUGIN.'rss_menu/rss_template.php');
			}
		}
		$text = $tp->parseTemplate($RSS_LIST_HEADER, true);
		while($row = $sql->fetch())
		{
			$sc->setVars($row);
			$text .= $tp->parseTemplate($RSS_LIST_TABLE, false, $sc);
		}
		$text .= $tp->parseTemplate($RSS_LIST_FOOTER, true);
		$ns->tablerender(RSS_MENU_L2, $text);
	}
 	require_once(FOOTERF);
	exit;
}
	while (ob_get_length() !== false)  // destroy all ouput buffering
	{
        ob_end_clean();
	}
// Returning feeds here
// Conversion table for old urls -------
$conversion[1] 	= 'news';
$conversion[5] 	= 'comments';
$conversion[10] = 'bugtracker';
$conversion[12] = 'download';
//-------------------------------------
// Convert certain old urls so we can check the db entries
// Rss.php?1.2 (news, rss-2) --> check = news (check conversion table)
if(is_numeric($content_type) && isset($conversion[$content_type]) )
{
	$content_type = $conversion[$content_type];
}
$check_topic = ($topic_id ? " AND rss_topicid = '".$topic_id."' " : "");
if(!$sql->select('rss', '*', "rss_class != 2 AND rss_url='".$content_type."' ".$check_topic." AND rss_limit > 0 "))
{	// Check if wildcard present for topic_id
	$check_topic = ($topic_id ? " AND rss_topicid = '".str_replace($topic_id, "*", $topic_id)."' " : "");
	if(!$sql->select('rss', '*', "rss_class != 2 AND rss_url='".$content_type."' ".$check_topic." AND rss_limit > 0 "))
	{
		require_once(HEADERF);
		
		$repl  		= array("
", "");
		$message 	= str_replace(array("[","]"), $repl, RSS_LAN_ERROR_1);
		$ns->tablerender('', $message);
		
		require_once(FOOTERF);
		exit;
	}
	else
	{
		$row = $sql->fetch();
	}
}
else
{
	$row = $sql->fetch();
}
// ----------------------------------------------------------------------------
if($rss = new rssCreate($content_type, $rss_type, $topic_id, $row))
{
	$rss_title = ($rss->contentType ? $rss->contentType : ucfirst($content_type));
	if(E107_DEBUG_LEVEL > 0)
	{
		define('e_IFRAME',true);
		require_once(HEADERF);
		$rss->debug();
		require_once(FOOTERF);
		exit;
	}
	else
	{
		$rss->buildRss($rss_title);
	}
}
else
{
	require_once(HEADERF);
	$ns->tablerender(LAN_ERROR, RSS_LAN_ERROR_1);
	require_once(FOOTERF);
}
class rssCreate
{
	protected $e107;
	var $contentType;
	var $rssType;
	var $path;
	var $parm;
	var $rssItems;
	var $rssQuery;
	var $topicid;
	var $offset;
	var $rssNamespace;
	var $rssCustomChannel;
	public function __construct($content_type, $rss_type, $topic_id, $row)
	{	// Constructor
		$sql_rs = new db;
		global $rssgen;
		$sql = e107::getDb();
		$tp = e107::getParser();
		$this->e107 = e107::getInstance();
		$this -> path = e_PLUGIN."rss_menu/";
		$this -> rssType = $rss_type;
		$this -> topicid = $topic_id;
		$this -> limit = $row['rss_limit'];
		$this -> contentType = $row['rss_name'];
		if(!is_numeric($content_type))
		{
			$path = e_PLUGIN.$row['rss_path'].'/e_rss.php';
		}
		if(strpos($row['rss_path'],'|')!==FALSE) //FIXME remove this check completely. 
		{
			$tmp = explode("|", $row['rss_path']);
			$path = e_PLUGIN.$tmp[0]."/e_rss.php";
			$this->parm = $tmp[1];	// FIXME @Deprecated - use $parm['url'] instead in data() method within e_rss.php.  Parm is used in e_rss.php to define which feed you need to prepare
		}
		switch ($content_type)
		{
			case 'news' :
			case 1:
				$path = e_PLUGIN."news/e_rss.php";
				$this->contentType = "news";
				break;
			case 2:
				$path='';
				$this -> contentType = "articles";
				break;
			case 3:
				$path='';
				$this -> contentType = "reviews";
				break;
			case 4:
				$path='';
				$this -> contentType = "content";
				break;
			case 'comments' : //TODO Eventually move to e107_plugins/comments
			case 5:
				$path='';
				$this -> rssQuery = "SELECT * FROM `#comments` WHERE `comment_blocked` = 0 ORDER BY `comment_datestamp` DESC LIMIT 0,".$this -> limit;
				$sql->gen($this -> rssQuery);
				$tmp = $sql->db_getList();
				$this -> rssItems = array();
				$loop=0;
				foreach($tmp as $value)
				{
					$this -> rssItems[$loop]['title'] = $value['comment_subject'];
					$this -> rssItems[$loop]['pubdate'] = $value['comment_datestamp'];
					switch ($value['comment_type'])
					{
						case 0 :
						case 'news' :
							$this -> rssItems[$loop]['link'] = "http://".$_SERVER['HTTP_HOST'].e_HTTP."comment.php?comment.news.".$value['comment_item_id'];
							break;
						case 2 :
						case 'download' :
							$this -> rssItems[$loop]['link'] = "http://".$_SERVER['HTTP_HOST'].e_HTTP."comment.php?comment.download.".$value['comment_item_id'];
							break;
						case 4:
						case 'poll' :
							$this -> rssItems[$loop]['link'] = "http://".$_SERVER['HTTP_HOST'].e_HTTP."comment.php?comment.poll.".$value['comment_item_id'];
							break;
					}
					$this -> rssItems[$loop]['description'] = $value['comment_comment'];
					$this -> rssItems[$loop]['author'] = substr($value['comment_author'], (strpos($value['comment_author'], ".")+1));
					$loop++;
				}
				break;
			case 6:
			case 7:
				$path = e_PLUGIN."forum/e_rss.php";
				break;
			case 8:
			case 11:
				if(!$this -> topicid)
				{
					return FALSE;
				}
				$path = e_PLUGIN."forum/e_rss.php";
				break;
			// case 10 was bugtracker
			case 'download':
			case 12:
				$path = e_PLUGIN."download/e_rss.php";
				break;
		}
		if(isset($path) && $path!='')
		{	// New rss reader from e_rss.php in plugin folder
			if (is_readable($path))
			{
				require_once($path);
				
				$className = basename(dirname($path)).'_rss';
				
				// v2.x standard 
				if($data = e107::callMethod($className,'data', array('url' => $content_type, 'id' => $this->topicid, 'limit' => $this->limit)))
				{			
					$eplug_rss_data = array(0 => $data);
					unset($data);			
				}
								
				foreach($eplug_rss_data as $key=>$rs)
				{
					foreach($rs as $k=>$row)
					{
						$this -> rssItems[$k]['author'] = $row['author'];
						$this -> rssItems[$k]['author_email'] = $row['author_email'];
						$this -> rssItems[$k]['title'] = $row['title'];
						if($row['link'])
						{
							if(stripos($row['link'], 'http') !== FALSE)
							{
								$this -> rssItems[$k]['link'] = $row['link'];
							}
							else
							{
								$this -> rssItems[$k]['link'] = SITEURLBASE.e_PLUGIN_ABS.$row['link'];
							}
						}
						$this -> rssItems[$k]['description'] = $row['description'];
						
						if($row['enc_url'])
						{
							$this -> rssItems[$k]['enc_url'] = SITEURLBASE.e_PLUGIN_ABS.$row['enc_url'].$row['item_id'];
						}
						
						if($row['enc_leng'])
						{
							$this -> rssItems[$k]['enc_leng'] = $row['enc_leng'];
						}
						if(!empty($eplug_rss['enc_type']))
						{
							$this -> rssItems[$k]['enc_type'] = $this->getmime($eplug_rss['enc_type']);
						}
						elseif($row['enc_type'])
						{
							$this -> rssItems[$k]['enc_type'] = $row['enc_type'];
						}
						$this -> rssItems[$k]['category_name'] = $row['category_name'];
						
						if($row['category_link'])
						{
							if(stripos($row['category_link'], 'http') !== FALSE)
							{
								$this -> rssItems[$k]['category_link'] = $row['category_link'];
							}
							else
							{
								$this -> rssItems[$k]['category_link'] = SITEURLBASE.e_PLUGIN_ABS.$row['category_link'];
							}
						}
						
						if(!empty($row['datestamp']))
						{
							$this -> rssItems[$k]['pubdate'] = $row['datestamp'];
						}
						else
						{
							$this -> rssItems[$k]['pubdate'] = time();
						}
						if($row['custom'])
						{
							$this -> rssItems[$k]['custom'] = $row['custom'];
						}
						if($row['media'])
						{
							$this -> rssItems[$k]['media'] = $row['media'];
						}
					}
				}
			}
		}
	}
	function debug()
	{
		unset($this->e107);
		print_a($this);
	//	print_a($this -> rssItems);
	}
	function buildRss($rss_title)
	{
		global $pref;
		$tp = e107::getParser();
		header('Content-type: application/xml', TRUE);
		$rss_title = $tp->toRss($tp->toHTML($pref['sitename'],'','defs')." : ".$tp->toHTML($rss_title,'','defs'));
        $rss_namespace = ($this->rssNamespace) ? "xmlns:".$this->rssNamespace : '';
        $rss_custom_channel = ($this->rssCustomChannel) ? $this->rssCustomChannel : '';
		$time = time();
		switch ($this -> rssType)
		{
			case 1:		// RSS 1.0
				echo "
						
						
						
						
						".$tp->toRss($rss_title)."
						".$pref['siteurl']."
						".$tp->toRss($pref['sitedescription'])."
						".$itemdate = date("r", ($time))."
						http://backend.userland.com/rss092\n";
					foreach($this -> rssItems as $value)
					{	// Multi-language rss links.
						$link 		= (e_LANQRY) ? str_replace("?","?".e_LANQRY,$value['link']) : $value['link'];
						echo "
							- 
							".$tp->toRss($value['title'])."
							".substr($tp->toRss($value['description']),0,150);
						if($pref['rss_shownewsimage'] == 1 && strlen(trim($value['news_thumbnail'])) > 0)
						{
							$news_thumbnail = SITEURLBASE.e_IMAGE_ABS."newspost_images/".$tp->toRss($value['news_thumbnail']);
							echo "<a href="".$link.""><img src="".$news_thumbnail."" height="50" border="0" hspace="10" vspace="10" align="right"></a>";
							unset($news_thumbail);
						}
						echo "
							".$value['author']."<".$this->nospam($value['author_email']).">
							".$link."
							";
					}
					echo "
						
						";
			break;
			case 2:	// RSS 2.0
				$sitebutton = (strpos(SITEBUTTON, "http:") !== false ? SITEBUTTON : SITEURL.str_replace("../", "", SITEBUTTON));
				echo "
				
				
				
				
				".$tp->toRss($rss_title)."
				".$pref['siteurl']."
				".$tp->toRss($pref['sitedescription'])."\n";
				echo $tp->toHTML($rss_custom_channel,FALSE)."\n"; // must not convert to CDATA.
				echo "
				".CORE_LC.(defined("CORE_LC2") ? "-".CORE_LC2 : "")."
				".$tp->toRss(SITEDISCLAIMER)."
				".$this->nospam($pref['siteadminemail'])." (".$pref['siteadmin'].")
				".$this->nospam($pref['siteadminemail'])." (".$pref['siteadmin'].")
				".date("r",($time))."
				".date("r",($time))."
				http://backend.userland.com/rss
				e107 (https://e107.org)
				hourly
				1
				60";
				echo "
				toRss(e107::url('rss_menu','atom', array('rss_url'=>$this->contentType, 'rss_topicid'=>$this->topicid),'full'))."\" rel=\"self\" type=\"application/rss+xml\" />\n";
				if (trim(SITEBUTTON))
				{
					echo "
					
					".$tp->toRss($rss_title)."
					".(strpos(SITEBUTTON, "http:") !== false ? SITEBUTTON : SITEURL.str_replace("../", "",SITEBUTTON))."
					".$pref['siteurl']."
					88
					31
					".$tp->toRss($pref['sitedescription'])."
					\n";
				}
				// Generally Ignored by 99% of readers.
				/*
				echo "
				
				Search
				Search ".$tp->toRss($pref['sitename'])."
				query
				".SITEURL.(substr(SITEURL, -1) == "/" ? "" : "/")."search.php
				";
				*/
				foreach($this -> rssItems as $value)
				{   // Multi-language rss links.
					$link 		= (e_LANQRY) ? str_replace("?","?".e_LANQRY,$value['link']) : $value['link'];
                    $catlink	= (e_LANQRY) ? str_replace("?","?".e_LANQRY,$value['category_link']) : $value['category_link'];
					echo "
- \n";
					echo "".$tp->toRss($value['title'])."\n";
					if($link)
					{
						echo "".$link."\n";
					}
					echo "".$tp->toRss($value['description'],true). "\n";
					if($value['content_encoded'])
					{
						echo "".$tp->toRss($value['content_encoded'],true)."\n";
					}
					if($value['category_name'] && $catlink)
					{
						echo "".$tp->toRss($value['category_name'])."\n";
					}
					if($value['comment'])
					{
						echo "".$value['comment']."\n";
					}
					if($value['author'])
					{
						echo "".$value['author']."\n"; // correct tag for author without email.
					}
					// Enclosure support for podcasting etc.
					if($value['enc_url'] && $value['enc_leng'] && $value['enc_type'])
					{
						echo "\n";
					}
					echo "".date("r", ($value['pubdate']))."\n";
					if($link)
					{
						echo "".$link."\n";
					}
					if(isset($value['custom'])) // custom tags. (podcasts etc)
					{
						foreach($value['custom'] as $cKey => $cVal)
						{
							echo "<".$cKey.">".$tp->toRss($cVal)."".$cKey.">\n";
						}
					}
					if(!empty($value['media']))
					{
						foreach($value['media'] as $cVal)
						{
							foreach($cVal as $k=>$v)
							{
								echo $this->buildTag($k,$v);
							}
						}
					}
					echo "\n\n";
				}
				// echo " contentType).".4.".$this -> topicId ."\" rel=\"self\" type=\"application/rss+xml\" />";
				echo "
				
				";
			break;
			case 3: 	// RDF
				echo "
				
				
				
				
				".$tp->toRss($rss_title)."
				".$pref['siteurl']."
				".$tp->toRss($pref['sitedescription'])."
				".CORE_LC.(defined("CORE_LC2") ? "-".CORE_LC2 : "")."
				".$this->get_iso_8601_date($time). "
				".$this->nospam($pref['siteadminemail'])."
				
				nospam($pref['siteadminemail'])."\" />
				hourly
				1
				2000-01-01T12:00+00:00
				
				";
				foreach($this -> rssItems as $value)
				{   // Multi-language rss links.
					$link = (e_LANQRY) ? str_replace("?","?".e_LANQRY,$value['link']) : $value['link'];
					echo "
						";
				}
				echo "
				
				
				";
				reset($this -> rssItems);
				unset($link);
				foreach($this -> rssItems as $value)
				{
					$link = (e_LANQRY) ? str_replace("?","?".e_LANQRY,$value['link']) : $value['link']; // Multi-language rss links.
					echo "
- 
						".$tp->toRss($value['title'])."
						".$link."
						".$this->get_iso_8601_date($time)."
						".$value['author']."
						".$tp->toRss($value['category_name'])."
						".$tp->toRss($value['description']). "
						";
				}
				echo "
				";
			break;
			// Atom
			case 4:
				echo "\n
				\n";
				/*
				\n";
				*/
					// Required
					echo "
					".$pref['siteurl']."\n
					".$tp->toRss($rss_title)."\n
					".$this->get_iso_8601_date($time)."\n";
					// Recommended
					echo "
					\n
						e107\n";
						//\n
						echo "
						https://e107.org/\n
					\n
					$this->contentType, 'rss_topicid'=>$this->topicid),'full'))."' />\n";
					// Optional
				//	include(e_ADMIN."ver.php");
					echo "
					\n
					\n
						e107\n
					\n
					e107\n";
					///icon.jpg\n
					echo "
					".(strpos(SITEBUTTON, "http:") !== false ? SITEBUTTON : SITEURL.str_replace("../", "", SITEBUTTON))."\n
					".$pref['siteadmin']." - ".$this->nospam($pref['siteadminemail'])."\n";
					if($pref['sitedescription']){
					echo "
					".$pref['sitedescription']."\n";
                    }
					foreach($this -> rssItems as $value) {
					echo "
					\n";
						// Required
						echo "
						".$value['link']."\n
						".$tp->toRss($value['title'])."\n
						".$this->get_iso_8601_date($value['pubdate'])."\n";
						// Recommended
                        $author = ($value['author']) ? $value['author'] : "unknown";
						echo "
						\n";
						echo "
						".$author."\n";
						echo ($value['author_email']) ? "\t\t\t\t\t\t".$this->nospam($value['author_email'])."\n" : "";
						echo "\n";
						//complete story here\n
						echo "
						\n
						".$tp->toRss($tp->toText($value['description'])). "\n";
						// Optional
						if(!empty($value['category_name']))
						{
							echo "\n";
						}
						//
						//	Jane Doe
						//
						echo "".$this->get_iso_8601_date($value['pubdate'])."\n";
						//
						//	http://example.org/
						//	Fourty-Two
						//	2003-12-13T18:30:02Z
						//	© 2005 Example, Inc.
						//
						//© 2005 John Doe
						echo "
					\n";
					}
				echo "
				\n";
			break;
		}
	}
	/**
	 * Build an XML Tag
	 * @param string $name
	 * @param array $attributes
	 * @param bool $closing
	 * @return string
	 */
	function buildTag($name='', $attributes=array())
	{
		$tp = e107::getParser();
		if(empty($name))
		{
			return '';
		}
		if(isset($attributes['value']))
		{
			$value = $attributes['value'];
			unset($attributes['value']);
		}
		$text = "\n<".$name;
		foreach($attributes as $att=>$attVal)
		{
			$text .= " ".$att."=\"".$tp->toRss($attVal)."\"";
		}
		$text .= ">";
		if(!empty($value))
		{
			if(is_array($value))
			{
				foreach($value as $t=>$r)
				{
					$text .= $this->buildTag($t,$r);
				}
			}
			else
			{
				$text .= $tp->toRss($value);
			}
		}
		$text .= "".$name.">\n";
		return $text;
	}
	function getmime($file)
	{
		$ext = strtolower(str_replace(".","",strrchr(basename($file), ".")));
		$mime["mp3"] = "audio/mpeg";
		return $mime[$ext];
	}
	function get_iso_8601_date($int_date)
	{	//$int_date: current date in UNIX timestamp
		$date_mod = date('Y-m-d\TH:i:s', $int_date);
		$pre_timezone = date('O', $int_date);
		$time_zone = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
		$date_mod .= $time_zone;
		return $date_mod;
	}
	function nospam($text)
	{
		$tmp = explode("@",$text);
		return ($tmp[0] != "") ? $tmp[0].RSS_LAN_2 : RSS_LAN_3;
	}
} // End class rssCreate