<?php
// Chargement des données
require_once('donnees_generales.php');

// Chemin vers la librairie GETID3
require_once('scripts/getid3/getid3.php');

function cleanText($intext) {
	return htmlspecialchars(stripslashes($intext), ENT_COMPAT | ENT_HTML401, "utf-8");
}

if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
    $link = "https";
}else{
    $link = "http"; 
}
$link .= "://"; 
$link .= $_SERVER['HTTP_HOST'];
$link .= $_SERVER['REQUEST_URI'];
$file = basename($link);
if(strpos($file, '.xml') or strpos($file, '.php')) {
	$link = str_replace($file, '', $link);
}


$dir = getcwd();
$dirprim = getcwd();
if($diradd) {
	$dir = $dir.'/'.$diradd;
}


function scan_dir($dirscan, $dirscanadd) {

    $files = array();    
    foreach (scandir($dirscan) as $file) {
		if(strpos($file, ".mp3")) {
			if($dirscanadd) {
				$file = $dirscanadd.'/'.$file;
			}
			$files[$file] = filectime($file);
		}
    }

    arsort($files);
    $files = array_keys($files);

    return ($files) ? $files : false;
}


$array = scan_dir($dir, $diradd);

$lastpubli = date('D, d M Y H:i:s', filectime($array[0]));


// Début de la génération du XML

header("Content-Type: text/xml");

$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$xml .= '<?xml-stylesheet type="text/xsl" href="scripts/rss.xslt" ?>'."\n";
$xml .= '<rss
	xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
	xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:spotify="http://www.spotify.com/ns/rss"
	xmlns:psc="http://podlove.org/simple-chapters/"
	version="2.0">'."\n";
$xml .= '<channel>'."\n";

$xml .='<title>'.$titre.'</title>'."\n";
$xml .='<link>'.$url.'</link>'."\n";
if($urlfacebook and $urlfacebook != 'https://' and $urlfacebook != 'http://') {
	$xml .='<facebook>'.$urlfacebook.'</facebook>'."\n";
}
if($urltwitter and $urltwitter != 'https://' and $urltwitter != 'http://') {
	$xml .='<twitter>'.$urltwitter.'</twitter>'."\n";
}
if($urlinstagram and $urlinstagram != 'https://' and $urlinstagram != 'http://') {
	$xml .='<instagram>'.$urlinstagram.'</instagram>'."\n";
}
$xml .='<atom:link rel="self" type="application/rss+xml" href="'.$link.'rss.php"/>'."\n";
$xml .='<description>'.$description.'</description>'."\n";
$xml .='<language>'.$language.'</language>'."\n";
$xml .='<copyright>'.$auteur.'</copyright>'."\n";
$xml .='<lastBuildDate>'.$lastpubli.' GMT</lastBuildDate>'."\n";
$xml .='<pubDate>'.$lastpubli.' GMT</pubDate>'."\n";
$xml .='<webMaster>contact@badgeek.fr (BadGeek)</webMaster>'."\n";
$xml .='<generator>BadGeek (https://www.badgeek.fr)</generator>'."\n";
$xml .='<managingEditor>'.$mailauteur.'</managingEditor>'."\n";
$xml .='<spotify:countryOfOrigin>'.$pays.'</spotify:countryOfOrigin>'."\n";

$xml .='<itunes:author>'.$auteur.'</itunes:author>'."\n";
$xml .='<itunes:owner>
<itunes:name>'.$auteur.'</itunes:name>
<itunes:email>'.$mailauteur.'</itunes:email>'."\n";
$xml .='</itunes:owner>'."\n";
$xml .='<itunes:summary>'.$description.'</itunes:summary>'."\n";
$xml .='<itunes:explicit>'.$explicit.'</itunes:explicit>'."\n";	
$xml .='<itunes:block>'.$appleblock.'</itunes:block>'."\n";	
$xml .='<itunes:type>episodic</itunes:type>'."\n";
$xml .='<itunes:subtitle>'.$titre.'</itunes:subtitle>'."\n";

$xml .='<googleplay:author>'.$auteur.'</googleplay:author>'."\n";
$xml .='<googleplay:email>'.$mailauteur.'</googleplay:email>'."\n";
$xml .='<googleplay:description>'.$description.'</googleplay:description>'."\n";
$xml .='<googleplay:explicit>'.$explicit.'</googleplay:explicit>'."\n";
$xml .='<googleplay:block>'.$googleblock.'</googleplay:block>'."\n";

$categorie = str_replace('&', '&amp;', $categorie);
$xml .= '<category>'.$categorie.'</category>'."\n";
if(strstr($categorie, ' > ')) {
	
	$theme_add = explode(" > ", $categorie);
	
	$premiertheme = trim($theme_add[0]);
	$secondtheme = str_replace($premiertheme.' > ', '', $categorie);
	
	$xml .= '<itunes:category text="'.$premiertheme.'"/>'."\n";
	$xml .= '<itunes:category text="'.$premiertheme.'">'."\n";
	$xml .= '<itunes:category text="'.$secondtheme.'"/>'."\n";
	$xml .= '</itunes:category>'."\n";	
	$xml .= '<googleplay:category text="'.$premiertheme.'"/>'."\n";
	$xml .= '<googleplay:category text="'.$premiertheme.'">'."\n";
	$xml .= '<googleplay:category text="'.$secondtheme.'"/>'."\n";
	$xml .= '</googleplay:category>'."\n";
	
}else{
	
	$xml .= '<itunes:category text="'.$categorie.'"/>'."\n";
	$xml .= '<googleplay:category text="'.$categorie.'"/>'."\n";
	
}
	
$xml .= '<image>'."\n";
$xml .= '<url>'.$link.$logo.'</url>'."\n";
$xml .= '<title>'.$titre.'</title>'."\n";
$xml .= '<link>'.$url.'</link>'."\n";
$xml .= '</image>'."\n";

$xml .= '<itunes:image href="'.$link.$logo.'"/>'."\n";
$xml .= '<googleplay:image href="'.$link.$logo.'"/>'."\n";

if(is_array($array)) {
// Scan des fichiers et recherche des tags
	for ($i = 0; $i < count($array); $i++) {
		
		$getID3 = new getID3;
		$tags = $getID3->analyze($dirprim."/".$array[$i]);
		
		$mp3_url = $link.$array[$i];
		
		$mp3_poids = filesize($array[$i]);
		$mp3_date = date('D, d M Y H:i:s', filectime($array[$i]));
		setlocale(LC_TIME, "");
		setlocale(LC_TIME, "fr_FR");
		$mp3_date_fr =  utf8_encode(strftime("%a %d %b", strtotime($mp3_date)));	
		getid3_lib::CopyTagsToComments($tags);
		$mp3_titre = cleanText($tags['comments']['title'][0]);
		$mp3_description = cleanText($tags['comments']['comment'][0]);
		$mp3_artist = cleanText($tags['comments']['artist'][0]);
		$mp3_duree_min = round(intval($tags['playtime_seconds'] / 60));
			if($mp3_duree_min == 0) { $mp3_duree_min = "moins de 1 "; }
		$mp3_duree_heures = intval($tags['playtime_seconds'] / 3600);
			if($mp3_duree_heures < 10) { $mp3_duree_heures = "0".$mp3_duree_heures; }
		$mp3_duree_minutes = intval(($tags['playtime_seconds'] % 3600) / 60);
			if($mp3_duree_minutes < 10) { $mp3_duree_minutes = "0".$mp3_duree_minutes; }
		$mp3_duree_secondes = intval((($tags['playtime_seconds'] % 3600) % 60));
			if($mp3_duree_secondes < 10) { $mp3_duree_secondes = "0".$mp3_duree_secondes; }
		$mp3_duree = $mp3_duree_heures.":".$mp3_duree_minutes.":".$mp3_duree_secondes;
		$permalink = filectime($array[$i]).$mp3_poids.'badgeek'.str_replace(".", "", $tags['playtime_seconds']);
		
		$mp3_numero = cleanText($tags['comments']['track_number'][0]);
		if($mp3_numero and !is_numeric($mp3_numero)){
			$numerotationcomplete = explode("E", str_replace(' ', '', $mp3_numero));
			$numerodesaison =  ltrim(preg_replace("/[^0-9.]/", "", $numerotationcomplete[0]), "0");
			$numerodepisode =  ltrim(preg_replace("/[^0-9.]/", "", $numerotationcomplete[1]), "0");
		}

		// Suite de la génération du XML

		$xml .='<item>'."\n";
		$xml .='<title>'.$mp3_titre.' ('.$mp3_duree_min.'min)</title>'."\n";
		$xml .='<guid isPermaLink="false">'.$permalink.'</guid>'."\n";
		$xml .='<description><![CDATA[';
		$xml .= $mp3_description; 
		$xml .=']]></description>'."\n";
		$xml .='<content:encoded><![CDATA[';
		$xml .= $mp3_description; 
		$xml .=']]></content:encoded>'."\n";
		$xml .='<pubDate>'.$mp3_date.' GMT</pubDate>'."\n";
		$xml .='<pubDateaffichage>'.$mp3_date_fr.'</pubDateaffichage>'."\n";
		$xml .='<enclosure url="'.$tracking.$mp3_url.'" length="'.$mp3_poids.'" type="audio/mpeg" />'."\n";
		$xml .='<link>'.$mp3_url.'</link>'."\n";
		
		$xml .='<itunes:title>'.$mp3_titre.' ('.$mp3_duree_min.'min)</itunes:title>'."\n";
		$xml .='<itunes:summary>'.$mp3_description.'</itunes:summary>'."\n";
		$xml .='<itunes:author>'.$mp3_artist.'</itunes:author>'."\n";
		$xml .='<itunes:block>'.$appleblock.'</itunes:block>'."\n";
		$xml .='<itunes:explicit>'.$explicit.'</itunes:explicit>'."\n";
		$xml .='<itunes:keywords>'.$keywords.'</itunes:keywords>'."\n";
		$xml .='<itunes:duration>'.$mp3_duree.'</itunes:duration>'."\n";
		$xml .='<itunes:episodeType>full</itunes:episodeType>'."\n";
		$xml .='<itunes:subtitle>'.$mp3_description.'</itunes:subtitle>'."\n";
		if($numerodesaison and $numerodepisode) {
			$xml .='<itunes:season>'.utf8_decode($numerodesaison).'</itunes:season>'."\n";
			$xml .='<itunes:episode>'.utf8_decode($numerodepisode).'</itunes:episode>'."\n";
		}

		$xml .='<googleplay:title>'.$mp3_titre.' ('.$mp3_duree_min.'min)</googleplay:title>'."\n";
		$xml .='<googleplay:author>'.$mp3_artist.'</googleplay:author>'."\n";
		$xml .='<googleplay:description>'.$mp3_description.'</googleplay:description>'."\n";
		$xml .='<googleplay:explicit>'.$explicit.'</googleplay:explicit>'."\n";
		$xml .='<googleplay:block>'.$googleblock.'</googleplay:block>'."\n";

		if(isset($tags['comments']['picture'][0])) {
			$url = $dirprim.'/'.$array[$i];
			
			if($tags['comments']['picture'][0]['image_mime'] == 'image/png') {
				$url = str_replace('.mp3', '.png', $url);
			}
			if($tags['comments']['picture'][0]['image_mime'] == 'image/jpg') {
				$url = str_replace('.mp3', '.jpg', $url);
			}
			
			$xml .= '<image>'."\n";
			$xml .= '<url>'.$link.'scripts/imageReturn.php?mp3='.$url.'</url>'."\n";
			$xml .= '</image>'."\n";
			$xml .='<itunes:image href="'.$link.'scripts/imageReturn.php?mp3='.$url.'"/>'."\n";
			$xml .='<googleplay:image href="'.$link.'scripts/imageReturn.php?mp3='.$url.'"/>'."\n";
		}else{
			$xml .= '<image>'."\n";
			$xml .= '<url>'.$link.$logo.'</url>'."\n";
			$xml .= '</image>'."\n";
			$xml .='<itunes:image href="'.$link.$logo.'"/>'."\n";
			$xml .='<googleplay:image href="'.$link.$logo.'"/>'."\n";
		}

		$xml .='</item>'."\n";
		
		$numerodesaison = '';
		$numerodepisode = '';
		
	}
}

if($ancienrss) {
	$item = 'item';
	$chaine = @implode("",@file($ancienrss));
	preg_match_all('#<item>(.*)<\/item>#isU', $chaine, $items);
	foreach($items[0] as $item) {
		$xml .= str_replace('dc:creator', 'dccreator', $item);
	}
}

$xml .='</channel>'."\n";
$xml .='</rss>';

echo $xml;

// Fin de la génération du XML
?>