<?php
/*
* Manage extrafeeds
*
* 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
*
*/

require_once(dirname(__FILE__) . '/config.php');
require_once(dirname(__FILE__) . '/extrafeed_model.php');
require_once(dirname(__FILE__) . '/other_functions.php');
wtg_messages();

//manage extra feeds
function wtg_manage_extrafeeds() {
	$ag = new WTG_Extrafeed();
	$ag->initDB();
	
	if (isset($_GET['mode'])) {
		//check_admin_referer('manage_extrafeeds');

		if ($_GET['mode'] == 'add')
		{  //Add feeds
			wtg_add_extrafeed();
		}
		elseif ($_GET['mode'] == 'checkurl') {  //Add feeds from URL
			 wtg_add_url_extrafeed();
		}
		elseif ($_GET['mode'] == 'edit')
		{  //edit feed
			if (!empty($_GET['id']))
			{
				wtg_edit_extrafeed($_GET['id']);
				return;
			}
		}
		elseif ($_GET['mode'] == 'delete') {  //delete feed
			$ag->delete_extrafeedDB($_GET['id']);
		}
	}
	wtg_db_check_and_create();
	wtg_display_extrafeeds_list();
}

function wtg_display_extrafeeds_list() 
{
	?>
	<div class="wrap">
		<h2>Manage Extrafeeds</h2>
		<form id="extrafeeds" action="" method="post">
			<table id="extrafeeds_list" class="widefat">
				<thead>
					<tr>
						<th width="30%">Title</th>
						<th width="30%">URL</th>
						<th width="30%">Description</th>
						<th colspan="2">Action</th>
					</tr>
				</thead>
				<tbody>
					<?php
						$ef = new WTG_Extrafeed();
						$ef->initDB();
						$extrafeeds_list = $ef->get_all_extrafeedsDB();
						if (is_array($extrafeeds_list) && !empty($extrafeeds_list)) 
						{
							$class = '';
							foreach ($extrafeeds_list as $extrafeed)
							{
								$class = ( $class == 'class="alternate"' ) ? '' : 'class="alternate"';
								?>
									<tr <?php echo $class; ?>>
										<td><?php echo str_replace(" ", "&nbsp;", htmlspecialchars($extrafeed->title) ); ?></td>
										<td><?php echo htmlspecialchars($extrafeed->url); ?></td>
										<td><?php echo str_replace(" ", "&nbsp;", htmlspecialchars($extrafeed->desc) ); ?></td>
										<td><a href="<?php echo wp_nonce_url("admin.php?page=manage_extrafeeds&amp;mode=edit&amp;id=".$extrafeed->id, 'manage_extrafeeds')?>" >Edit</a></td>
										<td><a href="<?php echo wp_nonce_url("admin.php?page=manage_extrafeeds&amp;mode=delete&amp;id=".$extrafeed->id, 'manage_extrafeeds')?>" onclick="return confirm('Do you really want to delete this site?');">Delete</a></td>
									</tr>
								<?php
							}
						} else {
							echo '<tr><td colspan="4" align="center"><strong>No entries found</strong></td></tr>';
						}
						echo '<tr><td colspan="4" align="center"><strong><a href="admin.php?page=manage_extrafeeds&amp;mode=add">Add New</a></strong></td></tr>';
					?>
				</tbody>
			</table>
		</form>
	</div>
	<?php
}

function wtg_add_extrafeed() {
	if (isset($_POST['addextrafeed']) || isset($_POST['addexitextrafeed'])) 
	{
		check_admin_referer('add_extrafeed');
		if (strlen(trim($_POST['title'])) >0 && strlen(trim($_POST['url'])) >0  && strlen(trim($_POST['desc'])) >0) {
			$ag = new WTG_Extrafeed();
			$ag->initDB();
			$extrafeeds_list = $ag->get_all_extrafeedsDB();
			$id = $ag->add_extrafeedDB($_POST['title'], trim($_POST['url']), $_POST['desc']);
			if ($id) 
			{
				$url = 'admin.php?page=manage_extrafeeds';
				$url = wp_nonce_url($url, 'manage_extrafeeds');
				echo '<div class="updated fade"><p>Feed added!</p></div>';
                // Clear fields
                unset($_POST['title']);
                unset($_POST['url']);
                unset($_POST['desc']);
                if (isset($_POST['addexitextrafeed']))
				{
					return ;
                }
            }
		} 
		else 
		{
			echo '<div class="error"><p>Please input the all fields.</p></div>';
		}
	}
 	if (isset($_POST['canceladdextrafeed'])) 
	{
		return ;
	}
?>
	<div class="wrap">
		<h2>Add Extrafeed</h2>
		<form action="" method="post">
			<?php wp_nonce_field('add_extrafeed'); ?>
			<p>
				<label>Title:</label>
				<input type="text" id="title" name="title" value="<?php echo isset($_POST['title'])?$_POST['title']:'';  ?>" size="35"/>
			</p>
			<p>
				<label>URL:</label>
				<input type="text" id="url" name="url" value="<?php echo isset($_POST['url'])?$_POST['url']:''; ?>" size="35"/> <span class="submit"><input type="button" name="checkurl" value="Add RSS Feed Entries &raquo;" onclick="open_win()"/></span>
			</p>
			<p>
				<label>Description:</label>
				<textarea id="desc" name="desc" cols="25" rows="5" ><?php echo isset($_POST['desc'])?$_POST['desc']:''; ?></textarea>
			</p>
			<p class="submit">
				<input type="submit" name="addextrafeed" value="Add and Continue &raquo;" />
				<input type="submit" name="addexitextrafeed" value="Add and Exit &raquo;" />
				<input type="submit" name="canceladdextrafeed" value="Cancel and Exit&raquo;" />
			</p>
		</form>
	<?php
		echo "<script language=\"javascript\" type=\"text/javascript\">
			document.getElementById(\"title\").focus(); 
			function open_win()
			{
				var url=document.getElementById(\"url\").value;
				url = url.replace(/ /g, '');
				url = url.replace(/\//g, '^');
				
				if(!url) {
					alert(\"Please enter the URL.\");
					return false;
				}
				//alert(url);
				var url='".$_SERVER['PHP_SELF']."?page=manage_extrafeeds&mode=checkurl&url='+url;
				window.open(url,'welcome', 'width=600,height=500,menubar=yes,status=yes,location=yes,toolbar=yes,scrollbars=yes');
			}
		</script>";
	?>	
	</div>
<?php
}

function wtg_edit_extrafeed($extrafeed_id) {
	if (isset($_POST['canceleditextrafeed'])){
    	wtg_display_extrafeeds_list();
		return;
	}
	if (isset($_POST['editextrafeed'])) {
		check_admin_referer('edit_extrafeed');
		if (strlen(trim($_POST['title'])) >0 && strlen(trim($_POST['url'])) >0  && strlen(trim($_POST['desc'])) >0) {
			$ag = new WTG_Extrafeed();
			$ag->initDB();
			$ag->set_extrafeed_paramsDB($_POST['id'],trim($_POST['title']), trim($_POST['url']),trim($_POST['desc']));
			echo '<div class="updated fade"><p>Feed Updated</p></a></div>';
            wtg_display_extrafeeds_list();
            return;
		} else {
			echo '<div class="error fade"><p>Please input the all fields.</p></div>';
		}
	}
	$ag1 = new WTG_Extrafeed();
	$ag1->initDB();
    $extrafeed = $ag1->get_extrafeedDB($extrafeed_id);
	?>
		<div class="wrap">
			<h2>Edit Extrafeed</h2>
			<form action="" method="post">
				<?php wp_nonce_field('edit_extrafeed'); ?>
				<p>
					<label>Title:</label>
					<input type="hidden" id="id" name="id" value="<?php echo $extrafeed->id; ?>" />
					<input type="text" id="title" name="title" value="<?php echo $extrafeed->title; ?>" size="35" />
				</p>
				<p>
					<label>URL:</label>
					<input type="text" id="url" name="url" value="<?php echo $extrafeed->url; ?>"  size="35"/>
				</p>
				<p>
					<label valign="top">Description:</label>
					<textarea  id="desc" name="desc" cols="25" rows="5"><?php echo $extrafeed->desc; ?></textarea>
				</p>
				<p class="submit">
					<input type="submit" name="editextrafeed" value="Update and Continue&raquo;" />
					<input type="submit" name="canceleditextrafeed" value="Cancel and Exit&raquo;" />
				</p>
			</form>
			<script language="javascript" type="text/javascript">
				document.getElementById("title").focus(); 
			</script>
		</div>
	<?php
}

function wtg_add_url_extrafeed() {
	if (isset($_POST['canceladdextrafeed'])) {
		echo '<SCRIPT language="JavaScript">
				setTimeout(window.self.close(), 5000);
			</script>';
		return ;
	}

	if (isset($_POST['addbulkextrafeed'])) 
	{
		check_admin_referer('add_extrafeed');
		if($_POST['totalrss']) {
			for ($i = 1; $i <= $_POST['totalrss'] ; $i++) {
				if($_POST["rss_$i"]) {
					if (strlen(trim($_POST["title_$i"])) >0 && strlen(trim($_POST["url_$i"])) >0  && strlen(trim($_POST["desc_$i"])) >0) {
						$ag = new WTG_Extrafeed();
						$ag->initDB();
						$extrafeeds_list = $ag->get_all_extrafeedsDB();
						$id = $ag->add_extrafeedDB(trim($_POST["title_$i"]), trim($_POST["url_$i"]), trim($_POST["desc_$i"]));
						if ($id) {
						   // Clear fields
							unset($_POST["title_$i"]);
							unset($_POST["url_$i"]);
							unset($_POST["desc_$i"]);
						}
					}
				}
			}
			$url = 'admin.php?page=manage_extrafeeds';
			$url = wp_nonce_url($url, 'manage_extrafeeds');
			echo '<div class="updated fade"><p>Feed added!</p></div>';
			echo '<SCRIPT language="JavaScript">
					function closeWindow()
					{
						window.opener.window.location.reload(true);
						window.self.close()
					}
					setTimeout("closeWindow()", 2000);
			</script>';
			return;
		}
	}
	?>
	<div class="wrap">
		<h2>Add Extrafeed</h2>
		<form action = "" method = "post">
	<?php
	if($_GET['url']) {
		$_GET['url'] = str_replace("^","/",$_GET['url']);
		$pos = strpos($_GET['url'],'http://');
		if($pos === false) {
			$_GET['url'] = 'http://'.$_GET['url'];
		}
		
		$response = wtg_verified_url($_GET['url']);
		//echo $_GET['url'];
		if($response)
		{
			require_once (ABSPATH . WPINC . '/class-feed.php');
			
			$cache_location = dirname(__FILE__);
			$rss = new SimplePie();
			$rss->set_feed_url($_GET['url']);
			$rss->set_cache_location($cache_location);
			$rss->init();
			$rss->handle_content_type();
			
			//$rss = fetch_feed($_GET['url']);
			//$rss -> init();
			//$rss -> handle_content_type();
			//$maxitems = $rss -> get_item_quantity();
			
			if( is_wp_error( $rss ) )
			{
				echo $rss->get_error_message();
			}
			else 
			{
				$rss_items=$rss->get_items(0, $maxitems);

				wp_nonce_field('add_extrafeed');
	
				$count=0;
				foreach ( $rss_items as $item ) 
				{
					$count++;
					$link = $item->get_link();
					while ( stristr($link, 'http') != $link )
						$link = substr($link, 1);
					$link = esc_url(strip_tags($link));
					$title = esc_attr(strip_tags($item->get_title()));
					$desc = str_replace(array("\n", "\r"), ' ', esc_attr(strip_tags(@html_entity_decode($item->get_description(), ENT_QUOTES, get_option('blog_charset')))));
					$desc = wp_html_excerpt( $desc, 360 ) . ' [&hellip;]';
					$desc = esc_html( $desc );
					?>
						<p>
							<label>Title:</label>
							<input type="text" id="title" name="title_<?=$count;?>" value="<?php echo isset($title)?$title:'';  ?>" size="35"/> <span class="submit"><input type="checkbox" name="rss_<?=$count;?>" value="1" "checked"/></span>
						</p>
						<p>
							<label>URL:</label>
							<input type="text" id="url" name="url_<?=$count;?>" value="<?php echo isset($link)?$link:''; ?>" size="35"/> 
						</p>
						<p>
							<label>Description:</label>
							<textarea id="desc" name="desc_<?=$count;?>" cols="25" rows="5" ><?php echo isset($desc)?$desc:''; ?></textarea>
						</p>
					<?php				
				}
				?>
					<p class="submit">
						<input type="hidden" name="totalrss" value="<?=$count;?>" />
						<input type="submit" name="addbulkextrafeed" value="Add &raquo;" />
						<input type="submit" name="canceladdextrafeed" value="Cancel &raquo;" />
					</p>
				<?php
			}
		}
		else
		{
			echo "Url is not valid.";
			return;
		}
	}
	else
	{
		echo "Rss Url is not specified.";
	}
?>
		</form>
	</div>
<?php
	exit;
}


function wtg_verified_url($url) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
	$ret = curl_exec($ch);
	curl_close($ch);
	return $ret;
}
?>