<?php
/*
License:
 ==============================================================================

    Copyright 2006  Dan Kuykendall  (email : dan@kuykendall.org)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-107  USA
*/
	class podPress_class {
		var $settings = array();

		// Global hardcoded settings
		var $podcastTag_regexp   = "/\[podcast:([^]]+)]/";
		var $podcastTag          = '[display_podcast]';
		var $podtrac_url         = 'http://www.podtrac.com/pts/redirect.mp3/';
		var $requiredAdminRights = 'level_7';
		var $realm               = 'Premium Subscribers Content';
		var $justposted          = false;
		var $tempFileSystemPath  = '';
		var $tempFileURLPath     = '';
		var $tempContentAddedTo  = array();

		/*************************************************************/
		/* Load up the plugin values and get ready to action         */
		/*************************************************************/

		function podPress_class() {
			// Make sure some standard values are set.
			$x = get_option('rss_language');
			if(!$x || empty($x))
			{
				add_option('rss_language', 'en_us');
			}

			$x = get_option('rss_image');
			if(!$x || empty($x))
			{
				podPress_update_option('rss_image', podPress_url().'images/powered_by_podpress.jpg');
			}

			// load up podPress general config
			$this->settings = podPress_get_option('podPress_config');
			if(!is_array($this->settings)) {
				$this->settings = array();
			}

			if($this->settings['compatibilityChecks']['themeTested'] !== true) {
				$this->settings['compatibilityChecks']['themeTested'] = false;
			}

			if($this->settings['compatibilityChecks']['wp_head'] !== true) {
				$this->settings['compatibilityChecks']['wp_head'] = false;
			}
			if($this->settings['compatibilityChecks']['wp_footer'] !== true) {
				$this->settings['compatibilityChecks']['wp_footer'] = false;
			}

			if(!is_bool($this->settings['enableStats'])) {
				if($this->settings['enableStats']== 'true') {
					$this->settings['enableStats'] = true;
				} else {
					$this->settings['enableStats'] = false;
				}
			}

			if(!is_bool($this->settings['enableStats'])) {
				if($this->settings['enableStats']== 'true') {
					$this->settings['enableStats'] = true;
				} else {
					$this->settings['enableStats'] = false;
				}
			}

			if(!$this->settings['statMethod'] || empty($this->settings['statMethod']) || $this->settings['statMethod'] == 'htaccess')
			{
				$this->settings['statMethod'] = 'permalinks';
			}

			if(!$this->settings['statLogging'] || empty($this->settings['statLogging']))
			{
				$this->settings['statLogging'] = 'Counts';
			}

			if(!is_bool($this->settings['enablePodTracStats'])) {
				if($this->settings['enablePodTracStats']== 'true') {
					$this->settings['enablePodTracStats'] = true;
				} else {
					$this->settings['enablePodTracStats'] = false;
				}
			}

			if(!is_bool($this->settings['enableMobatalkAudioComments'])) {
				if($this->settings['enableMobatalkAudioComments']== 'true') {
					$this->settings['enableMobatalkAudioComments'] = true;
				} else {
					$this->settings['enableMobatalkAudioComments'] = false;
				}
			}

			if(!$this->settings['rss_copyright'] || empty($this->settings['rss_copyright']))
			{
				$this->settings['rss_copyright'] = '2006-2007';
			}

			if(!$this->settings['mobatalkID'] || empty($this->settings['mobatalkID']))
			{
				$this->settings['mobatalkID'] = '352';
			}

			if(podPress_WPVersionCheck('2.0.0')) {
				if(!is_bool($this->settings['enablePremiumContent'])) {
					if($this->settings['enablePremiumContent']== 'true') {
						$this->settings['enablePremiumContent'] = true;
					} else {
						$this->settings['enablePremiumContent'] = false;
					}
				}
			} else {
				$this->settings['enablePremiumContent'] = false;
			}

			if(empty($this->settings['premiumMethod'])) {
				$this->settings['premiumMethod'] = 'Digest';
			}
			if(!defined('PODPRESS_PREMIUM_METHOD')) {
				define('PODPRESS_PREMIUM_METHOD', $this->settings['premiumMethod']);
			}

			if(!is_bool($this->settings['enableTorrentCasting'])) {
				if($this->settings['enableTorrentCasting']== 'true') {
					$this->settings['enableTorrentCasting'] = true;
				} else {
					$this->settings['enableTorrentCasting'] = false;
				}
			}

			if(empty($this->settings['podcastFeedURL'])) {
				if(podPress_WPVersionCheck('2.1')) {
					$this->settings['podcastFeedURL'] = get_settings('siteurl').'/?feed=podcast';
				} else {
					$this->settings['podcastFeedURL'] = get_settings('siteurl').'/?feed=rss2';
				}
			}

			if(empty($this->settings['mediaWebPath'])) {
				$this->settings['mediaWebPath'] = get_settings('siteurl').'/wp-content/uploads';
			}

			unset($this->settings['autoDetectedMediaFilePath']);
			if(!file_exists($this->settings['mediaFilePath'])) {
				$this->settings['autoDetectedMediaFilePath'] = str_replace(get_settings('siteurl'), '', $this->settings['mediaWebPath']);
				$this->settings['autoDetectedMediaFilePath'] = ABSPATH.$this->settings['autoDetectedMediaFilePath'];
				if(!file_exists($this->settings['autoDetectedMediaFilePath'])) {
					$this->settings['autoDetectedMediaFilePath'] .= ' (Auto Detection Failed.)';
				}
			}

			if(empty($this->settings['maxMediaFiles']) || $this->settings['maxMediaFiles'] < 1) {
				$this->settings['maxMediaFiles'] = 5;
			}

			if(!$this->settings['contentBeforeMore'] || empty($this->settings['contentBeforeMore']))
			{
				$this->settings['contentBeforeMore'] = 'yes';
			}

			if(!$this->settings['contentLocation'] || empty($this->settings['contentLocation']))
			{
				$this->settings['contentLocation'] = 'end';
			}

			if(!$this->settings['contentImage'] || empty($this->settings['contentImage']))
			{
				$this->settings['contentImage'] = 'button';
			}

			if(!$this->settings['contentPlayer'] || empty($this->settings['contentPlayer']))
			{
				$this->settings['contentPlayer'] = 'both';
			}

			if(empty($this->settings['videoPreviewImage'])) {
				$this->settings['videoPreviewImage'] = podPress_url().'images/vpreview_center.png';
			}

			if(!is_bool($this->settings['disableVideoPreview'])) {
				if($this->settings['disableVideoPreview']== 'true') {
					$this->settings['disableVideoPreview'] = true;
				} else {
					$this->settings['disableVideoPreview'] = false;
				}
			}

			if(!$this->settings['contentDownload'] || empty($this->settings['contentDownload']))
			{
				$this->settings['contentDownload'] = 'enabled';
			}

			if(!$this->settings['contentDownloadText'] || empty($this->settings['contentDownloadText']))
			{
				$this->settings['contentDownloadText'] = 'enabled';
			}

			if(!$this->settings['contentDownloadStats'] || empty($this->settings['contentDownloadStats']))
			{
				$this->settings['contentDownloadStats'] = 'enabled';
			}

			if(!$this->settings['contentDuration'] || empty($this->settings['contentDuration']))
			{
				$this->settings['contentDuration'] = 'enabled';
			}

			if(!is_bool($this->settings['contentAutoDisplayPlayer'])) {
				if($this->settings['contentAutoDisplayPlayer'] == 'false') {
					$this->settings['contentAutoDisplayPlayer'] = false;
				} else {
					$this->settings['contentAutoDisplayPlayer'] = true;
				}
			}

			if(!is_bool($this->settings['enableFooter'])) {
				if($this->settings['enableFooter']== 'false') {
					$this->settings['enableFooter'] = false;
				} else {
					$this->settings['enableFooter'] = true;
				}
			}

			if($this->settings['player']['bg'] == '') {
				$this->resetPlayerSettings();
			}

			if(empty($this->settings['iTunes']['summary'])) {
				$this->settings['iTunes']['summary'] = stripslashes(get_option('blogdescription'));
			} else {
				$this->settings['iTunes']['summary'] = stripslashes($this->settings['iTunes']['summary']);
			}
			$this->settings['iTunes']['keywords'] = stripslashes($this->settings['iTunes']['keywords']);
			$this->settings['iTunes']['subtitle'] = stripslashes($this->settings['iTunes']['subtitle']);
			$this->settings['iTunes']['author'] = stripslashes($this->settings['iTunes']['author']);

			$this->settings['iTunes']['FeedID'] = stripslashes($this->settings['iTunes']['FeedID']);
			$this->settings['iTunes']['FeedID'] = str_replace(' ', '', $this->settings['iTunes']['FeedID']);
			if(!is_numeric($this->settings['iTunes']['FeedID'])) {
				$this->settings['iTunes']['FeedID'] = settype($this->settings['iTunes']['FeedID'], 'double');
			}

			if(empty($this->settings['iTunes']['explicit'])) {
				$this->settings['iTunes']['explicit'] = 'No';
			}

			if(empty($this->settings['iTunes']['image'])) {
				$x = get_option('rss_image');
				if(isset($x) && $x != podPress_url().'images/powered_by_podpress.jpg') {
					$this->settings['iTunes']['image'] = $x;
				} else {
					$this->settings['iTunes']['image'] = podPress_url().'images/powered_by_podpress_large.jpg';
				}
			}

			if(empty($this->settings['iTunes']['new-feed-url'])) {
				$this->settings['iTunes']['new-feed-url'] = 'Disable';
			}
			//$this->feed_getCategory();
			$this->tempFileSystemPath = ABSPATH.get_option('upload_path').'/podpress_temp';
			$this->tempFileURLPath = get_settings('siteurl').'/'.get_option('upload_path').'/podpress_temp';
		}

		/*************************************************************/
		/* Handle all the default values for a new install of plugin */
		/*************************************************************/
		function activate() {
			GLOBAL $wpdb;
			$current = get_option('podPress_version');
			if(!$current) {
				$current = 0;
			}

			if(function_exists('get_role')) {
				$ps_role = get_role('premium_subscriber');
				if(!$ps_role) {
					add_role('premium_subscriber', 'Premium Subscriber', $caps);
					$ps_role = get_role('premium_subscriber');
				}
				$ps_role = get_role('premium_subscriber');
				if(!$ps_role->has_cap('premium_content')) {
					$ps_role->add_cap('premium_content');
				}
				if(!$ps_role->has_cap('read')) {
					$ps_role->add_cap('read');
				}
				$role = get_role('administrator');
				if(!$role->has_cap('premium_content')) {
					$role->add_cap('premium_content');
				}
			}

			// Create stats table
			$create_table = "CREATE TABLE ".$wpdb->prefix."podpress_statcounts (".
			                "postID int(11) NOT NULL default '0',".
			                "media varchar(255) NOT NULL,".
			                "total int(11) default '1',".
			                "feed int(11) default '0',".
			                "web int(11) default '0',".
			                "play int(11) default '0',".
			                "PRIMARY KEY (media)) TYPE=MyISAM;";
			podPress_maybe_create_table($wpdb->prefix."podpress_statcounts", $create_table);

			// Create stats table
			$create_table = "CREATE TABLE ".$wpdb->prefix."podpress_stats (".
			                "id int(11) unsigned NOT NULL auto_increment,".
			                "postID int(11) NOT NULL default '0',".
			                "media varchar(255) NOT NULL default '',".
			                "method varchar(50) NOT NULL default '',".
			                "remote_ip varchar(15) NOT NULL default '',".
			                "country varchar(50) NOT NULL default '',".
			                "language VARCHAR(5) NOT NULL default '',".
			                "domain varchar(255) NOT NULL default '',".
			                "referer varchar(255) NOT NULL default '',".
			                "resource varchar(255) NOT NULL default '',".
			                "user_agent varchar(255) NOT NULL default '',".
			                "platform varchar(50) NOT NULL default '',".
			                "browser varchar(50) NOT NULL default '',".
			                "version varchar(15) NOT NULL default '',".
			                "dt int(10) unsigned NOT NULL default '0',".
			                "UNIQUE KEY id (id)) TYPE=MyISAM;";
			podPress_maybe_create_table($wpdb->prefix."podpress_stats", $create_table);
			$create_table = "ALTER TABLE ".$wpdb->comments." ADD COLUMN comment_enclosure text NULL;";
			podPress_maybe_add_column($wpdb->comments, 'comment_enclosure', $create_table);

			if(function_exists('wp_cache_flush')) {
				wp_cache_flush();
			}

			if($current == 0) {
				$current = PODPRESS_VERSION;
				add_option('podPress_version', $current);
			}

			$x = podPress_get_option('podPress_config');
			if($x['mediaWebPath'] == '') {
				$x['mediaWebPath'] = get_settings('siteurl').'/wp-content/uploads';
			}
			if($x['mediaFilePath'] == '') {
				$x['mediaFilePath'] = ABSPATH.'/wp-content/uploads';
			}
			if(!is_array($x['player']) || $x['player']['bg'] == '') {
				$x['player'] = $this->resetPlayerSettings();
			}

			podPress_update_option('podPress_config', $x);
		}

		function deactivate() {
			// at the moment I have nothing I would want to clean up
		}

		function iTunesLink() {
			return '<a href="http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id='.$this->settings['iTunes']['FeedID'].'"><img src="'.podPress_url().'images/itunes.png" border="0" alt="View in iTunes"/></a>';
		}

		function resetPlayerSettings() {
			$result['bg'] = '#F8F8F8';
			$result['leftbg'] = '#F8F8F8';
			$result['text'] = '#666666';
			$result['leftbg'] = '#EEEEEE';
			$result['lefticon'] = '#666666';
			$result['rightbg'] = '#CCCCCC';
			$result['rightbghover'] = '#999999';
			$result['righticon'] = '#666666';
			$result['righticonhover'] = '#FFFFFF';
			$result['slider'] = '#666666';
			$result['track'] = '#FFFFFF';
			$result['loader'] = '#9FFFB8';
			$result['border'] = '#666666';
			$result['listen_wrapper'] = 'off';
			$this->settings['player'] = $result;
			return $result;
		}

		function convertPodcastFileNameToValidWebPath($filename){
			if(strpos(substr($filename, 0, 10), '://')) {
				$url = $filename;
			} else {
				if(substr($filename, 0,1) == '/') {
					$baseurl = strtolower(strtok($_SERVER['SERVER_PROTOCOL'], '/')).'://'.$_SERVER['HTTP_HOST'].$this->settings['mediaWebPath'];
				} elseif(strpos(substr($this->settings['mediaWebPath'], 0, 10), '://')) {
					$baseurl = $this->settings['mediaWebPath'];
				} else {
					$baseurl = get_settings('siteurl').$this->settings['mediaWebPath'];
				}

				if(substr($filename, -1, 1) != '/')
				{
					$baseurl .= '/';
				}
				$url = $baseurl.$filename;
			}
			return $url;
		}

		function convertPodcastFileNameToWebPath($postID, $mediaNum, $filename = '', $method = false){
			$url = $this->convertPodcastFileNameToValidWebPath($filename);
			if($method != false) {
				if($this->settings['enableStats']) {
					$filename_part = podPress_getFileName($url);
					if($this->settings['statMethod'] == 'download.mp3') {
						$url = podPress_url().'download.mp3?'.$method.'='.$postID.'/'.$mediaNum.'/'.$filename_part;
					} else {
						$url = get_settings('siteurl').'/podpress_trac/'.$method.'/'.$postID.'/'.$mediaNum.'/'.$filename_part;
					}
				} elseif($this->settings['enablePodTracStats']) {
					$url = str_replace(array('ftp://', 'http://', 'https://'), '', $url);
					$url = $this->podtrac_url.$url;
				}
			}
			$url = str_replace(' ', '%20', $url);
			return $url;
		}

		function convertPodcastFileNameToSystemPath($filename = ''){
			if(!strpos(substr($filename, 0, 10), '://')) {
				$filename = $this->settings['mediaFilePath'].'/'.$filename;
				if(file_exists($filename))
				{
					return $filename;
				}
			}
			return false;
		}

		function checkWritableTempFileDir($showErrors = true) {
			/* check, if user-upload path is set */
			$this->uploadPath = ABSPATH.get_option('upload_path');
			if (file_exists($this->tempFileSystemPath)) {
				if(is_writable($this->tempFileSystemPath)) {
					return true;
				} else {
					if($showErrors) {
						echo '<p>'.__('Your uploads/podpress_temp directory is not writable. Please set permissions as needed, and make sure <a href="'.get_settings('siteurl').'/wp-admin/options-misc.php">configuration</a> is correct.', 'podpress').'<br />Currently set to:<code>'.get_option('upload_path')."/podpress_temp</code></p>\n";
					}
					return false;
				}
			} elseif (!file_exists($this->uploadPath)) {
				if($showErrors) {
					echo '<p>'.__('Your WordPress upload directory does not exist. Please create it and make sure <a href="'.get_settings('siteurl').'/wp-admin/options-misc.php">configuration</a> is correct.', 'podpress').'<br />Currently set to:<code>'.get_option('upload_path')."</code></p>\n";
				}
				return false;
			} elseif (!is_writable($this->uploadPath)) {
				if($showErrors) {
					echo '<p>'.__('Your WordPress upload directory is not writable. Please set permissions as needed, and make sure <a href="'.get_settings('siteurl').'/wp-admin/options-misc.php">configuration</a> is correct.', 'podpress').'<br />Currently set to:<code>'.get_option('upload_path')."</code></p>\n";
				}
				return false;
			} else {
				$mkdir = @mkdir($this->tempFileSystemPath);
				if (!$mkdir) {
					if($showErrors) {
						echo '<p>'.__('Could not create uploads/podpress_temp directory. Please set permission of the following directory to 755 or 777:', 'podpress').'<br /><code>'.get_option('upload_path')."/podpress_temp</code></p>\n";
					}
					return false;
				}
				return true;
			}
		}

		/*************************************************************/
		/* Load up the plugin values and get ready to action         */
		/*************************************************************/

		function addPostData($input, $forEdit = false) {
			$input->podPressMedia = podPress_get_post_meta($input->ID, 'podPressMedia', true);
			if(!is_array($input->podPressMedia)) {
				$x = maybe_unserialize($input->podPressMedia);
				if(is_array($x)) {
					$input->podPressMedia = $x;
				}
				if(!is_array($input->podPressMedia)) {
					$x = maybe_unserialize($input->podPressMedia, true);
					if(is_array($x)) {
						$input->podPressMedia = $x;
					}
				}
			}
			if(is_array($input->podPressMedia)) {
				reset($input->podPressMedia);
				while (list($key) = each($input->podPressMedia)) {
					if(!empty($input->podPressMedia[$key]['URI'])) {
						if($input->podPressMedia[$key]['premium_only'] == 'on' || $input->podPressMedia[$key]['premium_only'] == true) {
							$input->podPressMedia[$key]['content_level'] = 'premium_content';
						} elseif(!isset($input->podPressMedia[$key]['content_level'])) {
							$input->podPressMedia[$key]['content_level'] = 'free';
						}

						if(!isset($input->podPressMedia[$key]['type'])) {
							$input->$input->podPressMedia[$key]['type'] = '';
						}
						settype($input->podPressMedia[$key]['size'], 'int');
						if(0 >= $input->podPressMedia[$key]['size']) {
							$filepath = $this->convertPodcastFileNameToSystemPath($input->podPressMedia[$key]['URI']);
							if($filepath) {
								$input->podPressMedia[$key]['size'] = filesize ($filepath);
							} else {
								$input->podPressMedia[$key]['size'] = 1;
							}
						}

						$input->podPressMedia[$key]['ext'] = podPress_getFileExt($input->podPressMedia[$key]['URI']);
						$input->podPressMedia[$key]['mimetype'] = podPress_mimetypes($input->podPressMedia[$key]['ext']);

						if(!$forEdit && $this->settings['enablePremiumContent'] && $input->podPressMedia[$key]['content_level'] != 'free' && @$GLOBALS['current_user']->allcaps[$input->podPressMedia[$key]['content_level']] != 1) {
							$input->podPressMedia[$key]['authorized'] = false;
							$input->podPressMedia[$key]['URI'] = '';
							$input->podPressMedia[$key]['URI_torrent'] = '';
						} else {
							$input->podPressMedia[$key]['authorized'] = true;
						}
					}
				}
			}

			$input->podPressPostSpecific = podPress_get_post_meta($input->ID, 'podPressPostSpecific', true);
			if(!is_array($input->podPressPostSpecific)) {
				$input->podPressPostSpecific = array();
			}

			if(empty($input->podPressPostSpecific['itunes:subtitle'])) {
				$input->podPressPostSpecific['itunes:subtitle'] = '##PostExcerpt##';
			}
			if(empty($input->podPressPostSpecific['itunes:summary'])) {
				$input->podPressPostSpecific['itunes:summary'] = '##PostExcerpt##';
			}
			if(empty($input->podPressPostSpecific['itunes:keywords'])) {
				$input->podPressPostSpecific['itunes:keywords'] = '##WordPressCats##';
			}
			if(empty($input->podPressPostSpecific['itunes:author'])) {
				$input->podPressPostSpecific['itunes:author'] = '##Global##';
			}
			if(empty($input->podPressPostSpecific['itunes:explicit'])) {
				$input->podPressPostSpecific['itunes:explicit'] = 'Default';
			}
			if(empty($input->podPressPostSpecific['itunes:block'])) {
				$input->podPressPostSpecific['itunes:block'] = 'Default';
			}

			return $input;
		}

		function the_posts($input) {
			GLOBAL $podPress_inAdmin;
			if(!$podPress_inAdmin && !$this->settings['compatibilityChecks']['themeTested']) {
				$this->settings['compatibilityChecks']['themeTested'] = true;
				podPress_update_option('podPress_config', $this->settings);
			}

			if(!is_array($input)) {
				return $input;
			}
			foreach($input as $key=>$value) {
				$input[$key] = $this->addPostData($value);
			}
			return $input;
		}

		function posts_join($input) {
			GLOBAL $wpdb;
			if(defined('PODPRESS_PODCASTSONLY')) {
				$input .= " JOIN ".$wpdb->prefix."postmeta ON ".$wpdb->prefix."posts.ID=".$wpdb->prefix."postmeta.post_id ";
			}
			return $input;
		}

		function posts_where($input) {
			GLOBAL $wpdb;
			if(defined('PODPRESS_PODCASTSONLY')) {
				$input .= "AND ".$wpdb->prefix."postmeta.meta_key='podPressMedia' ";
			}
			return $input;
		}

		function insert_the_excerpt($content = '') {
			GLOBAL $post;
			$this->tempContentAddedTo[$post->ID] = true;
			return $content;
		}

		function insert_the_excerptplayer($content = '') {
			GLOBAL $post;
			unset($this->tempContentAddedTo[$post->ID]);
			$content = $this->insert_content($content);
			unset($this->tempContentAddedTo[$post->ID]);
			return $content;
		}

		function insert_content($content = '') {
			GLOBAL $post, $podPressTemplateData, $podPressTemplateUnauthorizedData, $wpdb;

			if(isset($this->tempContentAddedTo[$post->ID])) {
				if(is_feed()) {
					return str_replace($this->podcastTag,'',$content);
				}
				return $content;
			} else {
				$this->tempContentAddedTo[$post->ID] = true;
			}

			if(is_feed()) {
				if($this->settings['protectFeed'] == 'Yes' && get_option('blog_charset') == 'UTF-8') {
					$content = podPress_feedSafeContent($content);
				}
				if($this->settings['rss_showlinks'] != 'yes') {
					return str_replace($this->podcastTag,'',$content);
				}
			}

			if(!is_array($post->podPressMedia)) {
				return str_replace($this->podcastTag,'',$content);
			}

			$hasLocationDefined = (bool)strstr($content, $this->podcastTag);
			if(!$hasLocationDefined) {
				if($this->settings['contentBeforeMore'] == 'no') {
					return $content;
				}
				if($this->settings['contentLocation'] == 'start') {
					$content = $this->podcastTag.$content;
				} else {
					$content .= $this->podcastTag;
				}
			} 

			$podPressRSSContent = '';
			$showmp3player = false;
			$showvideopreview = false;
			$showvideoplayer = false;
			$podPressTemplateData = array();

			$podPressTemplateData['showDownloadText'] = $this->settings['contentDownloadText'];
			$podPressTemplateData['showDownloadStats'] = $this->settings['contentDownloadStats'];
			$podPressTemplateData['showDuration'] = $this->settings['contentDuration'];
			$this->playerCount++;
			$podPressTemplateData['files'] = array();
			$podPressTemplateData['player'] = array();
			reset($post->podPressMedia);
			while (list($key) = each($post->podPressMedia)) {
				if(empty($post->podPressMedia[$key]['previewImage'])) {
					$post->podPressMedia[$key]['previewImage'] = $this->settings['videoPreviewImage'];
				}

				if($this->settings['disableVideoPreview']) {
					$post->podPressMedia[$key]['disablePreview'] = true;
				}

				if($post->podPressMedia[$key]['feedonly'] == 'on') {
					continue;
				}
				$post->podPressMedia[$key]['title'] = htmlentities(stripslashes($post->podPressMedia[$key]['title']), ENT_QUOTES, get_settings('blog_charset'));
				$post->podPressMedia[$key]['stats'] = false;
				if($this->settings['enableStats']) {
					$pos = strrpos($post->podPressMedia[$key]['URI'], '/');
					$len == strlen($post->podPressMedia[$key]['URI']);
					while(substr($post->podPressMedia[$key]['URI'], $pos, 1) == '/') {
						$pos++;
					}
					$filename = substr($post->podPressMedia[$key]['URI'], $pos);
					$sql = "SELECT * FROM ".$wpdb->prefix."podpress_statcounts WHERE media = '".$filename."'";
					$stats = $wpdb->get_results($sql);
					if($stats) {
						$post->podPressMedia[$key]['stats'] = array('feed'=>$stats[0]->feed, 'web'=>$stats[0]->web, 'play'=>$stats[0]->play, 'total'=>$stats[0]->total);
					}
				}
				$supportedMediaTypes = array('audio_mp3', 'audio_ogg', 'audio_m4a', 'audio_mp4', 'audio_m3u', 'video_mp4', 'video_m4v', 'video_mov', 'video_qt', 'video_avi', 'video_mpg', 'video_asf', 'video_wmv', 'video_wma', 'video_flv', 'video_swf', 'ebook_pdf');
				if(!in_array($post->podPressMedia[$key]['type'], $supportedMediaTypes)) {
					$post->podPressMedia[$key]['type'] = 'misc_other';
				}
				// this loop is for the basics. After this the unauthorized content will stop
				if(empty($post->podPressMedia[$key]['title'])) {
					$post->podPressMedia[$key]['title'] = podPress_defaultTitles($post->podPressMedia[$key]['type']);
				}

				if($this->settings['contentImage'] != 'none') {
					$post->podPressMedia[$key]['image'] = $post->podPressMedia[$key]['type'].'_'.$this->settings['contentImage'].'.png';
				}

				if($post->podPressMedia[$key]['authorized']) {
					$post->podPressMedia[$key]['URI_orig'] = $post->podPressMedia[$key]['URI'];
					$post->podPressMedia[$key]['URI'] = $this->convertPodcastFileNameToWebPath($post->ID, $key, $post->podPressMedia[$key]['URI'], 'web');
					$post->podPressMedia[$key]['URI_Player'] = $this->convertPodcastFileNameToWebPath($post->ID, $key, $post->podPressMedia[$key]['URI'], 'play');
					if(!empty($post->podPressMedia[$key]['URI_torrent'])) {
						$post->podPressMedia[$key]['URI_torrent'] = $this->convertPodcastFileNameToWebPath($post->ID, $key, $post->podPressMedia[$key]['URI_torrent'], 'web');
					}

					if($this->settings['contentDownload'] == 'disabled') {
						$post->podPressMedia[$key]['enableDownload'] = false;
						$post->podPressMedia[$key]['enableTorrentDownload'] = false;
					} else {
						$post->podPressMedia[$key]['enableDownload'] = true;
						$podPressRSSContent .= '<a href="'.$post->podPressMedia[$key]['URI'].'">'.__('Download', 'podpress').' '.__($post->podPressMedia[$key]['title'], 'podpress').'</a><br/>';
						if($this->settings['enableTorrentCasting'] && !empty($post->podPressMedia[$key]['URI_torrent'])) {
							$post->podPressMedia[$key]['enableTorrentDownload'] = true;
						}
					}
					switch($this->settings['contentPlayer']) {
						case 'disabled':
							$post->podPressMedia[$key]['enablePlayer'] = false;
							$post->podPressMedia[$key]['enablePopup'] = false;
							break;
						case 'inline':
							$post->podPressMedia[$key]['enablePlayer'] = true;
							$post->podPressMedia[$key]['enablePopup'] = false;
							break;
						case 'popup':
							$post->podPressMedia[$key]['enablePlayer'] = false;
							$post->podPressMedia[$key]['enablePopup'] = true;
							break;
						case 'both':
							$post->podPressMedia[$key]['enablePlayer'] = true;
							$post->podPressMedia[$key]['enablePopup'] = true;
						default:
					}
					if($post->podPressMedia[$key]['enablePlayer']) {
						// This loop is to put together the player data.
						switch($post->podPressMedia[$key]['type']) {
							case 'audio_mp3':
								$post->podPressMedia[$key]['dimensionW'] = 300;
								$post->podPressMedia[$key]['dimensionH'] = 30;
								break;
							case 'audio_ogg':
								$post->podPressMedia[$key]['dimensionW'] = 300;
								$post->podPressMedia[$key]['dimensionH'] = 30;
								break;
							case 'audio_m4a':
							case 'audio_m4a':
							case 'audio_mp4':
							case 'video_m4v':
							case 'video_mp4':
							case 'video_mov':
							case 'video_qt':
							case 'video_avi':
							case 'video_mpg':
							case 'video_asf':
							case 'video_wma':
							case 'video_wmv':
							case 'video_flv':
							case 'video_swf':
								break;
							case 'audio_m3u':
								$post->podPressMedia[$key]['enableDownload'] = true;
							case 'ebook_pdf':
							default:
								$post->podPressMedia[$key]['enablePlayer'] = false;
								$post->podPressMedia[$key]['enablePopup'] = false;
						}
					}
				}
				if($post->podPressMedia[$key]['disablePlayer']) {
					$post->podPressMedia[$key]['enablePlayer'] = false;
					$post->podPressMedia[$key]['enablePopup'] = false;
				} 

				$podPressTemplateData['files'][] = $post->podPressMedia[$key];
				$post->podPressMedia[$key]['URI'] = $post->podPressMedia[$key]['URI_orig'];
				unset($post->podPressMedia[$key]['URI_orig']);
			}

			if(is_feed()) {
				return str_replace($this->podcastTag,'<br/>'.$podPressRSSContent,$content);
			}

			if(!$this->settings['compatibilityChecks']['wp_head']) {
				$podPressContent = '<code>podPress theme compatibility problem. Please check podPress->General Settings for more information.</code><br/>';
				$this->settings['compatibilityChecks']['wp_head'] = false;
				$this->settings['compatibilityChecks']['wp_footer'] = false;
				podPress_update_option('podPress_config', $this->settings);
			} else {
				/* The theme file needs to populate these */
				$podPressContent = podPress_webContent($podPressTemplateData);
			}
			return str_replace($this->podcastTag,$podPressContent,$content);
		}

		function comment_form() {
			echo "<br />\n";
			echo '<div id="podPress_audioCommentStatus"><a href="#RecordAudio" onclick="javascript: podPressShowRecorder();" ><img src="http://podpress.mobatalk.com/images/mobatalk-bullet.jpg" width="16" height="16" alt="mobatalk-bullet" border="0" /> Insert Audio Comment</a></div>'."\n";
			echo "<p><br />\n";
			echo '<a name="RecordAudio"/>'."\n";
			echo '<iframe id="podPress_audioRecorder" scrolling="no" name="podPress_audioRecorder" frameborder="0" style="overflow:hidden;width:450px;height:135px;display:none" src=""></iframe>'."\n";
			echo '<input type="hidden" name="podPress_audioCommentURL" id="podPress_audioCommentURL" value="" />'."\n";
			echo '<input type="hidden" name="podPress_audioCommentSize" id="podPress_audioCommentSize" value="" />'."\n";
			echo '<input type="hidden" name="podPress_audioCommentDuration" id="podPress_audioCommentDuration" value="" />'."\n";
			echo "</p><br />\n";
		}

		function comment_post($id) {
			GLOBAL $wpdb;
			$URL = mysql_escape_string($_REQUEST['podPress_audioCommentURL']);
			$q = $wpdb->query("UPDATE ".$wpdb->comments." SET comment_enclosure='$URL' WHERE comment_ID='$id'");
		}

		function comment_text($input) {
			GLOBAL $comment;
			if(!empty($comment->comment_enclosure)) {
				$listenWrapper = false;
				$playerOptions = '';
				if(@!is_array($this->settings['player'])) {
					$this->resetPlayerSettings();
				}
				foreach($this->settings['player'] as $key => $val) {
					if($key == 'listenWrapper') {
						$listenWrapper = $val;
					} else {
						$val = str_replace('#', '0x', $val);
						$playerOptions .= '&amp;' . $key . '=' . rawurlencode($val);
					}
				}
				$input .= '<br/><br/>Includes the following Audio Comment<br/>'."\n";
				if($listenWrapper) {
					$input .= podPress_listenWrapperBox('start');
				}
				$input .= '<object type="application/x-shockwave-flash" data="'.podPress_url(). 'players/player.swf'.'" width="290" height="24" id="audioplayer'.$comment->comment_ID.'">'."\n";
				$input .= '	<param name="movie" value="'.podPress_url().'players/player.swf" />'."\n";
				$input .= '	<param name="FlashVars" value="playerID='.$comment->comment_ID.$playerOptions.'&amp;soundFile='.rawurlencode($comment->comment_enclosure).'" />'."\n";
				$input .= '	<param name="quality" value="high" />'."\n";
				$input .= '	<param name="menu" value="false" />'."\n";
				$input .= '	<param name="wmode" value="transparent" />'."\n";
				//$result .= '<embed src="'.podPress_url().'players/player.swf" quality="high" width="290" height="24" '.$playerOptionsEmbed.' id="audioplayerBBB'.$randID.'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'."\n";
				$input .= '</object>'."\n";
				if($listenWrapper) {
					$input .= podPress_listenWrapperBox('end');
				}
			}
			return $input;
		}

		/*************************************************************/
		/* feed generation functions                                 */
		/*************************************************************/

		function do_feed_premium() {
			define('PREMIUMCAST', true);
			podPress_validateLogin();
			load_template(ABSPATH.'wp-rss2.php');
		}

		function do_feed_podcast() {
			GLOBAL $wp_query;
			define('PODPRESS_PODCASTSONLY', true);
			$wp_query->get_posts();
			load_template(ABSPATH.'wp-rss2.php');
		}

		function do_feed_atom1() {
			load_template(ABSPATH.PLUGINDIR.'/podpress/wp-atom1.php');
		}

		function do_feed_torrent() {
			GLOBAL $posts;
			define('PODPRESS_TORRENTCAST', true);
			$posts = $this->the_posts($posts);
			load_template(ABSPATH.'wp-rss2.php');
		}

		function rss2_ns() {
			echo 'xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"'."\n";
			echo '	xmlns:dtvmedia="http://participatoryculture.org/RSSModules/dtv/1.0"'."\n";
			echo '	xmlns:media="http://search.yahoo.com/mrss/"'."\n";
		}

		function rss2_head() {
			GLOBAL $post, $post_meta_cache, $blog_id;
			podPress_reloadCurrentUser();

			if(is_array($post_meta_cache[$blog_id])) {
				foreach($post_meta_cache[$blog_id] as $key=>$val) {
					if(isset($post_meta_cache[$blog_id][$key]['enclosure']) && isset($post_meta_cache[$blog_id][$key]['podPressMedia'])) {
						$post_meta_cache[$blog_id][$key]['enclosure_podPressHold'] = $post_meta_cache[$blog_id][$post->ID]['enclosure'];
						unset($post_meta_cache[$blog_id][$key]['enclosure']);
					}
				}
			}

			if(!isset($this->settings['category_data'])) {
				$this->feed_getCategory();
			}
			$data = $this->settings['iTunes'];

			$data['podcastFeedURL'] = $this->settings['podcastFeedURL'];

			$data['rss_image'] = get_option('rss_image');
			$data['admin_email'] = stripslashes(get_option('admin_email'));

			if($this->settings['category_data']['categoryCasting'] == 'true') {

				$data['podcastFeedURL'] = $this->settings['category_data']['podcastFeedURL'];

				if($this->settings['category_data']['iTunesNewFeedURL'] != '##Global##') {
					$data['new-feed-url'] = $this->settings['category_data']['iTunesNewFeedURL'];
				}

				if($this->settings['category_data']['iTunesSummaryChoice'] == 'Custom') {
					$data['summary'] = $this->settings['category_data']['iTunesSummary'];
				}

				if($this->settings['category_data']['iTunesSubtitleChoice'] == 'Custom') {
					$data['subtitle'] = $this->settings['category_data']['iTunesSubtitle'];
				}

				if($this->settings['category_data']['iTunesKeywordsChoice'] == 'Custom') {
					$data['keywords'] = $this->settings['category_data']['iTunesKeywords'];
				}

				if($this->settings['category_data']['iTunesAuthorChoice'] == 'Custom' && !empty($this->settings['category_data']['iTunesAuthor'])) {
					$data['author'] = $this->settings['category_data']['iTunesAuthor'];
				}
				if($this->settings['category_data']['iTunesAuthorEmailChoice'] == 'Custom') {
					$data['admin_email'] = $this->settings['category_data']['iTunesAuthorEmail'];
				}

				if($this->settings['category_data']['iTunesBlock'] != '##Global##' && !empty($this->settings['category_data']['iTunesBlock'])) {
					$data['block'] = $this->settings['category_data']['iTunesBlock'];
				}
				if($this->settings['category_data']['iTunesExplicit'] != '##Global##' && !empty($this->settings['category_data']['iTunesExplicit'])) {
					$data['explicit'] = $this->settings['category_data']['iTunesExplicit'];
				}
				if($this->settings['category_data']['iTunesImageChoice'] == 'Custom') {
					$data['image'] = $this->settings['category_data']['iTunesImage'];
				}
				if($this->settings['category_data']['rss_imageChoice'] == 'Custom') {
					$data['rss_image'] = $this->settings['category_data']['rss_image'];
				}
				if($this->settings['category_data']['rss_copyrightChoice'] == 'Custom') {
					$data['rss_copyright'] = $this->settings['category_data']['rss_copyright'];
				}
			}

			$data['rss_ttl'] = get_option('rss_ttl');
			if(!empty($data['rss_ttl']) && $data['rss_ttl'] < 1440) {
				$data['rss_ttl'] = 1440;
			}
			echo '	<!-- podcast_generator="podPress/'.PODPRESS_VERSION.'" -->'."\n";
			echo '		<copyright>&#xA9;'.podPress_feedSafeContent($data['author']).' '.podPress_feedSafeContent($data['rss_copyright']).'</copyright>'."\n";
			if($data['new-feed-url'] == 'Enable') {
				if(!empty($data['podcastFeedURL']) && !strpos(strtolower($data['podcastFeedURL']), 'phobos.apple.com') && !strpos(strtolower($data['podcastFeedURL']), 'itpc://')) {
					echo '		<itunes:new-feed-url>'.podPress_feedSafeContent($data['podcastFeedURL']).'</itunes:new-feed-url>'."\n";
				}
			}
			echo '		<managingEditor>'.podPress_feedSafeContent(stripslashes(get_option('admin_email'))).' ('.podPress_feedSafeContent($this->settings['iTunes']['author']).')</managingEditor>'."\n";
			echo '		<webMaster>'.podPress_feedSafeContent(get_option('admin_email')).'</webMaster>'."\n";
			echo '		<category>'.podPress_feedSafeContent($this->settings['rss_category']).'</category>'."\n";
			if(!empty($data['rss_ttl'])) {
				echo '		<ttl>'.$data['rss_ttl'].'</ttl>'."\n";
			}
			echo '		<itunes:keywords>'.podPress_stringLimiter(podPress_feedSafeContent($data['keywords'], true), 255).'</itunes:keywords>'."\n";
			echo '		<itunes:subtitle>'.podPress_stringLimiter(podPress_feedSafeContent($data['subtitle'], true), 255).'</itunes:subtitle>'."\n";
			echo '		<itunes:summary>'.podPress_stringLimiter(podPress_feedSafeContent($data['summary'], true), 4000).'</itunes:summary>'."\n";
			echo '		<itunes:author>'.podPress_feedSafeContent($data['author']).'</itunes:author>'."\n";
			echo '		' . $this->getiTunesCategoryTags();
			echo '		<itunes:owner>'."\n";
			echo '			<itunes:name>'.stripslashes(podPress_feedSafeContent($data['author'])).'</itunes:name>'."\n";
			echo '			<itunes:email>'.podPress_feedSafeContent($data['admin_email']).'</itunes:email>'."\n";
			echo '		</itunes:owner>'."\n";
			if(empty($data['block'])) {
				$data['block'] = 'No';
			}
			echo '		<itunes:block>'.$data['block'].'</itunes:block>'."\n";
			echo '		<itunes:explicit>'.podPress_feedSafeContent(strtolower($data['explicit'])).'</itunes:explicit>'."\n";
			echo '		<itunes:image href="'.$data['image'].'" />'."\n";
			echo '		<image>'."\n";
			echo '			<url>'.podPress_feedSafeContent($data['rss_image']).'</url>'."\n";
			echo '			<title>'; bloginfo_rss('name'); echo '</title>'."\n";
			echo '			<link>'; bloginfo_rss('url'); echo '</link>'."\n";
			echo '			<width>144</width>'."\n";
			echo '			<height>144</height>'."\n";
			echo '		</image>'."\n";
		}

		function rss2_item() {
			GLOBAL $post, $post_meta_cache, $blog_id;
			$enclosureTag = $this->getEnclosureTags();
			if($enclosureTag != '') // if no enclosure tag, no need for iTunes tags
			{
				echo '		' . $enclosureTag;

				if($post->podPressPostSpecific['itunes:subtitle'] == '##PostExcerpt##') {
					ob_start();
					the_content_rss('', false, 0, 25);
					$data = ob_get_contents();
					ob_end_clean();
					$post->podPressPostSpecific['itunes:subtitle'] = substr(ltrim($data), 0, 254);
				}
				if(empty($post->podPressPostSpecific['itunes:subtitle'])) {
					$post->podPressPostSpecific['itunes:subtitle'] = get_the_title_rss();
				}
				echo '		<itunes:subtitle>'.podPress_feedSafeContent($post->podPressPostSpecific['itunes:subtitle'], true).'</itunes:subtitle>'."\n";

				if($post->podPressPostSpecific['itunes:summary'] == '##Global##') {
					$post->podPressPostSpecific['itunes:summary'] = $this->settings['iTunes']['summary'];
				}
				if(empty($post->podPressPostSpecific['itunes:summary']) || $post->podPressPostSpecific['itunes:summary'] == '##PostExcerpt##') {
					ob_start();
					the_content_rss('', false, 0, '', 2);
					$data = ob_get_contents();
					ob_end_clean();
					$post->podPressPostSpecific['itunes:summary'] = substr(ltrim($data), 0, 4000);
				}
				if(empty($post->podPressPostSpecific['itunes:summary'])) {
					$post->podPressPostSpecific['itunes:summary'] = $this->settings['iTunes']['summary'];
				}
				echo '		<itunes:summary>'.podPress_stringLimiter(podPress_feedSafeContent($post->podPressPostSpecific['itunes:summary'], true), 4000).'</itunes:summary>'."\n";

				if($post->podPressPostSpecific['itunes:keywords'] == '##WordPressCats##') {
					$categories = get_the_category();
					$post->podPressPostSpecific['itunes:keywords'] = '';
					if(is_array($categories)) {
						foreach ($categories as $category) {
							$category->cat_name = $category->cat_name;
							if($post->podPressPostSpecific['itunes:keywords'] != '') {
								$post->podPressPostSpecific['itunes:keywords'] .= ', ';
							}
							$post->podPressPostSpecific['itunes:keywords'] .= $category->cat_name;
						}
						$post->podPressPostSpecific['itunes:keywords'] = trim($post->podPressPostSpecific['itunes:keywords']);
					}
				} elseif($post->podPressPostSpecific['itunes:keywords'] == '##Global##') {
					$post->podPressPostSpecific['itunes:keywords'] = $this->settings['iTunes']['keywords'];
				}
				echo '		<itunes:keywords>'.podPress_stringLimiter(podPress_feedSafeContent(str_replace(' ', ',', $post->podPressPostSpecific['itunes:keywords']), true), 255).'</itunes:keywords>'."\n";

				if($post->podPressPostSpecific['itunes:author'] == '##Global##') {
					$post->podPressPostSpecific['itunes:author'] = $this->settings['iTunes']['author'];
					if(empty($post->podPressPostSpecific['itunes:author'])) {
						$post->podPressPostSpecific['itunes:author'] = stripslashes(get_option('admin_email'));
					}
				}
				echo '		<itunes:author>'.podPress_feedSafeContent($post->podPressPostSpecific['itunes:author'], true).'</itunes:author>'."\n";

				if($post->podPressPostSpecific['itunes:explicit'] == 'Default') {
					$post->podPressPostSpecific['itunes:explicit'] = $this->settings['iTunes']['explicit'];
					if(empty($post->podPressPostSpecific['itunes:explicit'])) {
						$post->podPressPostSpecific['itunes:explicit'] = 'No';
					}
				}
				echo '		<itunes:explicit>'.podPress_feedSafeContent(strtolower($post->podPressPostSpecific['itunes:explicit'])).'</itunes:explicit>'."\n";

				if($post->podPressPostSpecific['itunes:block'] == 'Default') {
					$post->podPressPostSpecific['itunes:block'] = $this->settings['iTunes']['block'];
					if(empty($post->podPressPostSpecific['itunes:block'])) {
						$post->podPressPostSpecific['itunes:block'] = 'No';
					}
				}
				if(empty($post->podPressPostSpecific['itunes:block'])) {
					$post->podPressPostSpecific['itunes:block'] = 'No';
				}
				echo '		<itunes:block>'.podPress_feedSafeContent($post->podPressPostSpecific['itunes:block']).'</itunes:block>'."\n";
				//echo '<comments>'. get_comments_link() .'</comments>'."\n";
			}
			if(isset($post_meta_cache[$blog_id][$post->ID]['enclosure_podPressHold'])) {
				$post_meta_cache[$blog_id][$post->ID]['enclosure'] = $post_meta_cache[$blog_id][$post->ID]['enclosure_podPressHold'];
				unset($post_meta_cache[$blog_id][$post->ID]['enclosure_podPressHold']);
			}
		}

		function atom_head() {
			if(!isset($this->settings['category_data'])) {
				$this->feed_getCategory();
			}
			echo '	<!-- podcast_generator="podPress/'.PODPRESS_VERSION.'" -->'."\n";
			if($this->settings['category_data']['categoryCasting'] == 'true' && $this->settings['category_data']['rss_imageChoice'] == 'Custom') {
				echo '	<icon>'.podPress_feedSafeContent($this->settings['category_data']['rss_image']).'</icon>'."\n";
			} else {
				echo '	<icon>'.podPress_feedSafeContent(get_option('rss_image')).'</icon>'."\n";
			}
		}

		function atom_entry() {
			$enclosureTag = $this->getEnclosureTags('atom');
			if($enclosureTag != '') // if no enclosure tag, no need for iTunes tags
			{
				echo '		' . $enclosureTag;
			}
		}

		function crossdomain() {
			header("HTTP/1.0 200 OK");
			header('Content-type: text/xml; charset=' . get_settings('blog_charset'), true);
			echo '<?xml version="1.0"?>'."\n";
			echo '<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">'."\n";
			echo '<cross-domain-policy>'."\n";
			echo '  <allow-access-from domain="*" />'."\n";
			echo '</cross-domain-policy>'."\n";
			exit;
		}

		function xspf_playlist() {
			GLOBAL $more, $posts, $m;
			header("HTTP/1.0 200 OK");
			header('Content-type: application/xspf+xml; charset=' . get_settings('blog_charset'), true);
			$more = 1;
			echo '<?xml version="1.0" encoding="'.get_settings('blog_charset').'" ?'.">\n";
			echo '<playlist version="0" xmlns="http://xspf.org/ns/0/">'."\n";
			echo "  <title>"; bloginfo_rss('name'); echo "</title>\n";
			echo "  <annotation></annotation>\n";
			echo "  <creator>"; the_author(); echo "</creator>\n";
			echo "  <location>"; bloginfo_rss('url'); echo "</location>\n";
			echo "  <license>http://creativecommons.org/licenses/by-sa/1.0/</license>\n";
			echo "  <trackList>\n";
			if ($posts) {
				foreach ($posts as $post) {
					start_wp();
					$enclosureTag = $this->getEnclosureTags('xspf');
					if($enclosureTag != '') // if no enclosure tag, no need for track tags
					{
						echo "    <track>\n";
						echo $enclosureTag;
						echo "    </track>\n";
					}
				}
			}
			echo "  </trackList>\n";
			echo "</playlist>\n";
			exit;
		}

		function getEnclosureTags($feedtype = 'rss2') {
			GLOBAL $post;
			$result = '';
			$hasMediaFileAccessible = false;
			if(is_array($post->podPressMedia)) {
				$foundPreferred = false;
				reset($post->podPressMedia);
				while (list($key, $val) = each($post->podPressMedia)) {
					$preferredFormat = false;
					if(!$post->podPressMedia[$key]['authorized']) {
						if($this->settings['premiumContentFakeEnclosure']) {
							$post->podPressMedia[$key]['URI'] = 'podPress_Protected_Content.mp3';
						} else {
							continue;
						}
					}
					if(defined('PODPRESS_TORRENTCAST') && !empty($post->podPressMedia[$key]['authorized']['URI_torrent'])) {
						$post->podPressMedia[$key]['URI'] = $post->podPressMedia[$key]['URI_torrent'];
					}
					$hasMediaFileAccessible = true;

					if(isset($_GET['onlyformat']) && $_GET['onlyformat'] != $post->podPressMedia[$key]['ext']) {
						continue;
					}

					if(isset($_GET['format']) && $_GET['format'] == $post->podPressMedia[$key]['ext']) {
						$preferredFormat = true;
					}
					/*
					if($this->settings['enablePodTracStats']) {
						$podTracAttrib = '';
						//$podTracAttrib = ' PodTracDirectURL="'.$this->convertPodcastFileNameToValidWebPath($post->podPressMedia[$key]['URI']).'"';
					} else {
						$podTracAttrib = '';
					}
					*/
					if($post->podPressMedia[$key]['rss'] == 'on' || $post->podPressMedia[$key]['atom'] == 'on' || $preferredFormat == true) {
						if($feedtype == 'atom' && $post->podPressMedia[$key]['atom'] == 'on') {
							$post->podPressMedia[$key]['URI'] = $this->convertPodcastFileNameToWebPath($post->ID, $key, $post->podPressMedia[$key]['URI'], 'feed');
							$result .= '<link rel="enclosure" type="'.$post->podPressMedia[$key]['mimetype'].'" href="'.$post->podPressMedia[$key]['URI'].'" length="'.$post->podPressMedia[$key]['size'].'" />'."\n";
						} elseif($feedtype == 'xspf') {
							$post->podPressMedia[$key]['URI'] = $this->convertPodcastFileNameToValidWebPath($post->podPressMedia[$key]['URI']);
							if(podPress_getFileExt($post->podPressMedia[$key]['URI']) == 'mp3') {
								$result .= '      <location>'.$post->podPressMedia[$key]['URI']."</location>\n";
								if(!empty($post->podPressMedia[$key]['title'])) {
									$result .= '      <annotation>'.podPress_feedSafeContent($post->podPressMedia[$key]['title'])."</annotation>\n";
									$result .= '      <title>'.podPress_feedSafeContent($post->podPressMedia[$key]['title'])."</title>\n";
								} else {
									$result .= '      <annotation>'.podPress_feedSafeContent($post->post_title)."</annotation>\n";
									$result .= '      <title>'.podPress_feedSafeContent($post->post_title)."</title>\n";
								}
								if(!empty($post->podPressMedia[$key]['previewImage'])) {
									$result .= '      <image>'.$post->podPressMedia[$key]['previewImage']."</image>\n";
								}
						 }
						} elseif($feedtype == 'rss2') {
							$post->podPressMedia[$key]['URI'] = $this->convertPodcastFileNameToWebPath($post->ID, $key, $post->podPressMedia[$key]['URI'], 'feed');
							if(!isset($post->podPressMedia[$key]['duration']) || !preg_match("/([0-9]):([0-9])/", $post->podPressMedia[$key]['duration'])) {
								$post->podPressMedia[$key]['duration'] = '00:01:01';
							}
							$durationTag = '<itunes:duration>'.$post->podPressMedia[$key]['duration'].'</itunes:duration>'."\n";

							if($post->podPressMedia[$key]['rss'] == 'on') {
								if(!$preferredFormat && $foundPreferred) {
									continue;
								} elseif($preferredFormat) {
									$foundPreferred = true;
								}
								$result = '<enclosure url="'.$post->podPressMedia[$key]['URI'].'" length="'.$post->podPressMedia[$key]['size'].'" type="'.$post->podPressMedia[$key]['mimetype'].'"'.$podTracAttrib.'/>'."\n";
								$result .= $durationTag;
							} elseif($preferredFormat && !$foundPreferred) {
								$result = '<enclosure url="'.$post->podPressMedia[$key]['URI'].'" length="'.$post->podPressMedia[$key]['size'].'" type="'.$post->podPressMedia[$key]['mimetype'].'"'.$podTracAttrib.'/>'."\n";
								$result .= $durationTag;
								$foundPreferred = true;
							}
						}
					}
				}
			}
			if($hasMediaFileAccessible && $result == '' && $feedtype != 'xspf') {
				echo "<!-- Media File exists for this post, but its not enabled for this feed -->\n";
			}
			return $result;
		}

		function getiTunesCategoryTags() {
			GLOBAL $post;
			$result = '';
			$data = array();
			if($this->settings['category_data']['categoryCasting'] == 'true' && is_array($this->settings['category_data']['iTunesCategory'])) {
				foreach ($this->settings['category_data']['iTunesCategory'] as $key=>$value) {
					if($value == '##Global##') {
						if(!empty($this->settings['iTunes']['category'][$key])) {
							$data[] = $this->settings['iTunes']['category'][$key];
						}
					} else {
						$data[] = $value;
					}
				}
			}
			if(empty($data)) {
				$data = $this->settings['iTunes']['category'];
			}
			if(is_array($data)) {
				foreach($data as $thiscat) {
					if(strstr($thiscat, ':')) {
						list($cat, $subcat) = explode(":", $thiscat);
						$result .= '<itunes:category text="'.str_replace('&', '&amp;', $cat).'">'."\n";
						$result .= '  <itunes:category text="'.str_replace('&', '&amp;', $subcat).'"/>'."\n";
						$result .= '</itunes:category>'."\n";
					}
					elseif(!empty($thiscat))
					{
						$result .= '<itunes:category text="'.str_replace('&', '&amp;', $thiscat).'"/>'."\n";
					}
				}
			}
			if(empty($result)) {
				$result .= '<itunes:category text="Society &amp; Culture"/>'."\n";
			}
			return $result;
		}

		function feed_getCategory() {
			GLOBAL $wpdb, $wp_query;
			if(!is_category()) {
				$this->settings['category_data'] = false;
				return $this->settings['category_data'];
			}
			$current_catid = $wp_query->get('cat');
			$category = get_category($current_catid);

			$data = podPress_get_option('podPress_category_'.$category->cat_ID);
			$data['id'] = $category->cat_ID;
			$data['blogname'] = $category->cat_name;
			$data['blogdescription'] = $category->category_description;
			$this->settings['category_data'] = $data;
			return $this->settings['category_data'];

			// old version of this function
			if(!is_category()) {
				//return false;
			}
			$byName = single_cat_title('', false);

			$categories = get_the_category();
			if(is_array($categories)) {
				foreach ($categories as $category) {
					$thisisit = false;
					if($byName == $category->cat_name) {
						$thisisit = true;
					}

					if($thisisit) {
						$data = podPress_get_option('podPress_category_'.$category->cat_ID);
						$data['id'] = $category->cat_ID;
						$data['blogname'] = $category->cat_name;
						$data['blogdescription'] = $category->category_description;
						$this->settings['category_data'] = $data;
						return $this->settings['category_data'];
					}
				}
			}
			$this->settings['category_data'] = false;
			return $this->settings['category_data'];
		}

		function getCategoryCastingFeedData ($selection, $input) {
			GLOBAL $feed;
			if(!isset($this->settings['category_data'])) {
				$this->feed_getCategory();
			}

			if(empty($feed) || $this->settings['category_data'] === false) {
				return $input;
			} else {
				if(empty($this->settings['category_data']['categoryCasting'])) {
					$this->settings['category_data']['categoryCasting'] = 'true';
				}

				switch($selection) {
					case 'blogname':
						switch($this->settings['category_data']['blognameChoice']) {
							case 'CategoryName':
								if(empty($this->settings['category_data']['blogname'])) {
									return $input;
								} else {
									return $this->settings['category_data']['blogname'];
								}
								break;
							case 'Append':
								if(empty($this->settings['category_data']['blogname'])) {
									return $input;
								} else {
									return $input.' : '.$this->settings['category_data']['blogname'];
								}
								break;
							default:
								return $input;
								break;
						}
						break;
					case 'blogdescription':
						if($this->settings['category_data']['blogdescriptionChoice'] == 'CategoryDescription' && !empty($this->settings['category_data']['blogdescription'])) {
							return $this->settings['category_data']['blogdescription'];
						}
						return $input;
						break;
					case 'rss_language':
						if($this->settings['category_data']['rss_language'] == '##Global##' || empty($this->settings['category_data']['rss_language'])) {
							return $input;
						} else {
							return $this->settings['category_data']['rss_language'];
						}
						break;
					case 'rss_image':
						if($this->settings['category_data']['rss_imageChoice'] == 'Global' || empty($this->settings['category_data']['rss_image'])) {
							return $input;
						} else {
							return $this->settings['category_data']['rss_image'];
						}
						break;
					default:
						return $input;
						break;
				}
			}
		}

		function feedBlogName ($input) {
			return $this->getCategoryCastingFeedData('blogname', $input);
		}

		function feedBlogDescription ($input) {
			return $this->getCategoryCastingFeedData('blogdescription', $input);
		}

		function feedBlogRssLanguage ($input) {
			return $this->getCategoryCastingFeedData('rss_language', $input);
		}

		function feedBlogRssImage ($input) {
			return $this->getCategoryCastingFeedData('rss_image', $input);
		}

		function commentsrss2_item() {
			GLOBAL $comment, $wpdb;
			$sql = "SELECT comment_enclosure FROM ".$wpdb->comments." WHERE comment_ID = '".$comment->comment_ID."'";
			$data = $wpdb->get_results($sql);
			if($data && !empty($data[0]->comment_enclosure)) {
				echo '<enclosure url="'.$data[0]->comment_enclosure.'" />'."\n";
			}
		}
	}
