<?php

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>',
        )
    );   
}

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

	$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">');
			echo ('<a href="'.get_category_link($category->cat_ID).'">'.$category->name.' </a>');
			echo '<ul>';
			
		
			$category_posts = get_posts('numberposts=15&category='.$category->cat_ID);
			$count2 = 0;
				 //echo("<!-- ".sizeof($category_posts)." -->");
					foreach($category_posts as $post) {
						
						echo '<li class="menu-h-li2" title="'.cache_cutter($post->post_title).'"><a href="'.$post->guid.'">'.text_cutter($post->post_title,200).'</a></li>';
						//echo '<li class="menu-h-li2" title="'.$count2.'"><a href="'.$post->guid.'">'.$post->post_title.'</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));
}


function dp_list_posts($Eparam='') {

		$category_posts = get_posts($Eparam);
		
		foreach($category_posts as $post) {
			echo '<li><a href="'.$post->guid.'">'.$post->post_title.'</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;
}
?>