<?php

function theme_init(){
	if (class_exists('xili_language')) {
		define('THEME_TEXTDOMAIN','IriTheme');
		define('THEME_LANGS_FOLDER','/language');
	} else {
	   load_theme_textdomain('IriTheme', get_template_directory() . '/languages');	
	}	
}
add_action ('init', 'theme_init');


//
define('THEME_TEXTDOMAIN','IriTheme');
define('THEME_LANGS_FOLDER','/language');
require( "lib/zip.lib.php" ) ; //indiquez le chemin d'accès à la lib

//error_reporting(E_ALL);

function getPost($post = NULL) {
	include('post.php');
}

function getSearch($q = NULL) {
	include('searchform.php');
}

if ( function_exists('register_sidebar') ){
    register_sidebar
    (   array
        (
          'name' => 'Sidebar-Single',
          'before_widget' => '<div class="bottombar">',
          'after_widget' => '</div>',
          'before_title' => '<h2 class="widgettitle">',
          'after_title' => '</h2>',
        )
    );
	register_sidebar
    (   array
        (
          'name' => 'Sidebar-Single-home',
          'before_widget' => '<div class="bottombar">',
          'after_widget' => '</div>',
          'before_title' => '<h2 class="widgettitle">',
          'after_title' => '</h2>',
        )
    );
    register_sidebar
    (   array
        (
          'name' => 'Bottom-Left',
          'before_widget' => '<div class="bottombar">',
          'after_widget' => '</div>',
          'before_title' => '<h2 class="widgettitle">',
          'after_title' => '</h2>',
        )
    );  
    register_sidebar
    (   array
        (
          'name' => 'Bottom-Middle',
          'before_widget' => '<div class="bottombar">',
          'after_widget' => '</div>',
          'before_title' => '<h2 class="widgettitle">',
          'after_title' => '</h2>',
        )
    );   
 register_sidebar
    (   array
        (
          'name' => 'Bottom-Right',
          'before_widget' => '<div class="bottombar">',
          'after_widget' => '</div>',
          'before_title' => '<h2 class="widgettitle">',
          'after_title' => '</h2>',
        )
    );   
}

// Need the tag Cloud Plug In 
// piece together the flash code
function xilimlSam_wp_cumulus_createflashcode( $widget=false, $atts=NULL ){


	// get the options
	if( $widget == true ){
		$options = get_option('wpcumulus_widget');
		$soname = "widget_so";
		$divname = "wpcumuluswidgetcontent";
		// get compatibility mode variable from the main options
		$mainoptions = get_option('wpcumulus_options');
		$options['compmode'] = $mainoptions['compmode'];
		$options['showwptags'] = $mainoptions['showwptags'];
	} else if( $atts != NULL ){
		$options = shortcode_atts( get_option('wpcumulus_options'), $atts );
		$soname = "shortcode_so";
		$divname = "wpcumuluscontent";
	} else {
		$options = get_option('wpcumulus_options');
		$soname = "so";
		$divname = "wpcumuluscontent";
	}
	// get the tag cloud...
	if( $options['mode'] != "cats" ){
		ob_start();	
		//wp_tag_cloud( $options['args'] );
		xili_tidy_tag_cloud('tagsgroup='.the_curlang());
		$tagcloud = urlencode( str_replace( "&nbsp;", " ", ob_get_clean() ) );	
	}
	// get categories
	if( $options['mode'] != "tags" ){
		ob_start();
		xili_tidy_tag_cloud('tagsgroup='.the_curlang());//
		$cats = urlencode( ob_get_clean() );
	}
	// get some paths
	if( function_exists('plugins_url') ){ 
		// 2.6 or better
		$movie = plugins_url('wp-cumulus/tagcloud.swf');
		$path = plugins_url('wp-cumulus/');
	} else {
		// pre 2.6
		$movie = get_bloginfo('wpurl') . "/wp-content/plugins/wp-cumulus/tagcloud.swf";
		$path = get_bloginfo('wpurl')."/wp-content/plugins/wp-cumulus/";
	}
	// add random seeds to so name and movie url to avoid collisions and force reloading (needed for IE)
	$soname .= rand(0,9999999);
	$movie .= '?r=' . rand(0,9999999);
	$divname .= rand(0,9999999);
	// write flash tag
	if( $options['compmode']!='true' ){
		$flashtag = '<!-- SWFObject embed by Geoff Stearns geoff@deconcept.com http://blog.deconcept.com/swfobject/ -->';	
		$flashtag .= '<script type="text/javascript" src="'.$path.'swfobject.js"></script>';
		// ------------------------------------------------------------------------------------
		$flashtag .= '<div id="'.$divname.'" style="position:absolute;z-index:0;">';
		if( $options['showwptags'] == 'true' ){ $flashtag .= '<p>'; } else { $flashtag .= '<p style="display:none;">'; };
		// alternate content
		if( $options['mode'] != "cats" ){ $flashtag .= urldecode($tagcloud); }
		if( $options['mode'] != "tags" ){ $flashtag .= urldecode($cats); }
		$flashtag .= '</p><!-- WP Cumulus Flash tag cloud by <a href="http://www.roytanck.com">Roy Tanck</a> and <a href="http://lukemorton.co.uk/">Luke Morton</a> requires <a href="http://www.macromedia.com/go/getflashplayer">Flash Player</a> 9 or better.   --></div>';
		$flashtag .= '<script type="text/javascript">';
		$flashtag .= 'var '.$soname.' = new SWFObject("'.$movie.'", "tagcloudflash", "'.$options['width'].'", "'.$options['height'].'", "9", "#'.$options['bgcolor'].'");';
		if( $options['trans'] == 'true' ){
			$flashtag .= $soname.'.addParam("wmode", "transparent");';
		}
		$flashtag .= $soname.'.addParam("allowScriptAccess", "always");';
		$flashtag .= $soname.'.addVariable("tcolor", "0x'.$options['tcolor'].'");';
		$flashtag .= $soname.'.addVariable("tcolor2", "0x' . ($options['tcolor2'] == "" ? $options['tcolor'] : $options['tcolor2']) . '");';
		$flashtag .= $soname.'.addVariable("hicolor", "0x' . ($options['hicolor'] == "" ? $options['tcolor'] : $options['hicolor']) . '");';
		$flashtag .= $soname.'.addVariable("tspeed", "'.$options['speed'].'");';
		$flashtag .= $soname.'.addVariable("distr", "'.$options['distr'].'");';
		$flashtag .= $soname.'.addVariable("mode", "'.$options['mode'].'");';
		// put tags in flashvar
		if( $options['mode'] != "cats" ){
			$flashtag .= $soname.'.addVariable("tagcloud", "'.urlencode('<tags>') . $tagcloud . urlencode('</tags>').'");';
		}
		// put categories in flashvar
		if( $options['mode'] != "tags" ){
			$flashtag .= $soname.'.addVariable("categories", "' . $cats . '");';
		}
		$flashtag .= $soname.'.write("'.$divname.'");';
		$flashtag .= '</script>';
	} else {
		$flashtag = '<object type="application/x-shockwave-flash" data="'.$movie.'" width="'.$options['width'].'" height="'.$options['height'].'" wmode="opaque">';
		$flashtag .= '<param name="movie" value="'.$movie.'" />';
		$flashtag .= '<param name="bgcolor" value="#'.$options['bgcolor'].'" />';
		$flashtag .= '<param name="AllowScriptAccess" value="always" />';
		$flashtag .= '<param name="wmode" value="opaque" />';
		if( $options['trans'] == 'true' ){
			$flashtag .= '<param name="wmode" value="transparent" />';
		}
		$flashtag .= '<param name="flashvars" value="';
		$flashtag .= 'tcolor=0x'.$options['tcolor'];
		$flashtag .= '&amp;tcolor2=0x'.$options['tcolor2'];
		$flashtag .= '&amp;hicolor=0x'.$options['hicolor'];
		$flashtag .= '&amp;tspeed='.$options['speed'];
		$flashtag .= '&amp;distr='.$options['distr'];
		$flashtag .= '&amp;mode='.$options['mode'];
		// put tags in flashvar
		if( $options['mode'] != "cats" ){
			$flashtag .= '&amp;tagcloud='.urlencode('<tags>') . $tagcloud . urlencode('</tags>');
		}
		// put categories in flashvar
		if( $options['mode'] != "tags" ){
			$flashtag .= '&amp;categories=' . $cats;
		}
		$flashtag .= '" />';
		// alternate content
		if( $options['mode'] != "cats" ){ $flashtag .= '<p>'.urldecode($tagcloud).'</p>'; }
		if( $options['mode'] != "tags" ){ $flashtag .= '<p>'.urldecode($cats).'</p>'; }
		$flashtag .= '<!-- WP-Cumulus by <a href="http://www.roytanck.com/">Roy Tanck</a> and <a href="http://lukemorton.co.uk/">Luke Morton</a> requires <a href="http://www.macromedia.com/go/getflashplayer">Flash Player</a> 9 or better. -->';
		$flashtag .= '</object>';
	}
	return $flashtag;
}

// Copy of the current category widget plugin adapted to xiliml
function xilimlSam_post_of_current_category (){
 global $wpdb;
	
	$defaults = array(
		'limit' => 30,
		'AscDesc' => "DSC", 
		'OrderBy' =>'ID',
	);
	
	$args =  $defaults;
	$lang = the_curlang();//echo ($lang);
	extract($args);
	
	$limit = (int) abs($limit);
		
	if(is_category()){
		$curCategoryID = get_query_var('cat');
	}
	
	if (is_single()) {
		$curCategoryID = '';
		
		foreach (get_the_category() as $catt) {
			$curCategoryID .= $catt->cat_ID.' '; 
		}
		
		$curCategoryID = str_replace(" ", ",", trim($curCategoryID));
	}
	
	if (!intval($curCategoryID)) $curCategoryID='';
	$query = "&category=$curCategoryID&showposts=$limit&orderby=$OrderBy&order=$AscDesc";
	$posts = get_posts($query); //get posts
	$postlist = '';	
	
    foreach ($posts as $post) {
	
		$CurLang = get_cur_post_lang_dir ($post->ID);//echo ($post->ID."-> ".$CurLang["lang"]."   <br/>");
		if($CurLang["lang"]==$lang){
			$post_title_s = htmlspecialchars(stripslashes(cache_cutter($post->post_title)));
			$post_title_l = htmlspecialchars(stripslashes(text_cutter($post->post_title,200)));
			$postlist .= '<li> <a href="' . get_permalink($post->ID) . '" title="'.  $post_title_s .'" >' . $post_title_l . ' </a> </li>';
		}
    }
	
	echo '<ul class="advanced-recent-posts">';		
		echo $postlist;
	echo '</ul>';

}

# 
function xilimlSam_page2cat_output_Hook($cat){
	
	if( function_exists(page2cat_output) and function_exists(xiliml_the_other_posts) ){
	
		global $wpdb;
		$mypage = $wpdb->get_row("SELECT * FROM {$wpdb->page2cat} WHERE cat_ID = '".$cat."';",OBJECT);
		$pageid = $mypage->page_ID;
		$pageInOtherLang = xiliml_the_other_posts ($pageid,'','','array');
		
		if($pageInOtherLang[the_curlang()]!=null){
			$pageid=$pageInOtherLang[the_curlang()];
		}
		
		if($pageid != ""):
		
		switch($style):
		
		case 'inline':
		default:	
		?>
		<div id="category-page-header">
		<?php
		$pagina = "SELECT * FROM {$wpdb->posts} WHERE ID='".$pageid."' AND post_type = 'page';";
		$mine = $wpdb->get_results($pagina);
		if($mine[0]->post_title!=""){
					?>
					<div id="p2c-header">
						<h2><?php echo $mine[0]->post_title; ?></h2>
						<p><?php echo wptexturize($mine[0]->post_content,1); ?></p>
					</div> 
			<div class="category-page-cleaner"></div>
		</div>
		<?php
		}
		break;
		
		
		endswitch;
		endif;
	}
	
	/*
		$current_lang = the_cur_lang_dir();
		page2cat_output($cat);
		
		$MyPost = xiliml_the_other_posts($post_ID,"","","array");
		//var_dump($MyPost);
		//echo($current_lang['lang']." -> ".$MyPost[$current_lang['lang']]);
		
		if (in_array($current_lang['lang'],$MyPost)){
			return ($post_ID);
		} else {
			return ($MyPost[$current_lang['lang']]);
			
		}
	*/
}

# 
function xilimlSam_other_posts($post_ID){

		if (class_exists('xili_language')) {
		
			$current_lang = the_cur_lang_dir();
			
			$MyPost = xiliml_the_other_posts($post_ID,"","","array");
			//var_dump($MyPost);
			//echo($current_lang['lang']." -> ".$MyPost[$current_lang['lang']]);
			
			if (in_array($current_lang['lang'],$MyPost)){
				return ($post_ID);
			} else {
				return ($MyPost[$current_lang['lang']]);
				
			}
			
		} else {
			return ($post_ID);
		}
		
}

# 
function xilimlSam_other_pages($post_ID){

		if (class_exists('xili_language')) {
		
			$current_lang = the_cur_lang_dir();
			
			$MyPost = xiliml_the_other_posts($post_ID,"","","array");
			//var_dump($MyPost);
			//echo($current_lang['lang']." -> ".$MyPost[$current_lang['lang']]);
			
			if (in_array($current_lang['lang'],$MyPost)){
				return ($post_ID);
			} else {
				return ($MyPost[$current_lang['lang']]);
				
			}
			
		} else {
			return ($post_ID);
		}
}

# Displays a list of categories
function dp_list_categories($Eparam='') {

	if (class_exists('xili_language')) {
		$current_lang = the_cur_lang_dir();
	}
	
	$categories = get_categories('hide_empty=1'.$Eparam);
	$first = true;
	$count = 0;
	
	foreach ($categories as $category) {

		if ($category->parent<1) {
						
			echo ('<li class="menu-h-li">');

			if (class_exists('xili_language')) {
				echo ('<a href="'.xiliml_get_category_link($category->cat_ID).'?lang='.$current_lang['lang'].'">'.__($category->name,'IriTheme').' </a>');
			} else {
				echo ('<a href="'.get_category_link($category->cat_ID).'">'.__($category->name,'IriTheme').' </a>');
			}
			echo '<ul>';
			
			$category_posts = get_posts('numberposts=15&order=ASC&orderby=parent&category='.$category->cat_ID);
			$count2 = 0;
			/*$categoryN2 = get_category_link($category->cat_ID);
			
					foreach($categoryN2 as $catN2) {
						
						//$category_posts = get_posts('numberposts=15&order=ASC&orderby=parent&category='.$category->cat_ID);
						echo ('<li class="menu-h-li2"><a href="'.get_category_link($catN2->cat_ID).'"> XX '.$catN2->name.' </a></li>');
					}*/
					
					//echo("<!-- ".sizeof($category_posts)." -->");
					foreach($category_posts as $post) {
						
						
						if (class_exists('xili_language')) {
								// Affiche les posts de la langue courante + les indéfinis 
								//if (get_cur_language($post->ID)==$current_lang['lang'] or get_cur_language($post->ID)==""){
								// Affiche seulement les posts  de la langue courante + les indéfinis 
							if (get_cur_language($post->ID)==$current_lang['lang']){
								
								// gestion des niv 2 ajout de class si nécessaire
								$MyCategoryPost = get_the_category($post->ID);
								//var_dump($MyCategoryPost);

								$MoreStyle="";
								$title ="";
								if (count($MyCategoryPost)>1){
										foreach($MyCategoryPost as $MyCategory) { 
											$MoreStyle.= " ".$MyCategory->category_nicename;
											$title.= " ".$MyCategory->category_nicename;
											//category_parent!=0
										} 							
								} else {
								$MoreStyle ="menu-h-li2";
								}
								
								echo '<li class="'.$MoreStyle.'" title="'.cache_cutter($post->post_title)." : ".$MoreStyle.'"><a href="'.get_permalink($post->ID).'">'.text_cutter($post->post_title,200).'</a></li>';
								$count2++; //if ($count2>6) break;
							}
							
						} else {
						
							echo '<li class="menu-h-li2" title="'.cache_cutter($post->post_title).'"><a href="'.get_permalink($post->ID).'">'.text_cutter($post->post_title,200).'</a></li>';
							$count2++; //if ($count2>6) break;
						}
						
					};
					

				echo "</ul></li>";
			
		}
		$count++; //if ($count>6) break; // limit to 5
		
	}
}

# Display the list of movies
function listeMyLdt(){

	$MyLdtDataBase 	= DB_NAME;
	$MyWPDataBase 	= DB_NAME;
	$MyLdtTable 	= LDT_DB;
	$MyLdtconnexion = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	$MyLdtListe		= "";
	//$WP_db_selected    = mysql_select_db();
	
	if (!$MyLdtconnexion) {
	   echo "Impossible de se connecter à la base de données : " . mysql_error();
	   exit;
	}

	if (!mysql_select_db($MyLdtDataBase)) {
	   echo "Impossible de sélectionner la base mydbname : " . mysql_error();
	   exit;
	}

	$MyLdtSql = "SELECT * FROM  ".$MyLdtTable." ORDER BY `Lignes`.`Auteur` ASC";// WHERE `NomFichier` NOT LIKE ''";

	$result = mysql_query($MyLdtSql);

	if (!$result) {
	   echo "Impossible d'exécuter la requête ($MyLdtSql) dans la base : " . mysql_error();
	   exit;
	}

	if (mysql_num_rows($result) == 0) {
	   echo "Aucune ligne trouvée, rien à afficher.";
	   exit;
	}
	$MyLdtTable="";
	while ($row = mysql_fetch_assoc($result)) {
	   $MyLdtLineTemplate = "<tr class='rollover'>
							 <td>".$row['Auteur']."</td> <td>".$row['Titre']."</td>  <td>".$row['Contributeur']."</td> ";
							 
		if ($row['NomFichier']!="") {
			$MyLdtLineTemplate .= "<td> <a href='?URL=".$row['NomFichier']."' title='Cliquez ici pour télécharger le projet".$row['NomFichier']."'> <img src='".get_bloginfo('stylesheet_directory')."/images/get.png'/> </a> </td> </tr>";
		}else {
			$MyLdtLineTemplate .= "<td> <a href='#' title='Fichier non disponible'> <img src='".get_bloginfo('stylesheet_directory')."/images/help.png'/> </a> </td> </tr>";
		}
		
	   $MyLdtTable .=  $MyLdtLineTemplate."\n";
	   
	}
	
	//  tableau
	$MyLdtOutPut = "
	<div class='box'>
		<table style='width:100%;'>
			<thead>
				<tr>
					<td class='thead'> <b>Auteur</b></td>
					<td class='thead'> <b>Titre</b> </td>
					<td class='thead'> <b>Contributeur(s)</b> </td>
					<td class='thead'> </td>
				</tr> 
			</thead>
			".$MyLdtTable."
		</table></div>";
	
	echo($MyLdtOutPut);
	
	mysql_free_result($result);
	mysql_select_db($MyWPDataBase);
	//mysql_select_db($WP_db_selected);
}

# Create the  LDT's ZIP to download IT 
function createMyLdtProject($fichierIRI){

	$MyLDTRoot  = ABSPATH;
	$MyDocPath  = LDT_PATH;
	$MyRootRel  = DWL_PAGE;
	$MyCache	= LDT_CACHE;
	$MyExemple 	= LDT_TEMPLATE;
	$MyPattern  = "X_NOMPROJET_X";
	$MyLdtName 	= "projet_".$MyPattern.".ldt";
	$MyReadMeName="LISEZ_MOI_READ_ME.txt";
	$MySoundExt = "_audio.xml";
	$Return 	= "";
	
	$end 		 = strrpos($fichierIRI,"."); 
	$FileName	 = substr($fichierIRI, 0, $end);
	$ext		 = substr($fichierIRI, $end, strlen($FileName));
	$Zipfilename = $MyLDTRoot.$MyCache."/".$FileName.".zip";
	$ZipfilenameRedir = $MyRootRel.$MyCache."/".$FileName.".zip";
	$baseExemplePath = $MyLDTRoot.$MyExemple;
	$baseDocPath = $MyLDTRoot.$MyDocPath;
	
	// cette fontion n'est utilisé que sur les .IRI
	if ($ext==".iri"){
	
		// Vérifie si le cache éxiste déja
		if (file_exists($Zipfilename)){
			echo ($Zipfilename." is in cache ");
			// ensuite envoyer vers la redirection.
			echo ("Veuillez patientez un instant...");
			redirectionDWL($ZipfilenameRedir);
			
		} else {
		
			echo ("Le fichier ".$FileName.".zip est en cours de compression, veuillez patientez un instant...");
					
			// Créer le .LDT à partir de l'exemple
			$MyLdtExemple = implode(file($baseExemplePath."/".$MyLdtName , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
			$MyFuturLdt = str_replace($MyPattern, $FileName, $MyLdtExemple);
		
			// Créer le read me 
			$MyReadMeExemple = implode(file($baseExemplePath."/".$MyPattern."/".$MyReadMeName , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
			$MyFuturReadMe = str_replace($MyPattern, $FileName, $MyReadMeExemple);
			
			// ZIP l'ensemble est mis dans le cache
			
			$zip = new ZipArchive();
			if ($zip->open($Zipfilename, ZIPARCHIVE::CREATE)!==TRUE) {
				exit("Impossible d'ouvrir <$filename>\n");
			}		
			// ZIP - ajouter le .LDT 
			$MyLdtNewName = str_replace($MyPattern, $FileName, $MyLdtName);
			$zip->addFromString($MyLdtNewName, $MyFuturLdt); //$zip->addFile($MyFuturLdtName, $FileName);
			// ZIP - ajouter le .IRI 
			$zip->addFile($baseDocPath."/".$fichierIRI, $FileName."/".$fichierIRI); 
			// ZIP - ajouter le ReadMe
			$zip->addFromString($FileName."/".$MyReadMeName, $MyFuturReadMe); //$zip->addFile($MyRoot.$MyTemp."/".$FileName."/".$MyReadMeName, $FileName."/".$MyReadMeName); 
			// ZIP - ajouter le audio si il y a 
			$fileAudio	= $baseDocPath."/".$FileName.$MySoundExt ;
			if (file_exists($fileAudio)){
				$zip->addFile($fileAudio, $FileName."/".$FileName.$MySoundExt); 
			}
			$zip->close();
			
			// mettre a jour la bdd ? pour vider le cache quand c'est un nouveau fichier ? 
			
			// ensuite envoyer vers la redirection.
			redirectionDWL($ZipfilenameRedir);
			//echo ('<br/> DWL : '.$FileDWL);
		}
	}
}

# Javascript DWL redirection 
function redirectionDWL ($url) {

     $URL = get_bloginfo('url')."/".$url; 
	 
	 echo("Le téléchargement est en cours... <br/>\n
    Si le téléchargement ne démarre pas automatiquement, veuillez cliquez <a href=".$URL.">ici</a>.<br/>\n");
	 
     echo("<script  language=\"javascript\" type=\"text/javascript\"> \n");
     echo("     <!--\n");
	 echo(" 	jQuery(document).ready(function($) {");
	 echo(" 		$(location).attr('href','".$URL."');");
	 echo(" 	});");
     echo("     //-->\n");
     echo("</script>\n");
	 
}

# Text cutter
function text_cutter($text,$length){
	$symbole="<!-- cut -->";
	
	$lastpos = strrpos($text,$symbole); 
	
	if($lastpos!=FALSE){
	
		return (substr($text, 0, $lastpos));
	
	} else {
	
		if(strlen($text)>$length){
			return (substr($text, 0, $length)."[...]");
		} else {
			return ($text);
		}
	}
}

# Cache cutter
function cache_cutter($text){
	return (str_replace( "<!-- cut -->", "", $text));
}

# Créer le menu du footer 
function dp_list_posts($Eparam='') {

	$category_posts = get_posts($Eparam);
	
	if (class_exists('xili_language')) {
		$current_lang = the_cur_lang_dir();
		foreach($category_posts as $post) {
			if (get_cur_language($post->ID)==$current_lang['lang']){
				echo '<li><a href="'.get_permalink($post->ID).'">'.__($post->post_title,'IriTheme').'</a></li>';
			}
		};
	} else {
		foreach($category_posts as $post) {
			echo '<li><a href="'.get_permalink($post->ID).'">'.__($post->post_title,'IriTheme').'</a></li>';
		};
	}
}


/*
Plugin Name: Get The Image
Plugin URI: http://justintadlock.com/archives/2008/05/27/get-the-image-wordpress-plugin
Description: This is a highly intuitive script that gets an image either by custom field input or post attachment.
Version: 0.1 Beta
Author: Justin Tadlock
Author URI: http://justintadlock.com
License: GPL
*/

/***********************************************************
Catchall function for getting images
***********************************************************/
function get_the_image($arr = false, $default_size = 'medium', $default_img = false) {
	global $post;
	$cf_array = load_the_image($arr, $post, $default_size);
	$image = display_the_image($cf_array, $post, $default_size, $default_img);
	if($image == false) $image = '<!-- No images were added to this post. -->';
	return $image;
}

/***********************************************************
Catchall function for getting images with a link
***********************************************************/
function get_the_image_link($arr = false, $default_size = 'medium', $default_img = false) {
	global $post;
	$cf_array = load_the_image($arr, $post, $default_size);
	$image = display_the_image($cf_array, $post, $default_size, $default_img);

	if($image == false) :
		$image_link = '<!-- No images were added to this post. -->';
	else :
		$post_perm = get_permalink($post->ID);
		$image_link = "<a href=\"$post_perm\" title=\"$post->post_title\">$image</a>";
	endif;
	return $image_link;
}

/***********************************************************
Function for loading an image
***********************************************************/
function load_the_image($custom_fields = false, $en_post, $default_size) {

// Checks only if there are custom fields to check for
	if(isset($custom_fields)) {

	// Loop through the custom fields, checking for images or video
		$i = 0;
		while(strcmp($image[0],'') == 0 && $i <= sizeof($custom_fields)) {

		// Check custom field values for image, image alt text, and image class
			$image = get_post_custom_values($key = $custom_fields[$i]);
			$image_alt = get_post_custom_values($key = $custom_fields[$i] . ' Alt');
			$image_class = get_post_custom_values($key = $custom_fields[$i] . ' Class');
		// Convert custom field key name to image class
			$img_class = $custom_fields[$i];
			$img_class = strtolower($img_class);
			$img_class = str_replace (" ", "-", $img_class);

		// Add space to image class if user inputs an extra class
			if($image_class == true) $image_class .= ' ';

		// Add user image class to default image classes
			if($default_size == 'thumbnail' && $img_class == 'thumbnail') $image_class .= $default_size;
			elseif($default_size == 'medium' && $img_class == 'medium') $image_class .= $default_size;
			elseif($default_size == 'full' && $img_class == 'full') $image_class .= $default_size;
			else $image_class .= $img_class . ' ' . $default_size;

		$i++;
		} // End while loop
	} // End check for custom field image

// If there is no image set through custom fields, check post attachments
	if($image == false && $default_size == true) {
		$img_att_arr = find_attachment_image($custom_fields[0], $en_post, $default_size);
		if(strcmp($image_att_arr[0],'') == 0) :
			$image = $img_att_arr[0];
			$image_class = $img_att_arr[1];
			$image_alt = false;
		else :
			$image = false; $image_alt = false; $image_class = false;
		endif;
	}

// Return array with an image, image alt, and image class
	return array($image, $image_alt, $image_class);
}

/***********************************************************
Function for displaying an image
***********************************************************/
function display_the_image($cf_array = false, $en_post = false, $default_size = false, $default_img = false) {

// Set nice names for image info
	if($cf_array[0] == false && $default_img == true) :
		$image[0] = $default_img;
		$image_class = $default_size;
	else :
		$image = $cf_array[0];
		$image_alt = $cf_array[1];
		$image_class = $cf_array[2];
	endif;

// If there's any kind of image for this post
	if(isset($image[0]) && strcmp($image[0],'') != 0) :
	// Open img tag
		$output = '<img src="'.$image[0].'"';
		$output .= ' alt="';
	// Image alt text
		if(isset($image_alt[0]) && strcmp($image_alt[0],'') != 0) $output .= $image_alt[0];
		else $output .= $en_post->post_title;
	// Image class
		$output .= '" class="';
		if(isset($image_class[0])) $output .= $image_class;
		else $output .= 'left';
	// Close img tag
		$output .= '" />';
// If there's no image
	else :
		$output = false;
	endif;
// Return the image
	return $output;
}

/***********************************************************
Function for finding an attachment image.
Only called if no custom field images are set.
***********************************************************/
function find_attachment_image($custom_fields = false, $en_post = false, $default_size = 'medium') {

	$custom = $custom_fields;
	$custom = strtolower($custom);
	$custom = str_replace (" ", "-", $custom);
// Don't repeat the same class name
	if($custom == 'thumbnail' || $custom == 'medium' || $custom == 'full') $img_class = $default_size;
	else $img_class = $custom . ' ' . $default_size;

	$attachments = get_children("post_parent=$en_post->ID&post_type=attachment&post_mime_type=image&orderby=\"menu_order ASC, ID ASC\"&numberposts=1");
	if($attachments == true) :
		foreach($attachments as $id => $attachment) :
			$img = wp_get_attachment_image_src($id, $default_size);
			$img_arr[0] = $img;
		endforeach;
		$img_arr[1] = $img_class;
	else :
		$img_arr = false;
	endif;
	return $img_arr;
}

?>