<?php
/*
Part of the Ad Injection plugin for WordPress
http://www.reviewmylife.co.uk/
*/

/*  Copyright 2010 reviewmylife (contact : http://www.reviewmylife.co.uk/)

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

	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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

if (!is_admin()) return;

$adinj_warning_msg_chmod = "";
$adinj_warning_msg_filewrite = "";

function adinj_checkNonce(){
	if (!empty($_POST) && check_admin_referer('_adinj_form')){
		// ok
	} else {
		echo 'Ad Injection: Nonce check has failed.';
		exit();
	}
}

function adinj_update_options($ops){
	update_option('adinj_options', $ops);
	// Refresh options from database as cached values are now invalidated
	global $adinj_data;
	$adinj_data = get_option('adinj_options');
}

function adinj_save_options(){
	// TODO investigate register_settings for a future release
	switch($_POST['adinj_action']){
	case 'Save all settings':
		adinj_checkNonce();
		
		// Extract all know options
		$default_options = adinj_default_options();
		$ops = adinj_options();
		foreach ($default_options as $key => $value){
			if (isset($_POST[$key])){
				$ops[$key] = $_POST[$key];
			}
		}
		
		extract_text_args('ad_code_random_', $ops, 1, 10, ADINJ_AD_PATH.'/ad_random_');
		extract_text_args('ad_code_top_', $ops, 1, 10, ADINJ_AD_PATH.'/ad_top_');
		extract_text_args('ad_code_bottom_', $ops, 1, 10, ADINJ_AD_PATH.'/ad_bottom_');
		extract_text_args('ad_code_footer_', $ops, 1, 10, ADINJ_AD_PATH.'/ad_footer_');
		
		extract_text_args('ad_code_random_alt_', $ops, 1, 2, ADINJ_AD_PATH.'/ad_random_alt_');
		extract_text_args('ad_code_top_alt_', $ops, 1, 2, ADINJ_AD_PATH.'/ad_top_alt_');
		extract_text_args('ad_code_bottom_alt_', $ops, 1, 2, ADINJ_AD_PATH.'/ad_bottom_alt_');
		extract_text_args('ad_code_footer_alt_', $ops, 1, 2, ADINJ_AD_PATH.'/ad_footer_alt_');
		
		extract_text_args('ad_referrers', $ops);
		extract_text_args('blocked_ips', $ops);
		
		adinj_update_options($ops);
		
		if (adinj_mfunc_mode()) {
			adinj_write_config_file();
		}

		break;

		case 'Reset to Default':
		adinj_checkNonce();
		adinj_update_options(adinj_default_options());
		break;
		
		case 'Delete settings from DB':
		adinj_checkNonce();
		delete_option('adinj_options');
		adinj_install_db();
		adinj_options(1);
		break;
		
		case 'Delete widget settings from DB':
		adinj_checkNonce();
		delete_option('widget_adinj');
		// TODO add option to delete ads files as well
		break;
	}
}

function extract_text_args($name, &$ops, $start=NULL, $end=NULL, $save_path_stem=NULL){
	if ($start === NULL){
		if (isset($_POST[$name])){
			$ops[$name] = stripslashes($_POST[$name]);
			if ($save_path_stem != NULL){
				write_ad_to_file($ops[$name], $save_path_stem.'1.txt');
			}
		}
	} else {
		for ($i = $start; $i<=$end; ++$i){
			if (isset($_POST[$name.$i])){
				$ops[$name.$i] = stripslashes($_POST[$name.$i]);
				if ($save_path_stem != NULL){
					write_ad_to_file($ops[$name.$i], $save_path_stem.$i.'.txt');
				}
			}
		}
	}
}

// Test reminder: These generated functions won't exist until the first save
// so be careful if adding any new ones - they might not exist yet, but could
// still be referenced by adshow.
function adinj_write_config_file(){
	if (!adinj_mfunc_mode()) return;
	$ops = adinj_options();
	
	$allow_referrers = adinj_ticked('sevisitors_only')?'true':'false';
	$allowed_referrers_list = adinj_quote_list('ad_referrers');
	
	$block_ips = adinj_ticked('block_ips')?'true':'false';
	$blocked_ip_list = adinj_quote_list('blocked_ips');
	
	$block_referrers = adinj_ticked('block_keywords')?'true':'false';
	$blocked_referrers_list = adinj_quote_list('blocked_keywords');
	$block_hours = $ops['block_ads_for_hours'];
	
	$debug_mode = adinj_ticked('debug_mode')?'true':'false';
	
	$version = adinj_db_version($ops);
	
	$config = <<<CONFIG
<?php
/*
Ad Injection config file dbversion=$version
DO NOT EDIT MANUALLY
This file is generated by Ad Injection
*/

function adinj_config_allow_referrers() { return $allow_referrers; }
function adinj_config_allowed_referrers_list() { return array($allowed_referrers_list); }

function adinj_config_block_ips() { return $block_ips; }
function adinj_config_blocked_ips_list() { return array($blocked_ip_list); }

function adinj_config_block_referrers() { return $block_referrers; }
function adinj_config_blocked_referrers_list() { return array($blocked_referrers_list); }
function adinj_config_block_hours() { return $block_hours; }

function adinj_config_block_after_ad_click() { return false; }

function adinj_config_debug_mode() { return $debug_mode; }

?>
CONFIG;

	adinj_write_file(ADINJ_CONFIG_FILE, $config, 0640);

}

function adinj_write_file($path, $content, $permission){
	$ops = adinj_options();
	global $adinj_warning_msg_filewrite;
	
	$dir = dirname($path);
	if (!@file_exists($dir)){
		if (!@mkdir($dir, 0750)){
			@mkdir($dir, 0755) or $adinj_warning_msg_filewrite .= "<br />Warning: could not create dir: ".$dir.". Please create it manually and try again.";
		}		
	}
	
	$handle = @fopen($path, "w");
	if (strlen($content) > 0){
		@fwrite($handle, $content) or $adinj_warning_msg_filewrite .= "<br />Warning: could not write to file: $path";
	}
	@fclose($handle);
	if (@file_exists($path)){
		adinj_chmod($path, $permission);
	}
}

function adinj_chmod($path, $permission){
	global $adinj_warning_msg_chmod;
	$oldperm = substr(decoct(@fileperms($path)), -3);
	$newperm = decoct($permission);
	if ($newperm == $oldperm) return;
	@chmod($path, $permission) or $adinj_warning_msg_chmod .=  "<br />Warning: chmod $newperm " .
		"on $path failed. Current permissions: $oldperm<br />	Try manually updating the permission if problems occur.";
}

function adinj_get_logo(){
	return '<a href="http://www.reviewmylife.co.uk/" target="_new"><img src="'. WP_PLUGIN_URL . '/ad-injection/rml-micro-logo.png" width="16" height="16" border="0" alt="reviewmylife" /></a>';
}

// only for Ad Injection admin pages
function adinj_admin_print_scripts_main(){
	adinj_admin_print_scripts_widgets();
}

// only for widgets.php
function adinj_admin_print_scripts_widgets(){
	echo "<!--start of Ad Injection scripts-->";
	adinj_javascript_addtext();
echo <<<HTML
	<script type="text/javascript">
	function adinj_toggle_click(show_setting_id, toggle_button_id, toggle_box_id){
		jQuery('#'+show_setting_id).val(jQuery('#'+toggle_box_id).is(":hidden"));
		adinj_button_update(show_setting_id, toggle_button_id);
		jQuery('#'+toggle_box_id).slideToggle(300);
	}
	function adinj_button_update(show_setting_id, toggle_button_id){
		if (jQuery('#'+show_setting_id).val() == 'true'){
			jQuery('#'+toggle_button_id).text('-');
		} else {
			jQuery('#'+toggle_button_id).text('+');
		}
	}
	</script>
	<!--end of Ad Injection scripts-->
	<script type="text/javascript">
        document.write('<style type="text/css" media="screen">.hiddenbox { display: none; }</style>');
	</script>
HTML;


}

function adinj_options_page(){
	if (isset($_POST['adinj_action'])){
		adinj_save_options();
	}
	
	adinj_upgrade_db_if_necessary();
	$ops = adinj_options();
	
	echo '<div class="wrap" style="width:950px;">';

	if (adinj_problem_with_wpminify_check()){
		echo '<div id="ad-injection-warning" class="error"><p><strong>';
		echo adinj_get_problem_with_wpminify_message();
		echo '</strong></p></div>';
	}
	
	echo '<div id="icon-options-general" class="icon32"></div><h2>Ad Injection ' . adinj_get_version() . adinj_get_logo() . '</h2>';
	
	adinj_top_message_box();
	
	adinj_admin_tabs();
	
	echo '<div style="width:258px; float:right;">';
	
	switch( $_GET[ 'tab' ] ) {
	case "adrotation":
		require_once(ADINJ_PATH . '/ui-tab-adrotation.php');
		adinj_side_donate_box();
		adinj_side_info_box();
		echo '</div>';
		echo '<form name="adinjform" method="post" action="">';
		wp_nonce_field('_adinj_form');
		adinj_tab_adrotation();
		break;
	case "debug":
		require_once(ADINJ_PATH . '/ui-tab-debug.php');
		adinj_side_donate_box();
		adinj_side_info_box();
		echo '</div>';
		echo '<form name="adinjform" method="post" action="">';
		wp_nonce_field('_adinj_form');
		adinj_tab_debug();
		break;
	case "main":
	default:
		require_once(ADINJ_PATH . '/ui-tab-main.php');
		adinj_side_advert_box();
		adinj_side_status_box();
		adinj_side_donate_box();
		adinj_side_info_box();
		echo '</div>';
		echo '<form name="adinjform" method="post" action="">';
		wp_nonce_field('_adinj_form');
		adinj_tab_main();
		break;
	}
	echo '</form>';
	echo '</div> <!--wrap-->';
}

function adinj_top_message_box(){
	$ops = adinj_options();
	if (isset($_POST['adinj_action'])) {
        echo '<div id="message" class="updated below-h2"><p style="line-height:140%"><strong>';
        echo 'All settings saved: ';
		if (is_plugin_active('wp-super-cache/wp-cache.php')){
			echo "You might need to <a href='options-general.php?page=wpsupercache&amp;tab=tester'>clear your WP Super Cache cache</a> for the settings to take effect.";
		} else if (is_plugin_active('w3-total-cache/w3-total-cache.php')){
			echo "You might need to <a href='options-general.php?page=w3tc_general'>clear your W3 Total Cache cache</a> for the settings to take effect.";
		} else if (is_plugin_active('wp-cache/wp-cache.php')){
			echo "You might need to <a href='options-general.php?page=wp-cache/wp-cache'>clear your WP Cache cache</a> for the settings to take effect.";
		} else {
			echo "If you are using a caching plugin you might need to delete its cache for any changes to take effect.";
        }
		echo '</strong>';
		if ($ops['debug_mode']=='on' && $ops['ads_enabled'] == 'on'){
			echo "<br /><b>Recommendation:</b> Turn <a href='?page=ad-injection&amp;tab=debug#debugging'>debug mode off</a> once you have got your ads working.";
		}
		if (adinj_mfunc_mode()){
			if (!is_supported_caching_plugin_active()){
				echo "<br /><b>Recommendation:</b> It looks like you don't have a supported caching plugin (WP Super Cache, W3 Total Cache or WP Cache) active. Therefore <a href='#restrictions'>direct insertion modes</a> might be better for you.";
			}
			global $adinj_warning_msg_filewrite;
			if (!empty($adinj_warning_msg_filewrite)){
				echo $adinj_warning_msg_filewrite;
				echo "<br />Workaround: If you are unable to fix these errors you will have to switch to a <a href='#restrictions'>direct insertion mode</a> (however dynamic features won't work if you are using a caching plugin).";
			}
		}
		global $adinj_warning_msg_chmod;
		if (!empty($adinj_warning_msg_chmod)){
			echo '<br />Info: Some warnings were generated by chmod. See the <a href="#warning_msg_chmod">warnings below</a> for more info.';
		}
		foreach (array('top', 'random', 'bottom', 'footer') as $type){
			$adcount = adinj_count_live_ads($type, $ops);
			if ($adcount > 0 && !adinj_ad_type_enabled($type)){
				$adads = 'ad';
				$isare = 'is';
				$theyit = 'it is';
				if ($adcount > 1) { $adads = 'ads'; $isare = 'are'; $theyit = 'they are'; } 
				echo "<br /><font color='red'>Warning: $adcount $type $adads $isare defined, but $theyit not enabled.</font>";
			}
		}
		if ($ops['ads_enabled'] != 'on'){
			echo '<br /><font color="red">Warning: Ads are not enabled. You need to turn the ads on for everyone to see them.</font>';
		}
		echo '</p></div>';
		
	} else if (!isset($_GET['tab'])){
		echo '<div id="message" class="updated below-h2"><p style="line-height:140%"><strong>';
		echo "11th August 2012: Add table exclusion option. Remove old advert - the space is now available. Please contact me ASAP if you spot any bugs, or odd behaviour via the <a href='http://wordpress.org/tags/ad-injection?forum_id=10'target='_new'>Ad Injection WordPress forum</a> or my ".'<a href="'.adinj_feedback_url().'" target="_new">quick feedback form</a>. If you like the plugin please consider making a donation using the PayPal box below :)'."<br/>And finally I've just released an app to help you try Facebook Likes, Twitter Tweets and Google +1s on your website. It is called <a href='http://www.reviewmylife.co.uk/blog/2012/07/14/web-social-stats-for-seo/' target='_new'>Web Social Stats for SEO</a>.";
		echo '</strong></p></div>';
	}
}

function adinj_side_donate_box(){
?>
	<div class="postbox-container" style="width:258px;">
		<div class="metabox-holder">	
		<div class="meta-box-sortables" style="min-height:200px;">
		<div class="postbox">
		<h3 class="hndle"><span><?php echo adinj_get_logo(); ?> Donate $10, $20 or $50!</span></h3>
		<div class="inside" style="margin:5px;">
		I have spent many hundreds of hours creating this plugin. If it helps you to make money please consider making a donation. Thank you!

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="JP5ECV7NX7GSY">
<input type="hidden" name="item_name" value="Ad Injection">
<input type="hidden" name="item_number" value="Ad Injection">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHosted">
<p>Amount:<br>
<input class="omni_donate_field" type="text" name="amount" size="9" title="The amount you wish to donate" value="10">
<select id="currency_code" name="currency_code">
	<option value="USD">U.S. Dollars</option>
<?php
	if (1==2 && strpos(home_url(), '.co.uk') !== false){
		echo '<option value="GBP" selected="selected">Pounds Sterling</option>';
	} else {
		echo '<option value="GBP">Pounds Sterling</option>';
	}
?>
    <option value="AUD">Australian Dollars</option>
    <option value="CAD">Canadian Dollars</option>
    <option value="EUR">Euros</option>
    <option value="JPY">Yen</option></select>
</p>
<center>
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" width="166" height="53" name="submit" alt="PayPal - The safer, easier way to pay online."></center>
</form>
				
		</div>
		</div>	
		</div>
		</div>
	</div> 
	<?php
}

function adinj_side_info_box(){
?>
	<div class="postbox-container" style="width:258px;">
		<div class="metabox-holder">	
		<div class="meta-box-sortables">
		<div class="postbox">
		<h3 class="hndle"><span><?php echo adinj_get_logo(); ?> Info</span></h3>
		<div class="inside" style="margin:5px;">
			<h4>More Ad Injection information</h4>
			<ul>
			<li><a href="http://wordpress.org/extend/plugins/ad-injection/faq/" target="_new">Ad Injection FAQ</a></li>
			<li><a href="http://wordpress.org/extend/plugins/ad-injection/other_notes/" target="_new">Ad Injection Troubleshooting</a></li>
			<li><a href="http://www.reviewmylife.co.uk/blog/2010/12/06/ad-injection-plugin-wordpress/" target="_new">Ad Injection at reviewmylife</a></li>
			<li><b><a href="<?php echo adinj_feedback_url(); ?>" target="_new">Report a bug / give feedback</a></b></li>
			</ul>
			
			<h4><font color="red">Important!</font></h4>
			<p>You are responsible for making sure the ad settings and positioning you define are in compliance with your ad provider's terms of service! Failure to do so could get you banned by them!</p>
		
			<h4><font color="red">Still in development</font></h4>
			<p>I'm actively listening to your feedback and fixing problems, and will be adding new features later in 2012. Please let me know if you like the plugin too!</p>
			
			<h4>More by this author</h4>
			<ul>
			<li><a href="http://www.lorisware.com/solar-balls/" target="_new">Solar Balls for iOS</a> New!</li>
			<li><a href="http://wordpress.org/extend/plugins/ad-logger/" target="_new">Ad Logger plugin for WordPress</a></li>
			<li><a href="http://www.reviewmylife.co.uk/" target="_new">www.reviewmylife.co.uk</a></li>
			<li><a href="http://www.advancedhtml.co.uk/" target="_new">www.advancedhtml.co.uk</a></li>
			</ul>
		</div>
		</div>	
		</div>
		</div>
	</div> 
	<?php
}

function adinj_feedback_url(){
	$wp_version = get_bloginfo('version');
	$ad_version = adinj_get_version();
	$data = urlencode($wp_version." / ".$ad_version);
	return "https://spreadsheets.google.com/viewform?formkey=dFUwZzBYcG1HNzNKMmJZdWFDdFhkY0E6MQ&amp;entry_3=$data";
}

function adinj_add_checkbox($name, $class=NULL, $all=NULL){
	$classhtml = '';
	$jshtml = '';
	if ($class != NULL) $classhtml=' class="'.$all.$class.'"';
	if ($all != NULL) $jshtml = 'onClick="javascript:adinj_toggle_tick_boxes('."'".$class."',this.checked".');"';
	echo '<input type="hidden" name="'.$name.'" value="off" />';
	echo '<input type="checkbox" name="'.$name.'" '.adinj_ticked($name)."$classhtml $jshtml />";
	if ($all != NULL && adinj_ticked($name)){
	?>
	<script type="text/javascript">
	document.write('<style type="text/css" media="screen">.<?php echo $class; ?> { opacity:0.3; filter:alpha(opacity=30) }</style>');
	</script>
	<?php
	}
}

// From WP Super cache
function adinj_admin_tabs( $current = 0 ) {
	global $wp_db_version;
	if ( $current == 0 ) {
		if ( isset( $_GET[ 'tab' ] ) ) {
			$current = $_GET[ 'tab' ];
		} else {
			$current = 'main';
		}
	}
	$tabs = array( 'main' => __( 'Main', 'ad-injection' ), 'adrotation' => __( 'Ad codes / Ad rotation / Advanced', 'ad-injection' ), 'debug' => __( 'Debug' ) );
	$links = array();
	foreach( $tabs as $tab => $name ) {
		if ( $current == $tab ) {
			$links[] = "<a class='nav-tab nav-tab-active' href='?page=ad-injection&amp;tab=$tab'>$name</a>";
		} else {
			$links[] = "<a class='nav-tab' href='?page=ad-injection&amp;tab=$tab'>$name</a>";
		}
	}
	
	echo '<div id="nav"><h3 class="themes-php">';
	echo implode( "", $links );
	echo '</h3></div>';
}

// TODO replace with new Javascript
function adinj_postbox_start($title, $anchor, $width='650px'){
	$ops = adinj_options();
	?>
	<div class='postbox-container' style='width:<?php echo $width; ?>;float:left; clear:left;'>
	<a name="<?php echo $anchor; ?>"></a>
	<div class="metabox-holder">
	<div class="postbox">
	<input type="submit" style="float:right" class="button-primary" name="adinj_action" value="<?php _e('Save all settings', 'adinj') ?>" />
	
	<?php
	$anchorclick = $anchor.'_click';
	$anchorupdate = $anchor.'_update';
	$anchorhide = 'ui_'.$anchor.'_hide';
	$hide = $ops[$anchorhide];
echo <<<HTML
	<input type='hidden' id='$anchorhide' name='$anchorhide' value='$hide' />
	<a href="#" onclick='javascript:$anchorclick();return false;' style="float:right;display:none" id="toggle-$anchor" class="button">Show/Hide</a>
	<script type="text/javascript">
	$anchorupdate();
	jQuery('#toggle-$anchor').show();
	
	function $anchorclick(){
		jQuery('#$anchorhide').val(!jQuery('#$anchor-box').is(":hidden"));
		jQuery('#$anchor-box').slideToggle(300);
		$anchorupdate();
		return false;
	}
	
	function $anchorupdate(){
		if (jQuery('#$anchorhide').val() == 'false'){
			jQuery('#toggle-$anchor').text('Hide');
		} else {
			jQuery('#toggle-$anchor').text('Show');
		}
	}
	</script>
HTML;
	?>
	
	<h3><?php $info = adinj_get_status($anchor); echo adinj_dot($info[0]); ?> <?php echo adinj_get_logo() . ' ' . $title; ?></h3>
	<?php if($hide == 'true'){ ?>
		<div id="<?php echo $anchor; ?>-box" class="hiddenbox">
	<?php } else { ?>
		<div id="<?php echo $anchor; ?>-box">
	<?php } ?>
	<div class="inside" style="margin:10px">
	<?php
}

function adinj_postbox_end(){
	echo '
	</div> <!--inside-->
	</div> <!--anchor-box-->
	</div> <!--postbox-->
	</div> <!--metabox-holder-->
	</div> <!--postbox-container-->';
}

function adinj_get_status($name){
	$ops = adinj_options();
	$status[] = 'black';
	$status[] = 'Error...';
	if ($name == 'global'){
		if ($ops['exclude_front'] == 'on' &&
			$ops['exclude_home'] == 'on' &&
			$ops['exclude_page'] == 'on' &&
			$ops['exclude_single'] == 'on' &&
			$ops['exclude_archive'] == 'on' &&
			$ops['exclude_search'] == 'on' &&
			$ops['exclude_404'] == 'on'){
			$status[0] = 'red';
			$status[1] = 'excluded from all';
			return $status;
		}
		$val = $ops['ads_enabled'];
		if ($val == 'on'){
			$status[0] = 'green';
			$status[1] = $val;
		} else if ($val == 'off' || $val == ''){
			$status[0] = 'red';
			$status[1] = $val;
		} else if ($val == 'test'){
			$status[0] = 'orange';
			$status[1] = 'test mode';
		}
	} else if ($name == 'mode'){
		$status[0] = 'green';
		if ($ops['ad_insertion_mode'] == 'direct_static') $status[0] = 'orange';
		$status[1] = $ops['ad_insertion_mode'];
	} else if ($name == 'restrictions'){
		$status[0] = 'green';
		$status[1] = "";
		if ($ops['sevisitors_only'] == 'on'){
			$status[1] .= 'referrer';
		}
		if ($ops['sevisitors_only'] == 'on'){
			$status[1] .= ' keywords';
		}
		if ($ops['block_ips'] == 'on' && !empty($ops['blocked_ips'])){
			$status[1] .= ' ip';
		}
	} else if ($name == 'older_than_normal'){
		$status[0] = 'green';
		$days = $ops['ads_on_page_older_than'];
		$status[1] = "> $days days";
	} else if ($name == 'older_than_widgets'){
		$status[0] = 'green';
		$days = $ops['widgets_on_page_older_than'];
		$status[1] = "> $days days";
	} else if ($name == 'adsettings'){
		$status[0] = 'green';
	} else if ($name == 'adverts'){
		if (adinj_count_live_ads('top', $ops) > 0 || adinj_count_live_ads('random', $ops) > 0 || adinj_count_live_ads('bottom', $ops) > 0 || adinj_count_live_ads('footer', $ops) > 0){
			$status[0] = 'green';
		} else {
			$status[0] = 'red';
		}
	} else if ($name == 'filters'){
		$status[0] = 'green';
	} else if ($name == 'debugging'){
		$val = $ops['debug_mode'];
		if ($val == 'on'){
			$status[0] = 'green';
			$status[1] = 'on';
		} else {
			$status[0] = 'red';
			$status[1] = 'off';
		}
	}
	return $status;
}

// This is for 'exclude' options so 'on' is red.
function adinj_green_or_red_dot($option){
	$ops = adinj_options();
	if ($ops[$option] == 'on'){
		return adinj_dot('red');
	} else {
		return adinj_dot('green');
	}
}

function adinj_print_ad_dot($adtype, $pagetype){
	if (adinj_max_num_ads($adtype, $pagetype) > 0){
		echo adinj_dot('green');
	} else {
		echo adinj_dot('red');
	}
}

function adinj_dot($colour){
	return '<span style="color:'.$colour.'">&#x25cf;</span>';
}

function adinj_max_num_ads($adtype, $pagetype){
	$ops = adinj_options();
	if (adinj_ticked('exclude_'.$pagetype)) return 0;
	if ($adtype == 'top' || $adtype == 'random' || $adtype == 'bottom' || 
		$adtype == 'footer' || $adtype == 'widget' || $adtype == 'template'){
		if (adinj_ticked($adtype.'_exclude_'.$pagetype)) return 0;
	}
	if ($adtype == 'top' || $adtype == 'random' || $adtype == 'bottom' || $adtype == 'footer'){
		if (adinj_count_live_ads($adtype, $ops) == 0) return 0;
	}
	if ($pagetype == 'front'){ // front could be an archive or a page so we don't do an ad count
		return 1;
	}
	if ($adtype == 'top' || $adtype == 'bottom'){
		if ($pagetype == "single" || $pagetype == "page"){
			return 1;
		} else if ($pagetype == 'home' || $pagetype == 'archive'){
			return $ops[$pagetype.'_max_num_'.$adtype.'_ads_per_page'];
		} else if ($pagetype == "excerpt"){
			//TODO
		}
	} else if ($adtype == "random"){
		if ($pagetype == "single" || $pagetype == "page"){
			return $ops['max_num_of_ads'];
		} else if ($pagetype == 'home' || $pagetype == 'archive'){
			if ($ops[$pagetype.'_max_num_random_ads_per_post'] > 0) return $ops[$pagetype.'_max_num_random_ads_per_page'];
		} else if ($pagetype == "excerpt"){
			//TODO
		}
	}
	if ($adtype == 'widget' || $adtype == 'footer' || $adtype == 'template'){
		return 1;
	}
	return 0;
}

function adinj_ad_type_enabled($adtype){
	return (adinj_max_num_ads($adtype, 'single') > 0 || adinj_max_num_ads($adtype, 'page') > 0 || adinj_max_num_ads($adtype, 'home') > 0 || adinj_max_num_ads($adtype, 'archive') > 0 || adinj_max_num_ads($adtype, 'front') > 0 || adinj_max_num_ads($adtype, '404') > 0 || adinj_max_num_ads($adtype, 'search') > 0);
}

function adinj_selection_box($name, $values, $type="", $selected_value=NULL){
	$associative = false;
	if (!array_key_exists(0, $values)){
		// Very naive test but works for me.
		$associative = true;
	}

	if ($selected_value == NULL){
		$ops = adinj_options();
		$selected_value = $ops[$name];
	}

	echo "<select name='$name' id='$name'>";
	foreach ($values as $key=>$value){
		$option_value = $value;
		$display_value = $value;
		if ($associative){
			$option_value = $key;
		}
		echo "<option value=\"$option_value\" ";
		if("$selected_value" == "$option_value" ||
			"$selected_value" == ADINJ_DISABLED && "$option_value" == 'd' || //todo remove?
			"$selected_value" == ADINJ_NA && "$option_value" == 'd' ||
			"$selected_value" == ADINJ_RULE_DISABLED && "$option_value" == 'd' || //todo remove?
			"$selected_value" == ADINJ_ONLY_SHOW_IN && "$option_value" == 'o' || 
			"$selected_value" == ADINJ_NEVER_SHOW_IN && "$option_value" == 'n'){
			echo 'selected="selected"';
		}
		$typetxt = $type;
		if (adinj_not_set($option_value)) $typetxt = "";
		if ("$option_value" === 'a') { $display_value = ADINJ_NA; } //TODO remove?
		if ("$option_value" === 'd') { $display_value = ADINJ_NA; }
		if ("$option_value" === 'o') { $display_value = ADINJ_ONLY_SHOW_IN; }
		if ("$option_value" === 'n') { $display_value = ADINJ_NEVER_SHOW_IN; }
		echo ">$display_value $typetxt</option>";
	}
	echo "</select>";
}

function adinj_javascript_addtext(){
	?>
	<script type="text/javascript">
	function adinj_addtext(element, value) {
		if (value.length == 0) return;
		separator = ', ';
		if (element.value.length == 0){
			separator = '';
		}
		element.value += (separator + value);
	}
	function adinj_toggle_tick_boxes(name, hide){
		if (hide){
			//jQuery('.'+name).hide();
			jQuery('.'+name).css({ opacity: 0.3 });
			//jQuery('.'+name+' :input').attr('disabled', true);
			//jQuery('.'+name+' :input').attr('readonly', true)
		} else {
			//jQuery('.'+name).show();
			jQuery('.'+name).css({ opacity: 1.0 });
			//jQuery('.'+name+' :input').removeAttr('disabled');
			//jQuery('.'+name+' :input').removeAttr('readonly');
		}
	}
	</script>
	<?php
}

// TODO replace previous show/hide code with this
function adinj_add_show_hide_section($anchor, $show_op, $show_field_name, $ops){
		$show_setting_id = $anchor.'_show';
		$show_value = $ops[$show_op];

	echo <<<HTML
		<input type='hidden' id="$show_setting_id" name="$show_field_name" value='$show_value' />
		<a href='#' onclick="javascript:adinj_toggle_click('$show_setting_id', '$anchor-button', '$anchor-box');return false;" style='display:none;width:10px;' id='$anchor-button' class='button'>+/-</a>
		<br clear="all" />
		
		<script type="text/javascript">
		adinj_button_update('$show_setting_id', '$anchor-button');
		jQuery('a#$anchor-button').show();
		</script>

HTML;
	if ($show_value == 'false'){
		echo "<div id='$anchor-box' class='hiddenbox'>";
	} else {
		echo "<div id='$anchor-box'>";
	}
}

function adinj_condition_tables($prefix, $show_setting){
	$ops = adinj_options();
	if (strlen($ops[$prefix.'category_condition_entries'])>0 || strlen($ops[$prefix.'tag_condition_entries'])>0 ||
		strlen($ops[$prefix.'author_condition_entries'])>0 || strlen($ops[$prefix.'id_condition_entries'])>0){
		$msg = "configured";
	} else {
		$msg = "empty";
	}
	echo "Category tag, author, and post id conditions [<b>".$msg."</b>]";
	adinj_add_show_hide_section('ad_conditions_'.uniqid(''), $show_setting, $show_setting, $ops);
	adinj_condition_table($prefix.'category', 'category slugs. e.g: cat1, cat2, cat3', 'category', $ops);
	adinj_condition_table($prefix.'tag', 'tag slugs. e.g: tag1, tag2, tag3', 'tag', $ops);
	adinj_condition_table($prefix.'author', 'author nicknames. e.g: john, paul', 'author', $ops);
	adinj_condition_table($prefix.'id', 'post or page ids. e.g: 7, 38, 243', 'id', $ops);
	echo '</div>';
}

function adinj_condition_table($name, $description, $type, $ops, $dropdown_fieldname=NULL, $textarea_fieldname=NULL){
	$style = "";
	if ($dropdown_fieldname == NULL){
		$dropdown_fieldname = $name."_condition_mode";
		// Only for the main screen - not for widgets screen.
		$style = "style='width:280px'";
	}
	if ($textarea_fieldname == NULL){
		$textarea_fieldname = $name."_condition_entries";
	}
	?>
	<table border="0">
	<tr><td>
	
	<textarea name="<?php echo $textarea_fieldname; ?>" rows="2" cols="40"><?php echo $ops[$name.'_condition_entries']; ?></textarea>
	
	</td><td style="vertical-align:top">
	
	<?php
		adinj_selection_box($dropdown_fieldname,
			array('o','n'), "", $ops[$name.'_condition_mode']);
	?>
	
	<?php 
	if ($type == 'category' || $type == 'tag' || $type == 'author') {
	?>

	<br />
	<select name="<?php echo $name; ?>_dropdown" <?php echo $style; ?> onchange='adinj_addtext(getElementsByName("<?php echo $textarea_fieldname; ?>")[0], this.options[this.selectedIndex].value);'>
		<option value=""><?php echo 'Add ' . $type; ?></option> 
	
	<?php 
	if ($type == 'category') { 
		$categories = get_categories();
		$cat = NULL;
		foreach ($categories as $cat) {
			$nicename = rawurldecode($cat->category_nicename);
			echo '<option value="'.$nicename.'">'.$nicename.' ('.$cat->category_count.')</option>';
		}
		unset ($cat);
	} else if ($type == 'tag') {
		/*s$testarray = array();
		for ($i=0;$i<549999;++$i){ $testarray[$i] = 'test';	}*/

		// A lot of blogs have large (1000+) tags. Loading this many tags at once can cause an OOM
		// error. Break up tag loading into chunks to reduce memory usage.
		$tagcount = 0;
		$tagquantity = 100;
		while (true){
			$more = adinj_print_tags($tagquantity, $tagcount);
			$tagcount += $tagquantity;
			if (!$more) break;
		}
	} else if ($type == 'author') { 
		$authors = adinj_get_authors();
		$author = NULL;
		foreach ($authors as $author) {
			$login = $author->user_login;
			$displayname = $author->display_name;
			echo '<option value="'.$login.'">'.$login.' ('.$displayname.')</option>';
		}
		unset ($authors);
	} else {
		echo 'ADINJ DEBUG Type not defined: ' . $type;
	}?>
	
	</select>
	<NOSCRIPT><br /><span style="font-size:10px">As JavaScript is disabled you will have to manually type in the values.</span></NOSCRIPT>
	
	<?php } ?>
	
	</td></tr>
	<tr><td colspan="2">
	<span style="font-size:10px;">Comma separated list of <?php echo $description; ?></span>
	</td></tr>
	</table>
	<?php
}

function adinj_print_tags($quantity, $offset){
	//$tags = get_tags(array('number' => $quantity, 'offset' => $offset));
	global $wpdb;
	$sql = "SELECT t.slug, tt.count FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('post_tag') AND tt.count > 0 ORDER BY t.name ASC LIMIT $offset,$quantity";
	$tags = $wpdb->get_results($sql);
	if (!$tags){
		return false;
	}
	
	if (count($tags) == 0) return false;
	$tag = NULL;
	foreach ($tags as $tag) {
		$slug = rawurldecode($tag->slug);
		echo '<option value="'.$slug.'">'.$slug.' ('.$tag->count.')</option>';
	}
	unset ($tag);
	if (count($tags) < $quantity) {
		return false; 
	}
	return true;
}

// TODO Currently gets all users
function adinj_get_authors(){
	global $wpdb;
	$authors = $wpdb->get_results( "SELECT user_login, display_name from $wpdb->users" );
	return $authors;
}

function adinj_process_text($text){
	return htmlentities($text, ENT_COMPAT | ENT_HTML401, "UTF-8");
}

function adinj_table_width($table){
	global $wp_db_version;
	if ($table == 'ad'){
		if ($wp_db_version < 18226){
			echo '60';
		} else { //WP3.2+
			echo '70';
		}
	} else if ($table == 'rotation'){
		if ($wp_db_version < 18226){
			echo '65';
		} else { //WP3.2+
			echo '75';
		}
	} else if ($table == 'dynamic'){
		if ($wp_db_version < 18226){
			echo '70';
		} else { //WP3.2+
			echo '80';
		}
	} else {
		echo '61';
	}
}

function adinj_add_alignment_options($prefix){
	adinj_add_alignment_clear_options($prefix);
	echo "<br />";
	adinj_add_padding_top_bottom_options($prefix);
	echo "<br />";
	adinj_add_margin_top_bottom_options($prefix);
}

function adinj_add_alignment_clear_options($prefix, $options=NULL, $alignname=NULL, $clearname=NULL){
	$aname = $prefix.'align';
	$cname = $prefix.'clear';
	$adefault = NULL;
	$cdefault = NULL;
	if ($alignname != NULL){
		$aname = $alignname;
		$adefault = "align";
	}
	if ($clearname != NULL){
		$cname = $clearname;
		$cdefault = "clear";
	}
	_e("Alignment", 'adinj');
	echo "<br />";
	adinj_selection_box($aname,array('d','left','center','right','float left','float right','rand lcr','rand float lr','rand all'),"",$options[$adefault]);
	echo "<br />";
	_e("Clear (CSS)", 'adinj');
	echo "<br />";
	adinj_selection_box($cname,array('d','left','right','both'),"",$options[$cdefault]);
}

function adinj_add_margin_top_bottom_options($prefix, $options=NULL, $topname=NULL, $bottomname=NULL){
	$tname = $prefix.'margin_top';
	$bname = $prefix.'margin_bottom';
	$tdefault = NULL;
	$bdefault = NULL;
	if ($topname != NULL){
		$tname = $topname;
		$tdefault = "margin_top";
	}
	if ($bottomname != NULL){
		$bname = $bottomname;
		$bdefault = "margin_bottom";
	}
	_e("Margin top", 'adinj');
	echo "<br />";
	$margin_settings = array('d',0,1,2,3,4,5,7,10,15,20,30);
	adinj_selection_box($tname, $margin_settings, "(px)", $options[$tdefault]);
	echo "<br />";
	_e("Margin bottom", 'adinj');
	echo "<br />";
	adinj_selection_box($bname, $margin_settings, "(px)", $options[$bdefault]);	
}

function adinj_add_padding_top_bottom_options($prefix, $options=NULL, $topname=NULL, $bottomname=NULL){
	$tname = $prefix.'padding_top';
	$bname = $prefix.'padding_bottom';
	$tdefault = NULL;
	$bdefault = NULL;
	if ($topname != NULL){
		$tname = $topname;
		$tdefault = "padding_top";
	}
	if ($bottomname != NULL){
		$bname = $bottomname;
		$bdefault = "padding_bottom";
	}
	_e("Padding top", 'adinj');
	echo "<br />";
	$padding_settings = array('d',0,1,2,3,4,5,7,10,15,20,30);
	adinj_selection_box($tname, $padding_settings, "(px)", $options[$tdefault]);
	echo "<br />";
	_e("Padding bottom", 'adinj');
	echo "<br />";
	adinj_selection_box($bname, $padding_settings, "(px)", $options[$bdefault]);	
}

function adinj_get_version(){
	$plugin_data=get_plugin_data(ADINJ_PATH . '/ad-injection.php');
	return $plugin_data['Version'];
}

function adinj_problem_with_wpminify_check(){
	if (!is_plugin_active('wp-minify/wp-minify.php')) return false;
	$wpm_options = get_option('wp_minify');
	$ops = adinj_options();
	if ($wpm_options['enable_html'] == true && adinj_mfunc_mode()){
		return true;
	}
	return false;
}

function adinj_get_problem_with_wpminify_message(){
	return '<font color="red">Problem: Ad Injection will not work if WP Minify is set to minify HTML whilst mfunc mode is enabled.</font><br />
			Solution: Go to <a href="options-general.php?page=wp-minify">the WP Minify settings page</a> and untick "Enable HTML Minification".';
}

function adinj_init_warning() {
	if (stripos($_SERVER["PHP_SELF"], 'plugins.php') !== false){
		echo '<div id="ad-injection-warning" class="updated fade"><p><strong>
		Ad Injection needs configuring:
		Go to <a href="options-general.php?page=ad-injection.php">the settings page</a> to configure and enable your ads.
		</strong></p></div>
		';
	}
	// TODO add option to disable message without having to go to settings.
}

function adinj_compatibility_checks() {
	if (stripos($_SERVER["PHP_SELF"], 'ad-injection') !== false){
		$wpm_options = get_option('wp_minify');
		if ($wpm_options['enable_html'] == true){
			echo '<div id="ad-injection-error" class="error"><p><strong>';
			echo adinj_get_problem_with_wpminify_message();
			echo '</strong></p></div>';
		}
	}
}

function is_supported_caching_plugin_active(){
	if (!is_plugin_active('wp-super-cache/wp-cache.php') && 
		!is_plugin_active('w3-total-cache/w3-total-cache.php') &&
		!is_plugin_active('wp-cache/wp-cache.php')){
		return false;
	}
	return true;
}

//////////////////////////////////////////////////////////////////////////////

function adinj_get_test_ad_link_escaped($rnd){
	echo htmlspecialchars(adinj_get_test_ad_link($rnd));
}
//? >&lt;a href=&quot;http://www.reviewmylife.co.uk/&quot;&gt;www.reviewmylife.co.uk&lt;/a&gt;< ?php

function adinj_get_test_ad_link($rnd){
	if ($rnd == 0){
?><a href="http://www.reviewmylife.co.uk/">www.reviewmylife.co.uk</a><?php
	} else if ($rnd == 1) {
?><a href="http://www.reviewmylife.co.uk/">reviewmylife</a><?php
	} else {
?><a href="http://www.reviewmylife.co.uk/blog/2010/12/06/ad-injection-plugin-wordpress/">Ad Injection</a><?php
	}
}

function adinj_testads(){
	adinj_postbox_start(__("Test Adverts and template ad examples", 'adinj'), "testads", '95%');
	$rnd = rand(0, 2);
	?>
<p>You can copy and paste these adverts into the boxes above to test your ad setup before switching to your real ads.</p>

<h4><a name="468x60"></a>468x60 banner</h4>

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="80" rows="4">&lt;div style=&quot;background-color:#ff9999; width:468px; height:60px;&quot;&gt;
&lt;h5&gt;AD INJECTION TEST ADVERT 468x60 - <?php adinj_get_test_ad_link_escaped($rnd); ?>&lt;/h5&gt;
&lt;/div&gt;</textarea></p>

<div style="background-color:#99ffff; width:468px; height:60px;">
<h5>AD INJECTION TEST ADVERT 468x60 - <?php adinj_get_test_ad_link($rnd); ?></h5>
</div><p></p>

<h4><a name="728x90"></a>728x90 banner</h4>

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="80" rows="4">&lt;div style=&quot;background-color:#ff9999; width:728px; height:90px;&quot;&gt;
&lt;h5&gt;AD INJECTION TEST ADVERT 728x90&lt;/h5&gt;
<?php adinj_get_test_ad_link_escaped($rnd); ?>&lt;br /&gt;
&lt;a href=&quot;http://www.advancedhtml.co.uk/&quot;&gt;www.advancedhtml.co.uk&lt;/a&gt;
&lt;/div&gt;</textarea></p>

<div style="background-color:#ff9999; width:728px; height:90px;">
<h5>AD INJECTION TEST ADVERT 728x90</h5>
<?php adinj_get_test_ad_link($rnd); ?><br />
<a href="http://www.advancedhtml.co.uk/">www.advancedhtml.co.uk</a>
</div><p></p>

<h4>160x90 link unit</h4>

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="80" rows="4">&lt;div style=&quot;background-color:#ccff99; width:160px; height:90px;&quot;&gt;
&lt;h5&gt;TEST ADVERT 160x90&lt;/h5&gt;
<?php adinj_get_test_ad_link_escaped($rnd); ?>&lt;br /&gt;
&lt;a href=&quot;http://www.advancedhtml.co.uk/&quot;&gt;advancedhtml.co.uk&lt;/a&gt;
&lt;/div&gt;</textarea></p>

<div style="background-color:#ccff99; width:160px; height:90px;">
<h5>TEST ADVERT 160x90</h5>
<?php adinj_get_test_ad_link($rnd); ?><br />
<a href="http://www.advancedhtml.co.uk/">advancedhtml.co.uk</a><br />
</div><p></p>

<h4><a name="468x15"></a>468x15 link unit</h4>

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="80" rows="4">&lt;div style=&quot;background-color:#cccc99; width:468px; height:15px;&quot;&gt;
&lt;font size=&quot;-2&quot;&gt;&lt;b&gt;TEST ADVERT 160x90&lt;/b&gt; <?php adinj_get_test_ad_link_escaped($rnd); ?>&lt;/font&gt;
&lt;/div&gt;</textarea></p>

<div style="background-color:#cccc99; width:468px; height:15px;">
<font size="-2"><b>TEST ADVERT 468x15</b> <?php adinj_get_test_ad_link($rnd); ?></font>
</div><p></p>

<h4><a name="336x280"></a>336x280 large rectangle</h4>

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="80" rows="4">&lt;div style=&quot;background-color:#ccccff; width:336px; height:280px;&quot;&gt;
&lt;h5&gt;TEST ADVERT 336x280 - <?php adinj_get_test_ad_link_escaped($rnd); ?>&lt;/h5&gt;
&lt;/div&gt;</textarea></p>

<div style="background-color:#ccccff; width:336px; height:280px;">
<h5>TEST ADVERT 336x280 - <?php adinj_get_test_ad_link($rnd); ?></h5>
</div><p></p>

<h4>468x60 banner with dynamic PHP</h4>

<p>The PHP will execute if you use a mfunc compatible caching plugin which is correctly configured, or if you don't use any caching plugin at all.</p>

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="80" rows="5">&lt;div style=&quot;background-color:#ffff99; width:468px; height:60px;&quot;&gt;
&lt;b&gt;TEST ADVERT 468x60 with date() and rand()&lt;/b&gt;&lt;br /&gt;
&lt;?php echo &quot;date=&quot;.date(&quot;Y-m-d H:i:s&quot;) .&quot; rand=&quot;.rand(); ?&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.advancedhtml.co.uk/&quot;&gt;www.advancedhtml.co.uk&lt;/a&gt;
&lt;/div&gt;</textarea></p>

<div style="background-color:#ffff99; width:468px; height:60px;">
<b>TEST ADVERT 468x60 with date() and rand()</b><br />
<?php echo "date=".date("Y-m-d H:i:s") ." rand=".rand(); ?><br />
<a href="http://www.advancedhtml.co.uk/">www.advancedhtml.co.uk</a>
</div><p></p>


<h4>Template ad examples</h4>

<p>Template ads allow any of the ads to be inserted anywhere in your theme. <b>*Don't*</b> try putting any of this code into one of the ad boxes - it is not an advert - it is code to load an advert directly into your theme.</p>

<b>Simple examples for loading top, random, bottom or footer ads</b><br />

<p>If you are using mfunc mode (for caching plugins) you may need to include the ad framework loading code snippet below. You would have to include this snippet above the ad display code.</p>

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="80" rows="1">
&lt;?php if (function_exists('adinj_print_ad')){ adinj_print_ad('top'); } ?&gt;</textarea></p>

<p>You can load the 'top', 'random', 'bottom', and 'footer' ads.</p> 

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="80" rows="1">
&lt;?php if (function_exists('adinj_print_ad')){ adinj_print_ad('hotel-ad.txt'); } ?&gt;</textarea></p>

<p>Or you can load ads stored as text files in the ad-injection-data directory (<?php echo ADINJ_AD_PATH; ?>/)</p>

<b>Ad framework loading code for mfunc mode with caching plugins + 1 random ad</b><br />

<p><textarea onclick="javascript:this.focus();this.select();" style="min-height:50px;" cols="110" rows="5">&lt;!--mfunc include_once('<?php echo ADINJ_PATH; ?>/adshow.php') --&gt;
&lt;?php include_once('<?php echo ADINJ_PATH; ?>/adshow.php'); ?&gt;
&lt;!--/mfunc--&gt;
&lt;?php if (function_exists('adinj_print_ad')){ adinj_print_ad('random'); } ?&gt;</textarea></p>

	<?php 
	adinj_postbox_end();
}

//////////////////////////////////////////////////////////////////////////////

function adinj_percentage_split($name_stem, $num, $ops, $total=NULL){
	// for old db -  TODO delete later
	if (adinj_db_version($ops) == 1){
		if ($num == 1) return '100%';
		return '0%';
	}
	
	if ($total == NULL){
		$total = adinj_total_split($name_stem, $ops);
	}

	$name = $name_stem.$num;
	$namesplit = $name.'_split';
	
	$percent = 0;
	if (!empty($ops[$name])){
		if ($total == 0){
			$percent = 0;
		} else {
			if (!empty($ops[$namesplit])){
				$percent = ($ops[$namesplit] / $total) * 100;
			}
		}
	}
	$percent = number_format($percent, 1).'%';
	return $percent;
}

function adinj_total_split($name_stem, $ops){
	$total = 0;
	for ($i=1; $i<=10; ++$i){
		$split = $name_stem.$i.'_split';
		if (!empty($ops[$name_stem.$i]) && 
				is_numeric($ops[$split]) && 
				$ops[$split] > 0){
			$total += $ops[$split];
		}
	}
	return $total;
}

function adinj_count_live_ads($adtype, $ops){
	$name_stem = adinj_ad_name_stem($adtype);
	$total = 0;
	for ($i=1; $i<=10; ++$i){
		$split = $name_stem.$i.'_split';
		if (!empty($ops[$name_stem.$i]) && 
				is_numeric($ops[$split]) && 
				$ops[$split] > 0){
			$total += 1;
		}
	}
	return $total;
}

function adinj_ad_name_stem($adtype){
	if ($adtype == 'top') return 'ad_code_top_';
	if ($adtype == 'random') return 'ad_code_random_';
	if ($adtype == 'bottom') return 'ad_code_bottom_';
	if ($adtype == 'footer') return 'ad_code_footer_';
	if ($adtype == 'top_alt') return 'ad_code_top_alt_';
	if ($adtype == 'random_alt') return 'ad_code_random_alt_';
	if ($adtype == 'bottom_alt') return 'ad_code_bottom_alt_';
	if ($adtype == 'footer_alt') return 'ad_code_footer_alt_';
	// TODO widget?
	return 'Error: adinj_ad_name_stem:'.$adtype;
}

//////////////////////////////////////////////////////////////////////////////

// Hopefully run on install and upgrade
function adinj_activate_hook(){
	$ops = adinj_options();
	if(empty($ops)){
		// 1st Install.
		adinj_install_db();
	} else {
		// Upgrade check.
		adinj_upgrade_db_if_necessary();
	}
}

function adinj_install_db(){
	$new_options = adinj_default_options();
	// Dynamic defaults.
	if (!is_supported_caching_plugin_active()){
		$new_options['ad_insertion_mode'] = 'direct';
	}
	adinj_update_options($new_options);
	if (adinj_mfunc_mode()){
		// Create config file.
		adinj_write_config_file();
	}
}

function adinj_upgrade_db(){
	$stored_options = adinj_options();
	$new_options = adinj_default_options();

	$stored_dbversion = adinj_db_version($stored_options);
	$new_dbversion = adinj_db_version($new_options);
	
	// 1. Copy existing options to new array. Use default as a baseline,
	// and then overwrite default with the saved ones.
	foreach ($new_options as $key => $value){
		if (array_key_exists($key, $stored_options)){
			$new_options[$key] = $stored_options[$key];
		}
	}
	
	// 2. Upgrade options if necessary.
	if ($stored_dbversion == 1){
		// Copy this to new setting
		if (adinj_ticked('first_paragraph_ad')){
			$new_options['start_from_paragraph'] = 1;
		}
		// This previously wan't configured correctly
		$new_options['block_ips'] = 'on';
	}
	
	if ($stored_dbversion < 4){
		// Maintain previous behaviour for users who upgrade
		$new_options['content_length_unit'] = 'all';
	}
	
	if ($stored_dbversion < 5){
		// Maintain previous behaviour for users who upgrade
		$new_options['exclude_search'] = 'on';
		$new_options['exclude_404'] = 'on';
		$new_options['widget_exclude_search'] = 'on';
		$new_options['widget_exclude_404'] = 'on';
	}
	
	if ($stored_dbversion < 6){
		$new_options['home_max_num_random_ads_per_page'] = $stored_options['max_num_of_ads_home_page'];
	}

	if ($stored_dbversion < 9){
		if ($stored_options['ad_insertion_mode'] == 'direct_static'){
			$new_options['ad_insertion_mode'] = 'direct';
			$new_options['block_ips'] = 'off';
			$new_options['sevisitors_only'] = 'off';
		}
		if ($stored_options['ad_insertion_mode'] == 'direct_dynamic'){
			$new_options['ad_insertion_mode'] = 'direct';
		}
	}
	
	if ($stored_dbversion < 11){
		$new_options['rnd_allow_ads_on_last_paragraph'] = 'on';
	}
	
	if ($stored_dbversion < 15){
		// values deliberately hard coded here to fix them on constants used for this version of db
		
		// if set to disabled
		if ($stored_options['top_ad_if_longer_than'] == 'd' || $stored_options['top_ad_if_longer_than'] == 'Disabled' || $stored_options['top_ad_if_longer_than'] == 'Rule Disabled'){
			$new_options['top_exclude_single'] = 'on';
			$new_options['top_exclude_page'] = 'on';
		}
		if ($stored_options['home_top_ad_if_longer_than'] == 'd' || $stored_options['home_top_ad_if_longer_than'] == 'Disabled' || $stored_option['home_top_ad_if_longer_than'] == 'Rule Disabled'){
			$new_options['top_exclude_home'] = 'on';
		}
		if ($stored_options['archive_top_ad_if_longer_than'] == 'd' || $stored_options['archive_top_ad_if_longer_than'] == 'Disabled' || $stored_options['archive_top_ad_if_longer_than'] == 'Rule Disabled'){
			$new_options['top_exclude_archive'] = 'on';
		}
		if ($stored_options['bottom_ad_if_longer_than'] == 'd' || $stored_options['bottom_ad_if_longer_than'] == 'Disabled' || $stored_options['bottom_ad_if_longer_than'] == 'Rule Disabled'){
			$new_options['bottom_exclude_single'] = 'on';
			$new_options['bottom_exclude_page'] = 'on';
		}
		if ($stored_options['home_bottom_ad_if_longer_than'] == 'd' || $stored_options['home_bottom_ad_if_longer_than'] == 'Disabled' || $stored_options['home_bottom_ad_if_longer_than'] == 'Rule Disabled'){
			$new_options['bottom_exclude_home'] = 'on';
		}
		if ($stored_options['archive_bottom_ad_if_longer_than'] == 'd' || $stored_options['archive_bottom_ad_if_longer_than'] == 'Disabled' || $stored_options['archive_bottom_ad_if_longer_than'] == 'Rule Disabled'){
			$new_options['bottom_exclude_archive'] = 'on';
		}

		// if set to always show
		if ($stored_options['top_ad_if_longer_than'] == 'a' || $stored_options['top_ad_if_longer_than'] == 'Always show'){
			$new_options['top_ad_if_longer_than'] = 'd';
		}
		if ($stored_options['home_top_ad_if_longer_than'] == 'a' || $stored_options['home_top_ad_if_longer_than'] == 'Always show'){
			$new_options['home_top_ad_if_longer_than'] = 'd';
		}
		if ($stored_options['archive_top_ad_if_longer_than'] == 'a' || $stored_options['archive_top_ad_if_longer_than'] == 'Always show'){
			$new_options['archive_top_ad_if_longer_than'] = 'd';
		}
		if ($stored_options['bottom_ad_if_longer_than'] == 'a' || $stored_options['bottom_ad_if_longer_than'] == 'Always show'){
			$new_options['bottom_ad_if_longer_than'] = 'd';
		}
		if ($stored_options['home_bottom_ad_if_longer_than'] == 'a' || $stored_options['home_bottom_ad_if_longer_than'] == 'Always show'){
			$new_options['home_bottom_ad_if_longer_than'] = 'd';
		}
		if ($stored_options['archive_bottom_ad_if_longer_than'] == 'a' || $stored_options['archive_bottom_ad_if_longer_than'] == 'Always show'){
			$new_options['archive_bottom_ad_if_longer_than'] = 'd';
		}
	}
	
	if ($stored_dbversion < 16){
		$new_options['widgets_on_page_older_than'] = $stored_options['ads_on_page_older_than'];
	}
	
	if ($stored_dbversion < 18){
		// todo test
		$new_options['random_ads_start_mode'] = $stored_options['random_ads_after_mode'];
		$new_options['random_ads_start_unit'] = $stored_options['random_ads_after_unit'];
		$new_options['random_ads_start_at'] = $stored_options['start_from_paragraph'];
		if ($new_options['random_ads_start_at'] == 'd'){
			$new_options['random_ads_start_mode'] = 'anywhere';
			$new_options['random_ads_start_at'] = '1';
		}
	}
	
	if ($stored_dbversion < 19){
		if ($new_options['random_ads_start_at'] == 'd' || 
			$new_options['random_ads_start_at'] == 'Rule Disabled' ||
			$new_options['random_ads_start_at'] == 'Disabled'){
			$new_options['random_ads_start_mode'] = 'anywhere';
			$new_options['random_ads_start_at'] = '1';
		}
	}
	
	// 3. Bump up db version number.
	$new_options['db_version'] = $new_dbversion;
	
	// 4. Save upgraded options. 
	adinj_update_options($new_options);
	
	// 5. Update config file.
	if ($new_options['ad_insertion_mode'] == 'mfunc'){
		// Update config file
		adinj_write_config_file();
	}
}

// All these stored in a single DB option row
function adinj_default_options(){
	return array(
		// Global settings
		'ads_enabled' => 'on',
		'ads_on_page_older_than' => '0',
		'widgets_on_page_older_than' => '0',
		'content_length_unit' => 'words',
		'exclude_ads_from_block_tags' => 'off',
		'exclude_ads_from_div_tags' => 'off',
		'exclude_ads_from_list_tags' => 'off',
		'exclude_ads_from_form_tags' => 'off',
		'exclude_ads_from_table_tags' => 'off',
		// random ad start/end position
		'random_ads_start_mode' => 'anywhere',
		'random_ads_start_unit' => 'paragraph',
		'random_ads_start_at' => '1',
		'random_ads_end_mode' => 'anywhere',
		'random_ads_end_unit' => 'paragraph',
		'random_ads_end_at' => '20',
		'random_ads_end_direction' => 'fromstart',
		'rnd_allow_ads_on_last_paragraph' => 'off',
		'rnd_reselect_ad_per_position_in_post' => 'off',
		'multiple_ads_at_same_position' => 'off',
		// top/bottom ad position
		'top_ad_position' => '0',
		'top_ad_position_unit' => 'paragraph',
		'bottom_ad_position' => '0',
		'bottom_ad_position_unit' => 'paragraph',
		// single posts and pages
		'top_ad_if_longer_than' => 'd',
		'max_num_of_ads' => '2', // random ads
		'no_random_ads_if_shorter_than' => 'd',
		'one_ad_if_shorter_than' => 'd',
		'two_ads_if_shorter_than' => 'd',
		'three_ads_if_shorter_than' => 'd',
		'bottom_ad_if_longer_than' => 'd',
		// Home page  ads
		'home_top_ad_if_longer_than' => 'd',
		'home_max_num_top_ads_per_page' => '1',
		'home_max_num_random_ads_per_post' => '1',
		'home_max_num_random_ads_per_page' => '3',
		'home_no_random_ads_if_shorter_than' => 'd',
		'home_one_ad_if_shorter_than' => 'd',
		'home_two_ads_if_shorter_than' => 'd',
		'home_three_ads_if_shorter_than' => 'd',
		'home_bottom_ad_if_longer_than' => 'd',
		'home_max_num_bottom_ads_per_page' => '1',
		// Archive ads
		'archive_top_ad_if_longer_than' => 'd',
		'archive_max_num_top_ads_per_page' => '1',
		'archive_max_num_random_ads_per_post' => '1',
		'archive_max_num_random_ads_per_page' => '3',
		'archive_no_random_ads_if_shorter_than' => 'd',
		'archive_one_ad_if_shorter_than' => 'd',
		'archive_two_ads_if_shorter_than' => 'd',
		'archive_three_ads_if_shorter_than' => 'd',
		'archive_bottom_ad_if_longer_than' => 'd',
		'archive_max_num_bottom_ads_per_page' => '1',
		// Top ads
		'ad_code_top_1' => '',
		'ad_code_top_2' => '',
		'ad_code_top_3' => '',
		'ad_code_top_4' => '',
		'ad_code_top_5' => '',
		'ad_code_top_6' => '',
		'ad_code_top_7' => '',
		'ad_code_top_8' => '',
		'ad_code_top_9' => '',
		'ad_code_top_10' => '',
		'ad_code_top_1_split' => '100',
		'ad_code_top_2_split' => '100',
		'ad_code_top_3_split' => '100',
		'ad_code_top_4_split' => '100',
		'ad_code_top_5_split' => '100',
		'ad_code_top_6_split' => '100',
		'ad_code_top_7_split' => '100',
		'ad_code_top_8_split' => '100',
		'ad_code_top_9_split' => '100',
		'ad_code_top_10_split' => '100',
		'ad_code_top_alt_1' => '',
		'ad_code_top_alt_2' => '',
		'ad_code_top_alt_1_split' => '100',
		'ad_code_top_alt_2_split' => '100',
		// Random ads
		'ad_code_random_1' => '',
		'ad_code_random_2' => '',
		'ad_code_random_3' => '',
		'ad_code_random_4' => '',
		'ad_code_random_5' => '',
		'ad_code_random_6' => '',
		'ad_code_random_7' => '',
		'ad_code_random_8' => '',
		'ad_code_random_9' => '',
		'ad_code_random_10' => '',
		'ad_code_random_1_split' => '100',
		'ad_code_random_2_split' => '100',
		'ad_code_random_3_split' => '100',
		'ad_code_random_4_split' => '100',
		'ad_code_random_5_split' => '100',
		'ad_code_random_6_split' => '100',
		'ad_code_random_7_split' => '100',
		'ad_code_random_8_split' => '100',
		'ad_code_random_9_split' => '100',
		'ad_code_random_10_split' => '100',
		'ad_code_random_alt_1' => '',
		'ad_code_random_alt_2' => '',
		'ad_code_random_alt_1_split' => '100',
		'ad_code_random_alt_2_split' => '100',
		// Bottom ads
		'ad_code_bottom_1' => '',
		'ad_code_bottom_2' => '',
		'ad_code_bottom_3' => '',
		'ad_code_bottom_4' => '',
		'ad_code_bottom_5' => '',
		'ad_code_bottom_6' => '',
		'ad_code_bottom_7' => '',
		'ad_code_bottom_8' => '',
		'ad_code_bottom_9' => '',
		'ad_code_bottom_10' => '',
		'ad_code_bottom_1_split' => '100',
		'ad_code_bottom_2_split' => '100',
		'ad_code_bottom_3_split' => '100',
		'ad_code_bottom_4_split' => '100',
		'ad_code_bottom_5_split' => '100',
		'ad_code_bottom_6_split' => '100',
		'ad_code_bottom_7_split' => '100',
		'ad_code_bottom_8_split' => '100',
		'ad_code_bottom_9_split' => '100',
		'ad_code_bottom_10_split' => '100',
		'ad_code_bottom_alt_1' => '',
		'ad_code_bottom_alt_2' => '',
		'ad_code_bottom_alt_1_split' => '100',
		'ad_code_bottom_alt_2_split' => '100',
		// Footer ads
		'ad_code_footer_1' => '',
		'ad_code_footer_2' => '',
		'ad_code_footer_3' => '',
		'ad_code_footer_4' => '',
		'ad_code_footer_5' => '',
		'ad_code_footer_6' => '',
		'ad_code_footer_7' => '',
		'ad_code_footer_8' => '',
		'ad_code_footer_9' => '',
		'ad_code_footer_10' => '',
		'ad_code_footer_1_split' => '100',
		'ad_code_footer_2_split' => '100',
		'ad_code_footer_3_split' => '100',
		'ad_code_footer_4_split' => '100',
		'ad_code_footer_5_split' => '100',
		'ad_code_footer_6_split' => '100',
		'ad_code_footer_7_split' => '100',
		'ad_code_footer_8_split' => '100',
		'ad_code_footer_9_split' => '100',
		'ad_code_footer_10_split' => '100',
		'ad_code_footer_alt_1' => '',
		'ad_code_footer_alt_2' => '',
		'ad_code_footer_alt_1_split' => '100',
		'ad_code_footer_alt_2_split' => '100',
		// dynamic features
		'ad_insertion_mode' => 'mfunc',
		'sevisitors_only' => 'off',
		'ad_referrers' => '.google., .bing., .yahoo., .ask., search?, search.',
		'block_keywords' => 'off',
		'blocked_keywords' => '',
		'block_ads_for_hours' => '24',
		'block_ips' => 'off',
		'blocked_ips' => '',
		// ad display (layout) settings
		'top_align' => 'd',
		'top_clear' => 'd',
		'top_margin_top' => 'd',
		'top_margin_bottom' => 'd',
		'top_padding_top' => 'd',
		'top_padding_bottom' => 'd',
		'rnd_align' => 'd',
		'rnd_clear' => 'd',
		'rnd_margin_top' => 'd',
		'rnd_margin_bottom' => 'd',
		'rnd_padding_top' => 'd',
		'rnd_padding_bottom' => 'd',
		'bottom_align' => 'd',
		'bottom_clear' => 'd',
		'bottom_margin_top' => 'd',
		'bottom_margin_bottom' => 'd',
		'bottom_padding_top' => 'd',
		'bottom_padding_bottom' => 'd',
		'footer_align' => 'center',
		'footer_clear' => 'd',
		'footer_margin_top' => 'd',
		'footer_margin_bottom' => 'd',
		'footer_padding_top' => 'd',
		'footer_padding_bottom' => '3',
		// category, tag, author, id filters
		'global_category_condition_mode' => 'o',
		'global_category_condition_entries' => '',
		'global_tag_condition_mode' => 'o',
		'global_tag_condition_entries' => '',
		'global_author_condition_mode' => 'o',
		'global_author_condition_entries' => '',
		'global_id_condition_mode' => 'o',
		'global_id_condition_entries' => '',
		'top_category_condition_mode' => 'o',
		'top_category_condition_entries' => '',
		'top_tag_condition_mode' => 'o',
		'top_tag_condition_entries' => '',
		'top_author_condition_mode' => 'o',
		'top_author_condition_entries' => '',
		'top_id_condition_mode' => 'o',
		'top_id_condition_entries' => '',
		'random_category_condition_mode' => 'o',
		'random_category_condition_entries' => '',
		'random_tag_condition_mode' => 'o',
		'random_tag_condition_entries' => '',
		'random_author_condition_mode' => 'o',
		'random_author_condition_entries' => '',
		'random_id_condition_mode' => 'o',
		'random_id_condition_entries' => '',
		'bottom_category_condition_mode' => 'o',
		'bottom_category_condition_entries' => '',
		'bottom_tag_condition_mode' => 'o',
		'bottom_tag_condition_entries' => '',
		'bottom_author_condition_mode' => 'o',
		'bottom_author_condition_entries' => '',
		'bottom_id_condition_mode' => 'o',
		'bottom_id_condition_entries' => '',
		'footer_category_condition_mode' => 'o',
		'footer_category_condition_entries' => '',
		'footer_tag_condition_mode' => 'o',
		'footer_tag_condition_entries' => '',
		'footer_author_condition_mode' => 'o',
		'footer_author_condition_entries' => '',
		'footer_id_condition_mode' => 'o',
		'footer_id_condition_entries' => '',
		'template_category_condition_mode' => 'o',
		'template_category_condition_entries' => '',
		'template_tag_condition_mode' => 'o',
		'template_tag_condition_entries' => '',
		'template_author_condition_mode' => 'o',
		'template_author_condition_entries' => '',
		'template_id_condition_mode' => 'o',
		'template_id_condition_entries' => '',
		// exclusion tick boxes
		'exclude_front' => 'off',
		'exclude_home' => 'off',
		'exclude_page' => 'off',
		'exclude_single' => 'off',
		'exclude_archive' => 'off',
		'exclude_search' => 'on',
		'exclude_404' => 'on',
		'top_exclude_front' => 'off',
		'top_exclude_home' => 'off',
		'top_exclude_page' => 'off',
		'top_exclude_single' => 'off',
		'top_exclude_archive' => 'off',
		'top_exclude_search' => 'off',
		'top_exclude_404' => 'off',
		'random_exclude_front' => 'off',
		'random_exclude_home' => 'off',
		'random_exclude_page' => 'off',
		'random_exclude_single' => 'off',
		'random_exclude_archive' => 'off',
		'random_exclude_search' => 'off',
		'random_exclude_404' => 'off',
		'bottom_exclude_front' => 'off',
		'bottom_exclude_home' => 'off',
		'bottom_exclude_page' => 'off',
		'bottom_exclude_single' => 'off',
		'bottom_exclude_archive' => 'off',
		'bottom_exclude_search' => 'off',
		'bottom_exclude_404' => 'off',
		'footer_exclude_front' => 'off',
		'footer_exclude_home' => 'off',
		'footer_exclude_page' => 'off',
		'footer_exclude_single' => 'off',
		'footer_exclude_archive' => 'off',
		'footer_exclude_search' => 'off',
		'footer_exclude_404' => 'off',
		'widget_exclude_front' => 'off',
		'widget_exclude_home' => 'off',
		'widget_exclude_page' => 'off',
		'widget_exclude_single' => 'off',
		'widget_exclude_archive' => 'off',
		'widget_exclude_search' => 'off',
		'widget_exclude_404' => 'off',
		'template_exclude_front' => 'off',
		'template_exclude_home' => 'off',
		'template_exclude_page' => 'off',
		'template_exclude_single' => 'off',
		'template_exclude_archive' => 'off',
		'template_exclude_search' => 'off',
		'template_exclude_404' => 'off',
		// advanced settings
		'the_content_filter_priority' => '10', // 10 is the default for add_filter
		// ui main tab
		'ui_global_hide' => 'false',
		'ui_adsettings_hide' => 'false',
		'ui_adverts_hide' => 'false',
		'ui_filters_hide' => 'false',
		'ui_restrictions_hide' => 'false',
		'ui_docsquickstart_hide' => 'false',
		'ui_testads_hide' => 'false',
		'ui_conditions_show' => 'false',
		'ui_top_conditions_show' => 'false',
		'ui_random_conditions_show' => 'false',
		'ui_bottom_conditions_show' => 'false',
		'ui_footer_conditions_show' => 'false',
		'ui_template_conditions_show' => 'false',
		'ui_footer_docs_show' => 'false',
		// ui ad rotation tab
		'ui_docs_adrotation_hide' => 'false',
		'ui_multiple_top_hide' => 'false',
		'ui_multiple_random_hide' => 'false',
		'ui_multiple_bottom_hide' => 'false',
		'ui_multiple_footer_hide' => 'false',
		'ui_advanced_hide' => 'true',
		'ui_docs_tags_hide' => 'true',
		// ui debug tab
		'ui_debugging_hide' => 'false',
		// debug
		'debug_mode' => 'off',
		// version
		'db_version' => ADINJ_DB_VERSION
	);
}

function adinj_getdefault($option){
	$default_options = adinj_default_options();
	return "(default: " . $default_options[$option] . ")";
}

function write_ad_to_file($ad, $ad_path){
		adinj_write_file($ad_path, $ad, 0640);
}

function adinj_init_hook() {
	$ops = adinj_options();
	if ($ops['ads_enabled'] != 'on') {
		add_action('admin_notices', 'adinj_init_warning');
	}
}

// init
add_action('init', 'adinj_init_hook');
// Config links
add_action('admin_menu', 'adinj_admin_menu_hook');
add_filter('plugin_action_links', 'adinj_options_link_hook', 10, 2); // digits = priority, num args

?>