<?php
defined('PRODUCT_NAME') or die;
class RSSFeedModule extends ModuleInstance
{
	public function __construct()
	{
		parent::__construct();

		$this->cache_config->enabled = false;
	}

	function render()
	{
		include_once("lastrss/lastRSS.php");

		$title 					= $this->setting("title");
		$title_heading_level 	= $this->setting("title_heading_level");
		$module_class 			= $this->setting("module_class");
		$num_articles 			= $this->setting("num_articles");

		// Create lastRSS object
		$rss = new lastRSS;
		$rss->cache_dir = 'modules/rss/lastrss/cache'; //path to cache directory on your server relative to scrollerbridge.php. Chmod 777!
		$rss->date_format = 'M d, Y g:i:s A'; //date format of RSS item. See PHP date() function for possible input.
		$rss->cache_time = 1800; //Global cache time before fetching RSS feed again, in seconds.

		// Define your list of RSS URLs- "RSS_id"=> "URL to RSS feed"
		$rsslist = array(
						$this->setting("rss1"),
						$this->setting("rss2"),
						$this->setting("rss3"),
						$this->setting("rss4"),
						$this->setting("rss5")
						);

		?>
		<div id="module_<?php echo($this->module_instance_id); ?>" class="module rss-module <?php echo($module_class); ?>">
			<?php
			if($title && $title_heading_level)
			{
				?><<?php echo($title_heading_level); ?> class="module-title"><?php echo($title); ?></<?php echo($title_heading_level); ?>><?php
			}

			foreach($rsslist as $rssurl)
			{
				if(!$rssurl)
				{
					continue;
				}

				$rs = $rss->get($rssurl);

				if($rs['items_count'] > 0)
				{
					$count = 0;

					if($rs['title'])
					{
						?><div class="rss-feed"><h3 class="rss-title"><?php echo $this->strip_cdata($rs['title'])?></h3><?php
					}
					else
					{
						?><div class="rss-feed"><?php
					}

					foreach ($rs['items'] as $item)
					{
						?>
						<h4 class="rss-headline"><a href="<?php echo $this->strip_cdata($item["link"])?>" target="_blank"><?php echo $this->strip_cdata($item["title"])?></a></h4>
						<h4 class="rss-date"><?php echo $this->strip_cdata($item["pubDate"])?></span></h4>
						<div class="rss-article"><?php echo $this->strip_cdata($item["description"])?></div>
						<div class="rss-read-more"><a href="<?php echo $this->strip_cdata($item["link"])?>" target="_blank">Read More</a></div>
						<?php

						$count ++;

						if($count == $num_articles)
						{
							break;
						}
					}

					?></div><?php
				}
			}
			?>
		</div>
		<?php
	}

	function strip_cdata($string)
	{
	    preg_match_all('/<!\[cdata\[(.*?)\]\]>/is', $string, $matches);
	    return html_entity_decode(strip_tags(str_replace($matches[0], $matches[1], $string)));
	}
}
