<?php
/*
Plugin Name: Intelligent content ad insertion for WordPress
Version: 0.2
Plugin URI: http://rudd-o.com/projects/wordpress-intelligent-content-ad-insert/
Description: Automatically insert advertisements in post and page content without manual intervention. It’s useful when you have a large amount of content (thousands of posts) that you want to monetize.  It's also compatible with other ad management plugins for WordPress, AdSense and can perform manual ad rotation.
Author: Rudd-O
Author URI: http://rudd-o.com/
*/

function iai_get_settings() {
	global $iai_settings;
	if (isset($iai_settings) && is_array($iai_settings)) return;
	$iai_settings = get_settings("iai_settings");
	if (!is_array($iai_settings)) $iai_settings = array();
}

function iai_save_settings() {
	global $iai_settings;
	update_option("iai_settings", $iai_settings);
}

function iai_get_ad($adname) {
	global $iai_settings;
	ob_start();
	$s = $iai_settings;
	if ($s["eval_ad_code"]) {
		$r = eval(" ?>".$s[$adname]."<?php ");
		if ($r === FALSE) print "<!-- PHP evaluation for ad code failed: ad name $adname.  Please refer to your Web server error_log for more information -->";
	}
	else print $s[$adname];
	$b = ob_get_contents(); ob_end_clean(); return $b;
}

function iai_get_halfway_ad() { return iai_get_ad("halfway_ad"); }
function iai_get_opener_ad() { return iai_get_ad("opener_ad"); }

function iai_filter_the_content_with_ad($content) {

	if (is_attachment()) return $content; //no for attachment pages
	if (!is_single() && !is_page() && !is_feed()) return $content;

	global $iai_settings; global $more;
	$settings = $iai_settings;
	if (is_single() && $settings["insert_in_single_posts"] != "1") return $content;
	if (is_page() && $settings["insert_in_pages"] != "1") return $content;
	if (is_feed() && $settings["insert_in_rss"] != "1") return $content;
	if (is_single() && !$more) return $content; // no ads inserted unless the post is "more"
	if (is_page() && !$more) return $content; // no ads inserted unless the page is "more"
	if (is_feed() && !$more) return $content; // no ads inserted unless the feed is "more"

	if (strpos($content, "<!--noadsense-->") !== false) return $content;
	
	$ad_beginning = iai_get_opener_ad();
	$ad_halfway = iai_get_halfway_ad();

	if (!($ad_beginning) && !($ad_halfway)) { return $content; }
	
	$beginning_positions = array (
		strpos($content,'<p><span id="more-'),
		strpos($content,"</p>") !== false ? strpos($content,"</p>")+4 : false,
		strpos($content,"<br>") !== false ? strpos($content,"<br>")+4 : false,
		strpos($content,"<br/>") !== false ? strpos($content,"<br/>")+5 : false,
		strpos($content,"<br />") !== false ? strpos($content,"<br />")+6 : false
	);
	$beginning_position = false; foreach ($beginning_positions as $p) {
		if ($p !== false) { $beginning_position = $p; break; }
	}
	
	if ($beginning_position === false) { return $content; }
	
	$paras = array();
	$lastpara = -1;
	$parastring = "<p"; if (strpos($content, $parastring) === false) $parastring = "<br";
	while (strpos($content, $parastring, $lastpara+1) !== false) {
		$lastpara = strpos($content, $parastring, $lastpara+1);
		$paras[] = $lastpara;
	}
	$middle_position = $paras[sizeof($paras) / 2];
	
	// time to inject the ads.  we work backwards so as not to modify positions
	
	if (sizeof($paras) >= 10) {
		// only if equal or more than ten paragraphs in content
		$content = substr_replace($content, $ad_halfway, $middle_position, 0);
	}
	$content = substr_replace($content, $ad_beginning, $beginning_position, 0);
	
	return $content;

}

function iai_parse_post_and_save_settings() {

	global $iai_settings;
	$keys = array("opener_ad","halfway_ad","eval_ad_code",
			"insert_in_single_posts","insert_in_pages","insert_in_rss");
	foreach ($keys as $key) $iai_settings[$key] = isset($_POST[$key]) ? stripslashes($_POST[$key]) : null;
	$iai_settings["saved"] = 1;
	iai_save_settings();

}


if (function_exists('is_plugin_page') && is_plugin_page()) {

	if ( isset($_POST['iai_commit']) ) iai_parse_post_and_save_settings();
	global $iai_settings;
	$iai_set = $iai_settings;

	?>

<div class="wrap">

<h2>Intelligent content ads</h2>

<p>This plugin lets you insert advertisements in post and page content without manual intervention.  It's useful when you have a large amount of content (thousands of posts) that you want to monetize.  See the <a href="#helphelp">help for more information</a>.</p>

<h3>Ad code</h3>

<p>Paste your ad code and tune the options to your needs:</p>

<form action="" method="POST">

<input type="hidden" name="iai_commit" value="1"/>

<table width="100%">
<tr><th>Ad code for opener ad</th><th>Ad code for halfway ad</th></tr>
<tr><td><textarea name="opener_ad" style="width:100%; height: 6em;"><?php if ($iai_set["opener_ad"]) print wp_specialchars($iai_set["opener_ad"]); ?></textarea></td>
<td><textarea name="halfway_ad" style="width:100%; height: 6em;"><?php if ($iai_set["halfway_ad"]) print wp_specialchars($iai_set["halfway_ad"]); ?></textarea></td></tr>
</table>

<h3>Configuration options</h3>

<ul>
<li><input type="checkbox" name="eval_ad_code" value="1" <?php if ($iai_set["eval_ad_code"]) print  "checked='checked'"; ?> /> <label for="eval_ad_code">Evaluate and execute PHP code in the ad code</label> <br/> <em>Useful if you want to use ads from the AdSenseDeluxe plugin, or create rotational ads</em></li>
<li><input type="checkbox" name="insert_in_single_posts" value="1" <?php if ( !$iai_set || $iai_set["insert_in_single_posts"]) print  "checked='checked'"; ?> /> <label for="insert_in_single_posts">Insert ads in posts presented in single view</label> <br/> <em>Recommended &mdash; ads will be inserted on full post pages</em></li>
<li><input type="checkbox" name="insert_in_pages" value="1" <?php if ($iai_set["insert_in_pages"]) print  "checked='checked'"; ?> /> <label for="insert_in_pages">Insert ads in pages</label> <br/> <em>Ads will be inserted on page content</em></li>
<li><input type="checkbox" name="insert_in_rss" value="1" <?php if ($iai_set["insert_in_rss"]) print  "checked='checked'"; ?> /> <label for="insert_in_rss">Insert ads in syndication feeds</label> <br/> <em>Ads will be inserted on syndicated content</em></li>
</ul>

<p class="submit" style="margin-top: -3.8em"><input type="submit" value="Update configuration »" name="submit"/></p>

</form>

</div>

<div class="wrap">

<h2 id="helphelp">Help</h2>

<p>There are a few things you should know about.  Let's explore them:</p>

<h3>Ad insertion</h3>

<p>At most two ads are inserted per-post (or per-page):</p>

<ol><li><em>An opener ad:</em> Right after the <code>&lt;!--more--&gt;</code> break of the post.  Failing that, between its first and second paragraphs.</li><li><em>A halfway ad:</em> In between the two paragraphs halfway of the post.</li></ol>

<p>Ads are not inserted on the front page, archive pages or any other page with multiple posts.</p>

<h3>PHP evaluation and execution</h3>

<p>If you're already using another ad system such as AdSenseDeluxe (or you plan to), you have the option to activate PHP evaluation.  In this mode, any PHP code you type on the Ad code boxes will be executed and evaluated.  You can use this technique to:</p>

<ul><li>Implement rotational ad systems<br/></li>
<li>Make ad code conditional to WordPress state<br/>
Example: <code>&lt;?php global $post; if ($post->title == "How to cook") { ?&gt; some ad code here &lt;? } ?&gt;</code></li>
<li>Perform A/B testing</li>
<li>Invoke AdSenseDeluxe code to pull ads from its configuration instead of manually maintaining ads separately<br/>
Example: <code>&lt;?php adsense_deluxe_ads('Ad_Name'); ?&gt;</code></li>
</ul>

<p>You should keep in mind, however, that PHP evaluation poses a security danger on multi-author blogs.</p>

<h3>Preventing a particular post from getting processed</h3>

<p>It's easy.  Just add the following on the post: <code>&lt;!--noadsense--&gt;</code>.</p>

<h3>My ads aren't showing!  I want a different feature!  Help!</h3>

<ul>
<li>If no ad code is present, no ads aren't shown.</li>
<li>If the page in question shows more than one post, no ad will be injected.</li>
<li>If the page in question is not a "more" page (<code>$more = 1</code>, true when viewing single posts, RSS feeds and pages), no ad will be injected.</li>
<li>Ads are not inserted on attachment pages.  Ads effective for posts and pages usually are much less effective on attachment pages due to layout issues.</li>
<li>If your story contains less than ten paragraphs in each page, the halfway ad is not shown.</li>
<li>Are you sure you checkmarked where you'd like to show the ads?</li>
<li>Are you using PHP evaluation?  If so, the code may be failing to evaluate properly.  Check the source of your page for an HTML comment starting with the string <code>PHP evaluation for ad code failed</code>, then check your server's PHP <code>error_log</code> for the exact error.</li>
</ul>

<p>As usual, there's paid support and services to go along with this plugin <a href="http://rudd-o.com/services/wp-consulting/">at my Web site</a>.</p>

</div>

<div class="wrap">

<h2>This and many other enhancements</h2>

<p class="credit">Were created by <a href="http://rudd-o.com/">Rudd-O</a>.  Get the latest version at <a href="http://rudd-o.com/projects/wordpress-intelligent-content-ad-insert/">this plugin's Web site</a> and the rest of the plugins at <a href="http://rudd-o.com/projects/">my project page</a>.  You can also <a href="http://rudd-o.com/services/wp-consulting/">get professional services</a>.</p>

</div>


<?php


}


function iai_init() {

	// load settings
	iai_get_settings();

	// add actions for the menu
	function iai_add_menu() {
		add_options_page('Intelligent content ads', 'Intelligent content ads', 8, __FILE__);
	}
	add_action('admin_head', 'iai_add_menu');

	add_filter('the_content', 'iai_filter_the_content_with_ad');

}

if ( function_exists('add_action') ) add_action('plugins_loaded', 'iai_init');

?>
