<?php
/**
 * @package WP-ldt-downloader
 * @author Samuel Huron
 * @version 0.1
 */
/*
Plugin Name: WP-ldt-downloader
Plugin URI: http://www.iri.centrepompidou.fr
Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
Author: Samuel Huron 
Version: 0.1
Author URI: http://www.cybunk.com
*/

// replace tag in content with tag cloud (non-shortcode version for WP 2.3.x)
function WP-ldt-downloader_init($content){
	if( strpos($content, '[WP-LDT-DWL]') === false ){
		return $content;
	} else {
		$code = WP-ldt-Template-Liste();
		$content = str_replace( '[WP-LDT-DWL]', $code, $content );
		return $content;
	}
}

function WP-ldt-Template-Liste(){

	// HTML TR
	$MyLdtLineTemplate = "<tr>
							 <td>"."X_row['Auteur']_X"."</td>
							 <td>"."X_row['Titre']_X"."</td>
							 <td>"."X_row['Fond']_X"."</td> 
							 <td> <a href='?URL="."X_row['NomFichier']_X"."' nicetitle='Cliquez ici pour télécharger le projet"."X_row['NomFichier']_X"."'>
							 <img src='".get_bloginfo('stylesheet_directory')."/images/get.png'/> </a> </td>
						 </tr>";			 
						 
						 
	// GET the DB informations
	$MyListe = listeMyLdt($MyLdtLineTemplate);
	
	 //  HTML table
	$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>Fond</b>  </td>
					<td class='thead'> </td>
				</tr>
			</thead>
			".$MyListe."
		</table></div>";
		
	echo ($MyLdtOutPut);

}

function WP-ldt-downloader(){


	
	
	
}

# Display the list of movies
function WP-ldt-listeMyLdt($template){

	$MyLdtDataBase 	= "lignesIRI";
	$MyLdtTable 	= "Lignes";
	$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." 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 = str_replace( "X_row['Auteur']_X", $row['Auteur'], $template );
		$MyLdtLineTemplate = str_replace( "X_row['Auteur']_X", $row['Titre'], $MyLdtLineTemplate  );
		$MyLdtLineTemplate = str_replace( "X_row['Auteur']_X", $row['Fond'], $MyLdtLineTemplate  );
		$MyLdtLineTemplate = str_replace( "X_row['Auteur']_X", $row['NomFichier'], $MyLdtLineTemplate  );
	    /*
		"<tr onClick='?URL=".$row['NomFichier']."'>
		 <td>".$row['Auteur']."</td> <td>".$row['Titre']."</td> <td>".$row['Fond']."</td> 
		 <td> <a href='?URL=".$row['NomFichier']."' nicetitle='Cliquez ici pour télécharger le projet".$row['NomFichier']."'> <img src='".get_bloginfo('stylesheet_directory')."/images/get.png'/> </a> </td> </tr>";
		*/
	   $MyLdtTable .=  $MyLdtLineTemplate."\n";
	   
	}
		
	return ($MyLdtTable);
	
	mysql_free_result($result);
	//mysql_select_db($WP_db_selected);
}

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

	$MyRoot   	= "/iridata/users/hurons/public_html/DOCUMENT/_LDT";
	$MyRootRel  = "non-classe/telecharger/?URL=DOCUMENT/_LDT";
	$MyCache	= "/CACHE";
	$MyExemple 	= "/EXEMPLE_zip";
	$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));
	
	
	// cette fontion n'est utilisé que sur les .IRI
	if ($ext==".iri"){
	
		// Vérifie si le cache éxiste déja
		if (file_exists($MyCache."/".$FileName.".zip")){
			//echo ($MyCache.$FileName.".zip"." is in cache");
			// ensuite envoyer vers la redirection.
			redirectionDWL($MyRootRel.$MyCache."/".$FileName.".zip");
			
		} 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($MyRoot.$MyExemple."/".$MyLdtName , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
			$MyFuturLdt = str_replace($MyPattern, $FileName, $MyLdtExemple);
		
			// Créer le read me 
			$MyReadMeExemple = implode(file($MyRoot.$MyExemple."/".$MyPattern."/".$MyReadMeName , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
			$MyFuturReadMe = str_replace($MyPattern, $FileName, $MyReadMeExemple);
			
			// ZIP l'ensemble est met dans le cache
			$Zipfilename = $MyRoot.$MyCache."/".$FileName.".zip";
			$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($MyRoot."/".$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	= $MyRoot."/".$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($MyRootRel.$MyCache."/".$FileName.".zip");
		}
	}
}

# Javascript DWL redirection 
function WP-ldt-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("    document.location.href = \"".$URL."\";\n ");
     echo("    window.location = \"".$URL."\";\n ");
     echo("     //-->\n");
     echo("</script>\n");
	 
}


//______________________



function hello_dolly_get_lyric() {
	/** These are the lyrics to Hello Dolly */
	$lyrics = "Hello, Dolly
Well, hello, Dolly
It's so nice to have you back where you belong
You're lookin' swell, Dolly
I can tell, Dolly
You're still glowin', you're still crowin'
You're still goin' strong
We feel the room swayin'
While the band's playin'
One of your old favourite songs from way back when
So, take her wrap, fellas
Find her an empty lap, fellas
Dolly'll never go away again
Hello, Dolly
Well, hello, Dolly
It's so nice to have you back where you belong
You're lookin' swell, Dolly
I can tell, Dolly
You're still glowin', you're still crowin'
You're still goin' strong
We feel the room swayin'
While the band's playin'
One of your old favourite songs from way back when
Golly, gee, fellas
Find her a vacant knee, fellas
Dolly'll never go away
Dolly'll never go away
Dolly'll never go away again";

	// Here we split it into lines
	$lyrics = explode("\n", $lyrics);

	// And then randomly choose a line
	return wptexturize( $lyrics[ mt_rand(0, count($lyrics) - 1) ] );
}

// This just echoes the chosen line, we'll position it later
function hello_dolly() {
	$chosen = hello_dolly_get_lyric();
	echo "<p id='dolly'>$chosen</p>";
}

// Now we set that function up to execute when the admin_footer action is called
add_action('admin_footer', 'hello_dolly');

// We need some CSS to position the paragraph
function dolly_css() {
	// This makes sure that the posinioning is also good for right-to-left languages
	$x = ( 'rtl' == get_bloginfo( 'text_direction' ) ) ? 'left' : 'right';

	echo "
	<style type='text/css'>
	#dolly {
		position: absolute;
		top: 4.5em;
		margin: 0;
		padding: 0;
		$x: 215px;
		font-size: 11px;
	}
	</style>
	";
}

add_action('admin_head', 'dolly_css');

?>
