<?php
/*
* Options
*
* 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__) . '/rss_cron_job.php');

require_once(dirname(__FILE__) . '/rss_log.php');
require_once(dirname(__FILE__) . '/export_aggregators.php');
require_once(dirname(__FILE__) . '/process_submit.php');
require_once(dirname(__FILE__) . '/form_parser.php');
require_once(dirname(__FILE__) . '/rss_database.php');
require_once(dirname(__FILE__) . '/feed_generator.php');
require_once(dirname(__FILE__) . '/extrafeed_model.php');
require_once(dirname(__FILE__) . '/curl_functions.php');
require_once(dirname(__FILE__) . '/other_functions.php');
require_once(dirname(__FILE__) . '/http_functions.php');

function wtg_test() {
	$id = 71;
	$post = get_post($id);
	wtg_publish_post($post);
}

function isValidURL($url)
{
	return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}

function wtg_jquery_publish_post($postID) {
	$post = get_post($postID);
	global $logger, $indent;
	$GLOBALS['wtg']['postID'] = $postID;
	// works for published post only
	if($post->post_status == 'publish') {
		$wtg_option = get_option('wtg_option');
		if(!empty($wtg_option['processing']) && $wtg_option['registration']) {
			$logger = new WTG_Rss_Log();
			$logger->openlog();
			$logger->info("A post was just published(postId=$postID). About to Trigger feed submission session.");
			$GLOBALS['wtg']['feedName'] = wtg_dump_feed($postID);
			if (empty($GLOBALS['wtg']['feedName'])) {
				$logger->error("Dump feed FAIL exit");
				return;
			}
			$logger->info("Feed url will be " . wtg_callback_rss_feed_url(array('feed_name' => $GLOBALS['wtg']['feedName'])));
			$return_info=wtg_submit_rss();
			$logger->closelog();
			$result=wtg_get_version(WTG_UPGRADE_VERSION_URL);
			$version_message='';
			if(version_compare($result, WTG_CURRENT_VERSION, '>')) {
				$version_message="###################################\nA new version of Web Traffic Genius is available.\n###################################\n\n";
			}
			
			// send the log
		 	if (!empty($wtg_option['email']) && !empty($wtg_option['latest'])) {
		       		wp_mail($wtg_option['email'], 'Latest RSS feed submission log', $version_message.$logger->get_latest_log_text());
			} 
			if (!empty($wtg_option['email']) && !empty($wtg_option['complete'])) {
			       wp_mail($wtg_option['email'], 'Complete RSS feed submission log', $version_message.$logger->get_complete_log_text());
			}
		}
		return $return_info;
	}
}


function wtg_options() {
	// java script function to handle the sub section of aggregator list.
	wtg_java_script();
	
	if(isset($_GET['action']) && ($_GET['action'] == 'jquery_submit_feed')) {
	
		if(!function_exists('json_encode'))
		{
			require_once(dirname(__FILE__).'/JSON.php');
			$GLOBALS['JSON_OBJECT'] = new Services_JSON();
			function json_encode($value)
			{
				return $GLOBALS['JSON_OBJECT']->encode($value);
			}

			function json_decode($value)
			{
				return $GLOBALS['JSON_OBJECT']->decode($value);
			}
		}
		$result=json_encode(wtg_jquery_publish_post($_GET[id]));
		if($result[success]) {
			print '<div class="updated fade below-h2" id="temp"><p>Feed submitted successfully!</p></div>';
		}
		return $result;
		exit;
	}

	$wtg_option = get_option('wtg_option');
	if (isset($_POST['forTest'])) {
		wtg_test();
	}
	if (isset($_POST['postExisting'])) {
		wtg_submit_existing();
	} elseif (isset($_POST['updateOption'])) {
		$error = '';
		if (!empty($_POST['email']) && !is_email(trim($_POST['email']))) {
			$error = 'Please input a valid email address.';
		}
		$wtg_option['email'] = trim($_POST['email']);
		if (!empty($_POST['latest'])) {
			$wtg_option['latest'] = 1;
		} else {
			$wtg_option['latest'] = 0;
		}
		if (!empty($_POST['minextrafeed']) && !is_numeric(trim($_POST['minextrafeed']))) {
			$error = 'Minimum extra feeds should be a number.';
		}
		if (!empty($_POST['maxextrafeed']) && !is_numeric(trim($_POST['maxextrafeed']))) {
			$error = 'Maxmimum extra feeds should be a number.';
		}
		if (!empty($_POST['complete'])) {
			$wtg_option['complete'] = 1;
		} else {
			$wtg_option['complete'] = 0;
		}
		if (!empty($_POST['processing'])) {
			$wtg_option['processing'] = 1;
		} else {
			$wtg_option['processing'] = 0;
		}
		$wtg_option['feed_length'] = $_POST['feed_length'];
		$wtg_option['feedType'] = $_POST['feedType'];
		
		if (is_dir(wtg_detect_doc_root() . '/' . trim($_POST['feedDir'])))
			$wtg_option['feedDir'] = trim($_POST['feedDir']);
		else
			$error = trim($_POST['feedDir']).' is not a directory but a file. Please create a directory.';
		//$wtg_option['feedDir'] = trim($_POST['feedDir']);

		$wtg_option['cron_enabled'] = empty($_POST['cron_enabled'])?0: 1;
		$wtg_option['extrafeeds']   = empty($_POST['extrafeeds'])?0: 1;
		$wtg_option['minextrafeed'] = empty($_POST['minextrafeed'])?0: $_POST['minextrafeed'];
		$wtg_option['maxextrafeed'] = empty($_POST['maxextrafeed'])?0: $_POST['maxextrafeed'];
		$wtg_option['auto_queue']   = empty($_POST['auto_queue'])?0: 1;	
		
		$wtg_option['site_number_per_thread'] = empty($_POST['site_number_per_thread'])?SITE_NUMBER_PER_THREAD_DEFAULT: $_POST['site_number_per_thread'];
		$wtg_option['cron_interval']          = empty($_POST['cron_interval'])?CRON_INTERVAL_DEFAULT: $_POST['cron_interval'];
		$wtg_option['posts_per_cron_job']     = empty($_POST['posts_per_cron_job'])?POSTS_PER_CRON_JOB_DEFAULT: $_POST['posts_per_cron_job'];
		$wtg_option['wtg_related_posts']      = empty($_POST['wtg_related_posts'])?WTG_RELATED_POSTS_DEFAULT: $_POST['wtg_related_posts'];
		$wtg_option['wtg_summarized_feed']    = empty($_POST['wtg_summarized_feed'])?WTG_SUMMARIZED_FEED_DEFAULT: $_POST['wtg_summarized_feed'];

		if (empty($error)) {
			update_option('wtg_option', $wtg_option);
			echo '<div class="updated fade"><p>Options saved.</p></div>';
		} else {
			echo '<div class="error"><p>' . $error . '</p></div>';
		}
		
			
	}
	// default: Processing Active on
	if (!isset($wtg_option['processing'])) {
		$wtg_option['processing'] = 1;
	}
	//default: summarized feed description
	if (!isset($wtg_option['feed_length'])) {
		$wtg_option['feed_length'] = 1;
	}
	
	if (isset($_POST['pausePosting'])) {
		if ($wtg_option['pause_posting'] == 1)
			$wtg_option['pause_posting'] = 0;
		else $wtg_option['pause_posting'] = 1;
		
		update_option('wtg_option', $wtg_option);
	}
	
	if (isset($_POST['submitPage'])) {
		if (!empty($_POST['pageID']))
		{
			$page_id = $_POST['pageID'];
			$logger = new WTG_Rss_Log();
			$logger->openlog();
			$logger->info("A page was submitted (pageID=$page_id). About to Trigger feed submission session.");
			$indent = 0;
			$GLOBALS['wtg']['feedName'] = wtg_dump_page_feed($page_id);
			$GLOBALS['wtg']['pageID'] = $page_id;
			if (empty($GLOBALS['wtg']['feedName'])) {
				$logger->error("Dump feed FAIL exit");
				echo "Dump feed FAIL exit";
				return;
			}
			$logger->info("Feed url will be " . wtg_callback_rss_feed_url(array('feed_name' => $GLOBALS['wtg']['feedName'])));
			$return_info=wtg_submit_page_rss();
			$logger->closelog();
			$result=wtg_get_version(WTG_UPGRADE_VERSION_URL);
			$version_message='';
			if(version_compare($result, WTG_CURRENT_VERSION, '>')) {
				$version_message="###################################\nA new version of Web Traffic Genius is available.\n###################################\n\n";
			}
			
			// send the log
			if (!empty($wtg_option['email']) && !empty($wtg_option['latest'])) {
					wp_mail($wtg_option['email'], 'Latest RSS feed submission log', $version_message.$logger->get_latest_log_text());
			} 
			if (!empty($wtg_option['email']) && !empty($wtg_option['complete'])) {
				   wp_mail($wtg_option['email'], 'Complete RSS feed submission log', $version_message.$logger->get_complete_log_text());
			}
		}
		else $error = 'Page URL is empty.';
		
		if (!empty($error)) echo '<div class="error"><p>' . $error . '</p></div>';
		
	}
	wtg_db_check_and_create();
	wtg_messages();
?>
<div class="wrap">
	<h2>Options</h2>
	<?php
	$message = wtg_check_setting();
	if (!empty($message)) {
		echo '<div class="error">' . $message . '</div>';
	}
	?>
	<p>Enter the email address below you would like to receive a copy of the log from the most current operation each time you post. Click all checkboxes if you want the complete log sent as well.</p>
	<form method="post" action="">
		<p>
			<input type="text" name="email" value="<?php echo empty($wtg_option['email'])?'':$wtg_option['email']; ?>" />
	    	Latest Log<input type="checkbox" <?php echo !empty($wtg_option['latest']) ?'checked':''; ?> name="latest" value="1" />
	    	Complete Log<input type="checkbox" <?php echo !empty($wtg_option['complete']) ?'checked':''; ?> name="complete" value="1" />
	    </p>
		<?php if ($wtg_option['pause_posting'] == 1) $text = "Start posting RSS Feeds";
			  else $text = "Pause posting RSS Feeds"; ?>
		<p class="submit"><input type="submit" name="pausePosting" value="<?php echo $text; ?>" /></p>
		<p>
			<label>Feed Type</label>
			<select name="feedType">
				<option  value="rss" <?php echo !empty($wtg_option['feedType']) && $wtg_option['feedType'] == 'rss'?'selected':''; ?> >RSS</option>
				<option  value="rss2" <?php echo !empty($wtg_option['feedType']) && $wtg_option['feedType'] == 'rss2'?'selected':''; ?> >RSS2</option>
				<option  value="atom" <?php echo !empty($wtg_option['feedType']) && $wtg_option['feedType'] == 'atom'?'selected':''; ?> >Atom</option>
			</select>
		</p>
		<!--<p><label>Processing Active</label> <input type="checkbox" <?php echo empty($wtg_option['processing']) ? '':'checked'; ?> name="processing" value="1"/></p>-->
		<p>RSS Feed description (To display full post in feed please select the detailed option.)</p>
		<p><label>Summarized</label> <input type="radio" name="feed_length" value="1" <?php 
			if($wtg_option['feed_length'] == '1') {
				echo "checked";
			}
			?>/> <label>Detailed</label> <input type="radio" <?php 
			if($wtg_option['feed_length'] == '2') {
				echo 'checked'; 
			}
			?> name="feed_length" value="2"/></p>
	        <p>Enter the directory where you want to put the feed.(under document root.e.g. blogfeed)</p>
		<p><input type="text" name="feedDir" value="<?php echo empty($wtg_option['feedDir'])?'':$wtg_option['feedDir']; ?>" /></p>
		<p>Enable Extra Feeds<input type="checkbox" <?php echo !empty($wtg_option['extrafeeds']) ?'checked':''; ?> name="extrafeeds" value="1" /></p>
		<p>Minimum Extra Feeds<input type="text" name="minextrafeed" value="<?php echo empty($wtg_option['minextrafeed'])?'':$wtg_option['minextrafeed']; ?>" /></p>
		<p>Maximum Extra Feeds<input type="text" name="maxextrafeed" value="<?php echo empty($wtg_option['maxextrafeed'])?'':$wtg_option['maxextrafeed']; ?>" /></p>
		<p>
			<label>Enable Cron Job</label>
     		<input type="checkbox" name="cron_enabled" <?php echo empty($wtg_option['cron_enabled'])?'':'checked';?> value="1" />
     	</p>
		<p>
			<label>Automatically queue more posts when empty</label>
     		<input type="checkbox" name="auto_queue" <?php echo empty($wtg_option['auto_queue'])?'':'checked';?> value="1" />
     	</p>
		<br/>
		<small><a href="#" onclick="showadvancedoptions()"><b>Advanced Options</b></a></small>
		<div class="wrap" id="advanced_options" style="display:none">
			<p>These are Advanced Options for users. Please DO NOT modify these settings if you do not know what you are doing.</p>
			<p>Sites per Thread: <input type="text" name="site_number_per_thread" value="<?php echo isset($wtg_option['site_number_per_thread'])?$wtg_option['site_number_per_thread']:SITE_NUMBER_PER_THREAD_DEFAULT; ?>" /></p>
			<p>Cron Interval (minutes): <input type="text" name="cron_interval" value="<?php echo isset($wtg_option['cron_interval'])?$wtg_option['cron_interval']:CRON_INTERVAL_DEFAULT; ?>" /></p>
			<p>Posts per Cron Job: <input type="text" name="posts_per_cron_job" value="<?php echo isset($wtg_option['posts_per_cron_job'])?$wtg_option['posts_per_cron_job']:POSTS_PER_CRON_JOB_DEFAULT; ?>" /></p>
			<p>Related Posts: <input type="text" name="wtg_related_posts" value="<?php echo isset($wtg_option['wtg_related_posts'])?$wtg_option['wtg_related_posts']:WTG_RELATED_POSTS_DEFAULT; ?>" /></p>
			<p>Summarized Feed Length: <input type="text" name="wtg_summarized_feed" value="<?php echo isset($wtg_option['wtg_summarized_feed'])?$wtg_option['wtg_summarized_feed']:WTG_SUMMARIZED_FEED_DEFAULT; ?>" /></p>
		</div>
	    <p class="submit"><input type="submit" name="updateOption" value="Update Options &raquo;" /></p>
	<?php
    if (empty($error) && $wtg_option['cron_enabled']) {
    ?>
		<p>It is recommended that you copy the following code in the text area into a php script and execute the script periodically using a cron job. Otherwise, the jobs in the schedule job list can only be triggered when someone visits your blog (and activates the script).</p>
		<p><textarea style="width: 98%;" rows="5"><?php echo htmlspecialchars(wtg_write_cron_job_script()); ?></textarea></p>
	<?php
    }
    ?>

	    <p>You can post existing posts to the rss aggregator sites here. Just click on the "Post Existing" button. It is recommended that you enable a cron job first.</p>
     	<p><input type="submit" name="postExisting" value="Post Existing &raquo;" onclick="return confirm('Do you really want to submit feeds of existing posts?');"/></p>
		<br/>
		<p>You can also submit your Wordpress pages as rss feeds to aggregates. Just paste the page URL below and click the button.</p>
		<p>Page URL: 
		<select name="pageID" > 
		 <option value="">
		<?php echo attribute_escape(__('Select page')); ?></option> 
		 <?php 
		  $pages = get_pages(); 
		  foreach ($pages as $pagg) {
			$option = '<option value="'.$pagg->ID.'">';
			$option .= $pagg->post_title;
			$option .= '</option>';
			echo $option;
		  }
		 ?>
		</select>
		<p><input type="submit" name="submitPage" value="Submit Page Feeds &raquo;" /></p>
		
   </form>
</div>
<?php
}

function wtg_check_setting() {
	$message = '';

	$feed_dir_mode = '0766';
	$aggregator_xml_mode = '0766';

	$cookiejar_mode = $aggregator_xml_mode;

	$wtg_option = get_option('wtg_option');
	if (empty($wtg_option['feedDir'])) {
		$message .= 'Please enter the directory you want to put the feed under the document root in option page.<br/>';
	} else {
		// $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'];
		}
		if (!file_exists($feed_absdir)) {
			$message .= 'Please create the directory ' . $wtg_option['feedDir'] . ' for feeds to be stored in the root folder ' . wtg_detect_doc_root() . '<br/>';
		} else {
			if (wtg_is_above_dir(realpath($feed_absdir), realpath(wtg_detect_doc_root()))) {
				$message .= "The directory must be under ". wtg_detect_doc_root() . ". <br/>";
			}
			if (!is_writable ($feed_absdir)) {
				$message .= "Please chmod $feed_absdir to $feed_dir_mode. <br/>";
			}
		}
	}

	/*if (!is_writable (AGGREGATORS_XML_TEMPLATE)) {
		$message .= "Please chmod " . AGGREGATORS_XML_TEMPLATE . " to $aggregator_xml_mode. <br/>";
	}*/
	if (!is_writable (COOKIEJAR)) {
		$message .= "Please chmod " . COOKIEJAR . " to $cookiejar_mode. <br/>";
	}
	if (!file_exists(dirname(__FILE__) . '/captcha')) {
		//mkdir(dirname(__FILE__) . '/captcha');
		$message .= "Please create directory " . dirname(__FILE__) . '/captcha' . " and chmod to $aggregator_xml_mode. <br/>";
	}
	else{
		//chmod(dirname(__FILE__) . '/captcha', 0766);
		if (!is_writable (dirname(__FILE__) . '/captcha')) {
			$message .= "Please chmod " . dirname(__FILE__) . '/captcha' . " to 0777. <br/>";
		}
	}
	if (!is_writable (dirname(__FILE__) . '/config.php')) {
		$message .= "Please chmod " . dirname(__FILE__) . '/config.php' . " to $aggregator_xml_mode. <br/>";
	}

	if (empty($message)) 
		return false;
	return '<p>' . $message . '</p>';
}

function wtg_java_script() {

?>
	<script language="javascript">
	function showadvancedoptions()
	{
		var dv="advanced_options";
		if ((document.getElementById(dv).style.display=="block") || (document.getElementById(dv).style.display=="visible"))
			document.getElementById(dv).style.display="none"
		else{
			document.getElementById(dv).style.display="block"
			document.getElementById(dv).style.display="visible"
		}
		
	}
	</script>
<?php
}
?>