<?php
/*
* Feed Generator code
*
* Web Traffic Genius Pro v3.5.4
* Copyright (c) 2008-2010
* Success on the Internet Pty Ltd
* PO Box 25
* Salisbury SA 5108
* Australia
* Phone: +61 422 512 549
* Fax: +61 8 8425 9657
* Web: http://www.webtrafficgenius.com
* Support: http://www.marketing-assassins.com
*
*/

function wtg_dump_feed($postID) {

	global $logger;

	// Get feed type
	$wtg_option = get_option('wtg_option');
	$feed_type = empty($wtg_option['feedType'])?'rss':$wtg_option['feedType'];

	if (empty($wtg_option['feedDir'])) return false;
	// $feed_absdir = wtg_detect_doc_root() . '/' . $wtg_option['feedDir'] . '/';
	if(wtg_path_is_absolute($wtg_option['feedDir'])) {
		$feed_absdir = $wtg_option['feedDir'] . '/';
	} else {
		$feed_absdir = wtg_detect_doc_root() . '/' . $wtg_option['feedDir'] . '/';
	}

	// Generate feed file according to feed type
	$feed_content = '';
	if ($feed_type == 'rss2') {
		$feed_content = wtg_generate_feed_rss2($postID);
	} elseif ($feed_type == 'atom') {
		$feed_content = wtg_generate_feed_atom($postID);
	} else {
		$feed_content = wtg_generate_feed_rss($postID);
	}

	if (empty($feed_content)) {
		$logger->error("Generate feed content. FAIL skip");
		return false;
	}

	// Generate feed name - top1
	$feed_name = wtg_generate_feed_name($postID, $feed_type);

	// Dump it
	if (file_put_contents($feed_absdir . $feed_name, $feed_content)) {
		$logger->info("Dump feed of the post.(feed_path=[" . $feed_absdir . "$feed_name]) SUCCESS");
		return $feed_name;
	}
	$logger->error("Dump feed of the post.(feed_path=[" . $feed_absdir . "$feed_name]) FAIL");
	return false;
}

function wtg_generate_feed_name($postID, $feed_type) {
	$post = get_post($postID);
	$feed_url = sanitize_title_with_dashes($post->post_title);
	$feed_url.='-' . $postID . '.xml';
	return $feed_url;
	
	//return $postID . '_' . $feed_type . '_' . current_time('timestamp') . '.xml';
	//	$post = get_post($postID);
	//	sanitize_title_with_dashes($post->post_title)
}



function wtg_generate_feed_rss2($postId) {
	// check feed submission is allow for page submission
	$postType = get_post_type( $postId );
	if($postType == 'page' && defined('WTG_FEED_PAGE_SUBMISSION') && WTG_FEED_PAGE_SUBMISSION) {
		query_posts(array('page_id' => $postId));
	} else {
		query_posts(array('p' => $postId));
	}
	
	if ( have_posts()) {
		the_post();
	} else 
		return false;
		$postlnk = get_permalink($postId);
		
	ob_start();
	echo '<?xml version="1.0" encoding="iso-8859-1"?'.'>'; ?>

<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
>
	<channel>
		<title><?php the_title_rss() ?></title>
		<atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" />
		<?php if (trim($postlnk) == "" ) : ?>
			<link><?php the_guid(); ?></link>
		<?php else : ?>
			<link><?php echo $postlnk; ?></link>
		<?php endif; ?>
			<description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
			<pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></pubDate>
		<?php the_generator( 'rss2' ); ?>
		<language><?php echo get_option('rss_language'); ?></language>
		<item>
			<title><?php the_title_rss() ?></title>
		<?php if (trim($postlnk) == "" ) : ?>
			<link><?php the_guid(); ?></link>
		<?php else : ?>
			<link><?php echo $postlnk; ?></link>
		<?php endif; ?>
			<pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate>
			<dc:creator><?php the_author() ?></dc:creator>
			<?php the_category_rss() ?>
			<guid isPermaLink="false"><?php the_guid(); ?></guid>
	<?php if (get_option('rss_use_excerpt')) : ?>
			<description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
	<?php else : ?>
			<description><![CDATA[<?php echo htmlspecialchars(get_the_content()) ?><?php wtg_get_related_posts ($postId);?>]]></description>
			<?php if ( strlen( $post->post_content ) > 0 ) : ?>
			<content:encoded><![CDATA[<?php echo preg_replace('/[^a-z0-9!, \.]/i', '',htmlentities(get_the_content())); ?>]]></content:encoded>
		<?php else : ?>
			<content:encoded><![CDATA[<?php the_excerpt_rss() ?>]]></content:encoded>
		<?php endif; ?>
	<?php endif; ?>
	<?php //rss_enclosure(); ?>
		</item>
	<?php echo wtg_generate_extrafeeds(2); ?>
	</channel>
</rss>
	<?php
	$feed_content = ob_get_contents();
	ob_end_clean();
	return $feed_content;
}

function wtg_generate_feed_atom($postId){
	// check feed submission is allow for page submission
	$postType = get_post_type( $postId );
	if($postType == 'page' && defined('WTG_FEED_PAGE_SUBMISSION') && WTG_FEED_PAGE_SUBMISSION) {
		query_posts(array('page_id' => $postId));
	} else {
		query_posts(array('p' => $postId));
	}
	
	if ( have_posts()) {
		the_post();
	} else 
		return false;
		$postlnk = get_permalink($postId);
		
		ob_start();
?>
<?php echo '<?xml version="1.0" encoding="iso-8859-1"?'.'>'; ?>
<feed
  xmlns="http://www.w3.org/2005/Atom"
  xmlns:thr="http://purl.org/syndication/thread/1.0"
  xml:lang="<?php echo get_option('rss_language'); ?>"
  xml:base="<?php self_link(); ?>"
 >
	<title type="text"><![CDATA[<?php the_title_rss() ?>]]></title>
	<updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT')); ?></updated>
	<?php the_generator( 'atom' ); ?>
	<link rel="alternate" type="text/html" href="<?php the_guid(); ?>" />
	<id><?php self_link(); ?></id>
	<link rel="self" type="application/atom+xml" href="<?php self_link(); ?>" />
	<entry>
		<author>
			<name><?php the_author() ?></name>
			<?php $author_url = get_the_author_url(); if ( !empty($author_url) ) : ?>
			<uri><?php the_author_url()?></uri>
			<?php endif; ?>
		</author>
		<title type="<?php html_type_rss(); ?>"><![CDATA[<?php the_title_rss() ?>]]></title>
		<?php if (trim($postlnk) == "" ) : ?>
			<link rel="alternate" type="text/html" href="<?php the_guid(); ?>" />
		<?php else : ?>
			<link rel="alternate" type="text/html" href="<?php echo $postlnk; ?>" />
		<?php endif; ?>
		
		<id><?php the_guid(); ?></id>
		<updated><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></updated>
		<published><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></published>
		<?php the_category_rss('atom') ?>
		<summary type="<?php html_type_rss(); ?>"><![CDATA[<?php the_excerpt_rss(); ?>]]></summary>
<?php if ( !get_option('rss_use_excerpt') ) : ?>
		<content type="<?php html_type_rss(); ?>" xml:base="<?php the_permalink_rss() ?>"><![CDATA[<?php the_content('', 0, '') ?>]]></content>
<?php endif; ?>
<?php atom_enclosure(); ?>
	</entry>
</feed>
	<?php
	$feed_content = ob_get_contents();
	ob_end_clean();
	return $feed_content;
}


function wtg_generate_feed_rss($postId){
	// check feed submission is allow for page submission
	$postType = get_post_type( $postId );
	if($postType == 'page' && defined('WTG_FEED_PAGE_SUBMISSION') && WTG_FEED_PAGE_SUBMISSION) {
		query_posts(array('page_id' => $postId));
	} else {
		query_posts(array('p' => $postId));
	}
	
	if ( have_posts()) {
		the_post();
	} else
		return false;
		$postlnk = get_permalink($postId);
	ob_start();
?>
<?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
<?php the_generator( 'comment' ); ?>
<rss version="0.92">
	<channel>
		<title><![CDATA[<?php the_title_rss(); ?>]]></title>
		<?php if (trim($postlnk) == "" ) : ?>
			<link><?php the_guid(); ?></link>
		<?php else : ?>
			<link><?php echo $postlnk; ?></link>
		<?php endif; ?>
		<description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
		<lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate>
		<docs>http://backend.userland.com/rss092</docs>
		<?php the_generator( 'rss2' ); ?>
		<language><?php echo get_option('rss_language'); ?></language>
		<item>
			<title><![CDATA[<?php the_title_rss() ?>]]></title>
			<pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate>
	<?php if (get_option('rss_use_excerpt')) { ?>
			<description><![CDATA[<?php the_excerpt_rss() ?><?php wtg_get_related_posts ($postId);?>]]></description>
	<?php } else { // use content ?>
			<description><?php 
			//echo htmlspecialchars(get_the_content('', 0, '', get_option('rss_excerpt_length'))); 
			/*$wtg_option = get_option('wtg_option');
			if($wtg_option['feed_length'] == 1) {
				echo htmlspecialchars(wtg_excerpts($postId));
			} else {
				echo htmlspecialchars(get_the_content('', 0, '', get_option('rss_excerpt_length'))); 
			}*/
			the_excerpt_rss();
			?>
			<?php wtg_get_related_posts ($postId); ?>
			</description>
	<?php } ?>
		<?php if (trim($postlnk) == "" ) : ?>
			<link><?php the_guid(); ?></link>
		<?php else : ?>
			<link><?php echo $postlnk; ?></link>
		<?php endif; ?>
		</item>
	<?php echo wtg_generate_extrafeeds(1); ?>
    </channel>
</rss>
	<?php
	$feed_content = ob_get_contents();
	ob_end_clean();
	return $feed_content;
}

function wtg_dump_page_feed($pageID) {
	global $logger;

	// Get feed type
	$wtg_option = get_option('wtg_option');

	if (empty($wtg_option['feedDir'])) return false;
	if(wtg_path_is_absolute($wtg_option['feedDir'])) {
		$feed_absdir = $wtg_option['feedDir'] . '/';
	} else {
		$feed_absdir = wtg_detect_doc_root() . '/' . $wtg_option['feedDir'] . '/';
	}

	// Generate feed file according to feed type
	$feed_content = "";
	$feed_content = wtg_do_feed_page($pageID);

	if (empty($feed_content)) {
		$logger->error("Generate feed content. FAIL skip");
		return false;
	}
	
	// Generate feed name - top1
	$feed_name = wtg_generate_page_feed_name($pageID);
	
	// Dump it
	if (file_put_contents($feed_absdir . $feed_name, $feed_content)) {
		//$logger->info("Dump feed of the post.(feed_path=[" . $feed_absdir . "$feed_name]) SUCCESS");
		return $feed_name;
	}
	//$logger->error("Dump feed of the post.(feed_path=[" . $feed_absdir . "$feed_name]) FAIL");
	return false;
}

function wtg_generate_page_feed_name($pageID) {
	$page = get_page($pageID);
	$feed_url = sanitize_title_with_dashes($page->post_title);
	$feed_url.='-' . $pageID . '.xml';
	return $feed_url;
}

function wtg_do_feed_page($pid) {
	//header('Content-Type: text/xml; charset=' . get_option('blog_charset'), true);
	if (is_numeric($pid ) && !empty($pid)) {
		$pid = mysql_escape_string($pid);
		$pages = get_pages(array('child_of'=>$pid,'sort_order'=>'DESC'));
	}
	
	//echo "<pre>";print_r($page);echo "</pre>";
	ob_start();

echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
<?php the_generator( 'comment' ); ?>
<rss version="0.92">
	<channel>
		<title><![CDATA[<?php bloginfo_rss('name').wp_title_rss(); ?>]]></title>
		<link><![CDATA[<?php echo bloginfo_rss('url') ?>]]></link>
		<description><?php echo bloginfo_rss('description') ?></description>
		<lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate>
		<docs>http://backend.userland.com/rss092</docs>
		<language><?php echo get_option('rss_language'); ?></language>		
		<?php foreach($pages as $page) { ?>
			<item>
			<title><?php echo $page->post_title?></title>
			<description><![CDATA[<?php echo $page->post_content?>]]></description>
			<link><?php echo get_permalink($page->ID); ?></link>
			<?php do_action('rss_item'); ?>
			</item>
		<?php } ?>
		<?php echo wtg_generate_extrafeeds(1); ?>
	</channel>
</rss>

	<?php
	$feed_content = ob_get_contents();
	ob_end_clean();
	return $feed_content;
}

function wtg_detect_doc_root() {
	if (!empty($_SERVER['DOCUMENT_ROOT'])) {
		return $_SERVER['DOCUMENT_ROOT'];
	}
}

function wtg_detect_site_name() {
	/* The $_SERVER['SERVER_NAME'] is affected by client request's header, sometimes it returns wrong server name.
	if (!empty($_SERVER['SERVER_NAME'])) {
		return 'http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"];
	}
	*/
	// Use Wordpress' site url set in option page.
	$u = @parse_url(get_option('siteurl'));
	return 'http://' . $u['host'] . ':' . (isset($u['port'])?$u['port']:80);

}

function wtg_generate_extrafeeds($ver=2){
	$wtg_option = get_option('wtg_option');
	$result=' ';
	if(!$wtg_option['extrafeeds']) {
		return $result;
	}
	$min=empty($wtg_option['minextrafeed'])?0: $wtg_option['minextrafeed'];
	$max=empty($wtg_option['maxextrafeed'])?0: $wtg_option['maxextrafeed'];
	//srand(floor(time() / (60*60*24)));
	$maxextrafeed = rand($min, $max);
	$ag = new WTG_Extrafeed();
	$ag->initDB();
    $extrafeeds_list = $ag->get_all_extrafeedsDB();
    //randomizes the order of the elements in extrafeeds_list array
    shuffle($extrafeeds_list);
	$count=0;
	foreach ($extrafeeds_list as $extrafeed) {
		if($count >= $maxextrafeed) {
			break;
		}
	
		$extrafeed->title=wtg_spin_text($extrafeed->title);
		ob_start();?>
        <item>
            <title><?php echo $extrafeed->title; ?></title>
			<link><?php echo htmlentities($extrafeed->url); ?></link>
		<?php if ($ver==2) { ?>
            <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate>
            <dc:creator><?php the_author() ?></dc:creator>
			<?php the_category_rss() ?>
            <guid isPermaLink="false"><?php echo htmlentities($extrafeed->url); ?></guid>
		<?php } ?>
            <description><![CDATA[<?php echo preg_replace('/[^a-z0-9!, \.]/i', '', wtg_spin_text($extrafeed->desc)); ?>]]></description>
		<?php if($ver==2) { ?>
            <content:encoded><![CDATA[<?php echo preg_replace('/[^a-z0-9!, \.]/i', '', wtg_spin_text($extrafeed->desc)); ?>]]></content:encoded>
		<?php } ?>
		<?php //rss_enclosure(); ?>
        </item>
	<?php
		$result.= ob_get_contents();
		ob_end_clean();
		$count=$count+1;
	}
	return $result;
}

function wtg_get_related_posts ($postId) {
	$wtg_option = get_option('wtg_option');
	if (isset($wtg_option['wtg_related_posts']))
		$wtg_related_posts = $wtg_option['wtg_related_posts'];
	else $wtg_related_posts = WTG_RELATED_POSTS_DEFAULT;
	
	if(defined('WTG_RELATED_POSTS_DEFAULT') && WTG_RELATED_POSTS_DEFAULT) {
		//for use in the loop, list 5 post titles related to first tag on current post
		$tags = wp_get_post_tags($postId);
		if ($tags) {
		  $first_tag = $tags[0]->term_id;
		  $args=array(
			'tag__in' => array($first_tag),
			'post__not_in' => array($postId),
			'showposts' => $wtg_related_posts,
			'caller_get_posts'=>1
		   );
		  $my_query = new WP_Query($args);
		  if( $my_query->have_posts() ) {
			echo '&lt;p&gt;Related Posts:';
			echo '&lt;ol&gt;';
			while ($my_query->have_posts()) : $my_query->the_post(); ?>
				&lt;li&gt;&lt;a href=&quot;<?php the_permalink() ?>&quot; rel=&quot;bookmark&quot; title=&quot;Permanent Link to <?php the_title_attribute(); ?>&quot;&gt;<?php the_title(); ?>&lt;/a&gt;&lt;/li&gt;
			  <?php
			endwhile;
			echo '&lt;/ol&gt;';
			echo '&lt;/p&gt;';
		  }
		}
	}
}

function wtg_spin_text($string){
	preg_match('#\{(.+?)\}#is',$string,$match);
	if(empty($match)) return $string;

	$temp = $match[1];

	if(strpos($temp,'{')!==false){
		$temp = substr($temp, strrpos($temp,'{') + 1);
	}
	$parts = explode("|", $temp);

	$string = preg_replace("+\{".preg_quote($temp)."\}+is", $parts[array_rand($parts)], $string, 1);

	return wtg_spin_text($string);
}

function wtg_excerpts($postId) {
	$wtg_option = get_option('wtg_option');
	if (isset($wtg_option['wtg_summarized_feed']))
		$wtg_summarized_feed = $wtg_option['wtg_summarized_feed'];
	else $wtg_summarized_feed = WTG_SUMMARIZED_FEED_DEFAULT;
	
	$post = get_post($postID);
    $content = $post->post_excerpt;
    $content = $post->post_content;
	$words = explode(' ', $content, $wtg_summarized_feed + 1);
	if(count($words) > $wtg_summarized_feed) {
		array_pop($words);
		array_push($words, '[...]');
		$content = implode(' ', $words);
	}
    return $content;
}