<?php
/*
Plugin Name: Home page for WordPress
Plugin URI: http://rudd-o.com/projects/wp-homepage/
Description: Mark a WordPress page as the home page, and make it show as the first post on the front page
Version: 0.0.1
Author: Rudd-O
Author URI: http://rudd-o.com/
*/

/*
Derivative work from adhesive, copyright Owen Winkler and Manuel Amador (Rudd-O)
Licensed under the GPL

*/

if(!function_exists('homepage_include_up')) {
	function homepage_include_up($filename) {
		$c=0;
		while(!is_file($filename)) {
			$filename = '../' . $filename;
			$c++;
			if($c==30) {
				echo 'Could not find ' . basename($filename) . '.';
				return '';
			}
		}
		return $filename;
	}
}


// Things to do when the file is included as a plugin

function homepage_basename($file) {
	return preg_replace('/^.*wp-content[\\\\\/]plugins[\\\\\/]/', '', $file);
}


// Don't change below here.

$homepage_metakey = 'homepage';

function homepage_should_kickin() {
	return is_home();
}

function homepage_get_stickies() {
	global $wpdb,$homepage_metakey;
	$qry = "SELECT {$wpdb->postmeta}.Post_ID FROM {$wpdb->postmeta} WHERE meta_key = '{$homepage_metakey}' AND meta_value = '1'";
	if($stickies = $wpdb->get_col($qry)) return $stickies;
	return array();
}

function homepage_posts_where($where)
{
	if (homepage_should_kickin()) {
		global $wpdb;
		$stickies = homepage_get_stickies();
		if ($stickies) {
			$stickies = "(" . implode(",",$stickies) . ")";
			$where = " AND ( 1=1 $where ) OR ID in $stickies";
		}
	}
	return $where;
}

function homepage_posts_orderby($orderby) {

	if (homepage_should_kickin()) {
		$stickies = homepage_get_stickies();
		if ($stickies) {
			$bluff = "";
			foreach ($stickies as $k => $v) {
				$bluff = " ( NOT ID IN (" . implode(",",$stickies) . ") ) ,";
			}
			$orderby = " $bluff $orderby";
		}
// 		die($orderby);
	}
	return $orderby;

}

// add_filter('the_posts', 'homepage_the_posts');
add_filter('posts_where', 'homepage_posts_where');
add_filter('posts_orderby', 'homepage_posts_orderby');


?>