<?php
/*
Template Name: Test get_posts
*/

/*************************************************
 *  Use as a page template to test the get_posts *
 ************************************************/
?><html><head><title>get_posts test page</title></head><body><?php
function get_wpdb_query($query) {
	global $test_wpdb_query;
	if ( ! empty( $query ) ) {
		$test_wpdb_query[] = $query;
	}
	return $query;
}
add_filter('query', 'get_wpdb_query');

// define('SAVEQUERIES', true);

// the old function 
function get_posts_old($args = null) {
	global $wpdb;

	$defaults = array(
		'numberposts' => 5, 'offset' => 0,
		'category' => 0, 'orderby' => 'post_date',
		'order' => 'DESC', 'include' => '',
		'exclude' => '', 'meta_key' => '',
		'meta_value' =>'', 'post_type' => 'post',
		'post_status' => 'publish', 'post_parent' => 0
	);

	$r = wp_parse_args( $args, $defaults );
	extract( $r, EXTR_SKIP );

	$numberposts = (int) $numberposts;
	$offset = (int) $offset;
	$category = (int) $category;
	$post_parent = (int) $post_parent;

	$inclusions = '';
	if ( !empty($include) ) {
		$offset = 0;    //ignore offset, category, exclude, meta_key, and meta_value, post_parent if using include
		$category = 0;
		$exclude = '';
		$meta_key = '';
		$meta_value = '';
		$post_parent = 0;
		$incposts = preg_split('/[\s,]+/',$include);
		$numberposts = count($incposts);  // only the number of posts included
		if ( count($incposts) ) {
			foreach ( $incposts as $incpost ) {
				if (empty($inclusions))
					$inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpost);
				else
					$inclusions .= $wpdb->prepare(' OR ID = %d ', $incpost);
			}
		}
	}
	if (!empty($inclusions))
		$inclusions .= ')';

	$exclusions = '';
	if ( !empty($exclude) ) {
		$exposts = preg_split('/[\s,]+/',$exclude);
		if ( count($exposts) ) {
			foreach ( $exposts as $expost ) {
				if (empty($exclusions))
					$exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expost);
				else
					$exclusions .= $wpdb->prepare(' AND ID <> %d ', $expost);
			}
		}
	}
	if (!empty($exclusions))
		$exclusions .= ')';

	// orderby
	if ( preg_match( '/.+ +(ASC|DESC)/i', $orderby ) )
		$order = ''; // orderby has its own order, so we'll use that

	$query  = "SELECT DISTINCT * FROM $wpdb->posts ";
	$query .= empty( $category ) ? '' : ", $wpdb->term_relationships, $wpdb->term_taxonomy  ";
	$query .= empty( $meta_key ) ? '' : ", $wpdb->postmeta ";
	$query .= " WHERE 1=1 ";
	$query .= empty( $post_type ) ? '' : $wpdb->prepare("AND post_type = %s ", $post_type);
	$query .= empty( $post_status ) ? '' : $wpdb->prepare("AND post_status = %s ", $post_status);
	$query .= "$exclusions $inclusions " ;
	$query .= empty( $category ) ? '' : $wpdb->prepare("AND ($wpdb->posts.ID = $wpdb->term_relationships.object_id AND $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id AND $wpdb->term_taxonomy.term_id = %d AND $wpdb->term_taxonomy.taxonomy = 'category')", $category);
	$query .= empty( $post_parent ) ? '' : $wpdb->prepare("AND $wpdb->posts.post_parent = %d ", $post_parent);
	// expected_slashed ($meta_key, $meta_value) -- Also, this looks really funky, doesn't seem like it works
	$query .= empty( $meta_key ) | empty($meta_value)  ? '' : $wpdb->prepare(" AND ($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = %s AND $wpdb->postmeta.meta_value = %s )", $meta_key, $meta_value);
	$query .= empty( $post_mime_type ) ? '' : wp_post_mime_type_where($post_mime_type);
	$query .= " GROUP BY $wpdb->posts.ID ORDER BY " . $orderby . ' ' . $order;
	if ( 0 < $numberposts )
		$query .= $wpdb->prepare(" LIMIT %d,%d", $offset, $numberposts);

	$posts = $wpdb->get_results($query);

	update_post_caches($posts);

	return $posts;
}
// end the old get_posts function

// the new get_posts function
function get_posts_new($args = null) {
	$defaults = array(
		'numberposts' => 5, 'offset' => 0,
		'category' => 0, 'orderby' => 'post_date',
		'order' => 'DESC', 'include' => '',
		'exclude' => '', 'meta_key' => '',
		'meta_value' =>'', 'post_type' => 'post',
		'post_status' => 'publish', 'post_parent' => 0
	);

	$r = wp_parse_args( $args, $defaults );
	if ( ! empty($r['numberposts']) )
		$r['posts_per_page'] = $r['numberposts'];
	if ( ! empty($r['category']) )
		$r['cat'] = $r['category'];
	if ( ! empty($r['include']) ) {
		$incposts = preg_split('/[\s,]+/',$r['include']);
		$r['posts_per_page'] = count($incposts);  // only the number of posts included
		$r['post__in'] = $incposts;
	} elseif ( ! empty($r['exclude']) )
		$r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']);
	
	$get_posts = new WP_Query;
	return $get_posts->query($r);

}

global $wpdb;
$query = ( isset( $_REQUEST['get-posts-query'] ) ) ? stripslashes($_REQUEST['get-posts-query']) : ''; 
$use_cache = ( isset( $_REQUEST['use-cache'] ) ) ? (int) $_REQUEST['use-cache'] : false;
echo "<p>Query is: <code>$query</code><p>";
?>
<form action="" method="post">
<label for="get-posts-query"><p>Enter query arguments to test out the functions. It's eval()'ed, so you can use arguments like <code>array('numberposts' => 3)</code> or <code>"numberposts=3"</code></p>
<input type="text" name="get-posts-query" id="get-posts-query" size="100" value="<?php echo htmlspecialchars($query) ?>" />
</label>
<p><label for="use-cache">Use Object Cache: <input type="checkbox" name="use-cache" value="1" <?php if ( $use_cache ) echo 'checked="checked"'; ?> /></label></p>
<input type="submit" value="Try Query" name="submit" />
</form>
<div style="width: 45%; float: left; border: 1px solid black; overflow: scroll;">
<h2>The old <code>get_posts</code> function:</h2>
<h3>Processing time: <?php 
if ( $use_cache ) {
	eval('$cache1 = get_posts_old(' . $query . ');');
} else {
	$wpdb->flush();
	wp_cache_flush();
}
timer_start();
eval('$old_posts = get_posts_old(' . $query . ');');
timer_stop(1); ?></h3>
<h3>Database queries: </h3><pre style="overflow: scroll; height: 10em;"><?php echo print_r($GLOBALS['test_wpdb_query']); ?></pre>
<?php if ( ! empty( $wpdb->queries ) ) : ?>
<h3>Saved db query info: </h3><pre style="overflow: scroll; height: 10em;"><?php echo print_r($wpdb->queries); ?></pre>
<?php endif; ?>
<pre>
<?php print_r($old_posts) ?>
</pre></div>

<div style="width: 45%; float: right; border: 1px solid black; overflow: scroll;">
<h2>The proposed <code>get_posts</code> function:</h2>
<h3>Processing time: <?php 
unset($GLOBALS['test_wpdb_query']);
if ( $use_cache ) {
	eval('$cache2 = get_posts_new(' . $query . ');');
} else {
	$wpdb->flush();
	wp_cache_flush();
}
timer_start();
eval('$new_posts = get_posts_new(' . $query . ');');
timer_stop(1); ?></h3>
<h3>Database queries: </h3><pre style="overflow: scroll; height: 10em;"><?php echo print_r($GLOBALS['test_wpdb_query']); ?></pre>
<?php if ( ! empty( $wpdb->queries ) ) : ?>
<h3>Saved db query info: </h3><pre style="overflow: scroll; height: 10em;"><?php echo print_r($wpdb->queries); ?></pre>
<?php endif; ?>
<pre>
<?php print_r($new_posts) ?>
</pre></div>
</body>
</html>
