<?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.2
Author: Rudd-O, Ori Pekelman
Author URI: http://rudd-o.com/
*/

/*
Derivative work from adhesive, copyright Owen Winkler and Manuel Amador (Rudd-O)
 modified by Ori Pekelman to support Gengo  Multilingual plugin( tested with version  0.7)
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() {// Start of modifications by Ori Pekelman to support Gengo
	global $wpdb,$homepage_metakey,$gengo;// add reference to Gengo object
	if (function_exists('the_language') ){ // test if gengo object exists
		$qry = "select {$wpdb->postmeta}.post_id from {$wpdb->postmeta} left join {$gengo->post2lang_table} on {$wpdb->postmeta}.post_id = {$gengo->post2lang_table}.post_id   left join {$gengo->language_table} on {$gengo->post2lang_table}.language_id = {$gengo->language_table}.language_id where {$gengo->language_table}.code ='".the_language_code(true)."' and {$wpdb->postmeta}.meta_key ='{$homepage_metakey}' AND {$wpdb->postmeta}.meta_value = '1'"; // Select only posts that have a meta of homepage and are in the current language. The second Join is just to get the language ID from the Language Code
	}else // fall back to original query if Gengo is not installed, End Modifications
	$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');


?>
