<?

require_once 'PEAR.php';
require_once 
'MP3/IDv2/Reader.php';
require_once 
'MP3/IDv2/Tag.php';
require_once 
'MP3/IDv2/Frame.php';

require_once 
'MP3/IDv2/Frame/APIC.php';
require_once 
'MP3/IDv2/Frame/TIT2.php';


define(ROOT_DIR'/nas/bighd/Music');
define(DATA_DIR'ab2cdata');

$cast substr($_SERVER['PATH_INFO'], 1);
//$cast = $_SERVER['argv'][1];

if (empty($cast)){
    
header("HTTP/1.0 404 Not Found");
    echo 
"no cast";
    exit;
}

if (
preg_match('#^_getimage#'$cast)){
    
$file "img-".preg_replace('#\..+#'''basename($_SERVER['PATH_INFO']));
    
$path DATA_DIR."/$file";
    if (!
file_exists($path)){
        
header("HTTP/1.0 404 Not Found");
        echo 
"image not found";
        exit;
    }
    
$info getimagesize($path);
    
header("Content-type: ".$info['mime']);
    
header("Content-length: ".filesize($path));
    
readfile($path);
    exit;
}

if (
preg_match('#^_getfile#'$cast)){
    
$file realpath(ROOT_DIR."/".base64_decode(basename(str_replace('_getfile/'''$cast), 'mp3')));
    if (!
preg_match('#^'.ROOT_DIR.'#'$file)){
        
header("HTTP/1.0 403 Forbidden");
        echo 
"can only access below MP3-root";
        exit;
    }
    if (!
file_exists($file)){
        
header("HTTP/1.0 404 Not Found");
        echo 
"file not found";
        exit; 
    }
    
header("Content-type: audio/mpeg");
    
header("Content-length: ".filesize($file));
    
readfile($file);
    exit;
}


$dir ROOT_DIR."/".$cast;
if (!
is_dir($dir)){
    
header("HTTP/1.0 404 Not Found");
    echo 
"invalid cast";
    exit;
}
header('Content-Type: text/xml');
echo 
'<?xml version="1.0" encoding="ISO-8859-1"?>';
echo 
'<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">'."\n";
echo 
"  <channel>\n";
echo 
"    <title>".clean_xml($cast)." - audiobook2cast</title>\n";
echo 
"    <description>Autogenerated PodCast from MP3-Collection. Artist: ".clean_xml($cast)."</description>\n";
echo 
"    <generator>audiobook2cast</generator>\n";
echo 
"    <category>Entertainment</category>\n";
echo 
"    <itunes:author>pilif</itunes:author>\n";
echo 
"    <itunes:keywords>".keywordize($cast)."</itunes:keywords>\n";
echo 
"    <itunes:explicit>no</itunes:explicit>\n";
echo 
"    <itunes:owner>\n";
echo 
"      <itunes:name>pilif</itunes:name>\n";
echo 
"      <itunes:email>pilif@pilif.home</itunes:email>\n";
echo 
"    </itunes:owner>\n";
echo 
"    <itunes:new-feed-url>http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'/'.clean_xml(rawurlencode($cast))."</itunes:new-feed-url>\n";
echo 
"    <itunes:block>no</itunes:block>\n";
echo 
"    <itunes:category text='Technology'>\n";
echo 
"      <itunes:category text='Podcasting' />\n";
echo 
"    </itunes:category>\n";

$entries gatherFiles($dir);
sort($entries); // posible here because of distinct naming scheme

$pub_date 0;
$image = array();
$fname md5($cast);
if (
file_exists(DATA_DIR."/img-$fname")){
    
$info getimagesize(DATA_DIR."/img-$fname");
    
$image = array('file' => $fname'type' => $info['mime'], 'info' => $info);
}
$pcent = array();

foreach(
$entries as $file){
    
$reader = new MP3_IDv2_Reader();
    
$reader->read($file);
    
$tag $reader->getTag();
    
$frames $tag->getFrames();
    
$h = array();
    
$info stat($file);
    foreach(
$frames as $frame){ 
        if (
preg_match('#^TIT#'$frame->getID())){
            
$h['title'] = trim($frame->getRawContent());
        }
        if (
preg_match('#^TPE#'$frame->getID())){
            
$h['author'] = trim($frame->getText());
        }
        if (
preg_match('#^TALB#'$frame->getID())){
            
$h['album'] = trim($frame->getText());
        }
        
// extract first usable image
        
if ( ($frame->getID() == "APIC") && empty($image)){
            
$frame->writeToFile(DATA_DIR."/img-$fname");
            
resizeForiTunes(DATA_DIR."/img-$fname");
            
$image = array('file' => $fname'type' => $frame->getMimeType(), 'info' => getimagesize(DATA_DIR."/img-$fname"));
        }
    }
    
$h['date'] = $info['mtime'];
    if (
$pub_date $info['mtime'])
        
$pub_date $info['mtime'];
    
$h['file'] = $file;
    
$h['size'] = $info['size'];
    
$h['hash'] = md5($file); //md5_file($file);
    
$pcent[] = $h;
}

if (
$image){
    
$imgurl sprintf("http://%s/%s/_getimage/%s.%s"$_SERVER['HTTP_HOST'], $_SERVER['SCRIPT_NAME'], $image['file'], str_replace('image/'''$image['type']));
    echo   
"    <image>\n";
    
printf("      <url>%s</url>\n"$imgurl);
    
printf("      <title>%s</title>\n"clean_xml($cast));
    
printf("      <link>http://www.lipfi.ch</link>\n");
    
printf("      <width>%d</width>\n"$image['info'][0]);
    
printf("      <height>%d</height>\n"$image['info'][1]);
    echo   
"    </image>\n";
    
printf('    <itunes:image href="%s" />'."\n"$imgurl);
}
$d date('r'$pub_date);

$base_date $pub_date;

printf("    <pubDate>%s</pubDate>\n    <lastBuildDate>%s</lastBuildDate>\n"$d$d);
foreach(
$pcent as $item){
    
$relpath str_replace(ROOT_DIR."/"''$item['file']);
    
$url sprintf("http://%s%s/_getfile/%s.mp3"$_SERVER['HTTP_HOST'], $_SERVER['SCRIPT_NAME'], base64_encode($relpath));
    
printf("    <item>\n");
    
printf("      <title>%s</title>\n"clean_xml($item['title']));
    
printf("      <link>http://www.lipfi.ch</link>\n");
    
printf("      <description>%s</description>\n"clean_xml("Autogenerated Feed-Item for: ".$item['title']));
    
printf("      <author>%s</author>\n"clean_xml($item['author']));
    
printf("      <pubDate>%s</pubDate>\n"clean_xml(date('r', --$base_date))); // enforce correct order by lying 
    
printf("      <comments>%s</comments>\n"clean_xml("Generated from Album: ".$item['album']));
    
printf("      <guid isPermaLink='false'>%s</guid>\n"$item['hash']);
    
printf("      <itunes:explicit>no</itunes:explicit>\n");
    
printf('      <enclosure url="%s" length="%d" type="audio/mpeg" />'."\n"$url$item['size']);
    echo   
"    </item>\n";
}
echo 
"  </channel></rss>\n";

function 
keywordize($str){
   
$words preg_split('#\s+#'$str);
   return 
implode(', 'array_map('clean_xml'array_unique(array_map('strtolower'$words))));
}

function 
clean_xml($str){
    
$str htmlspecialchars($strENT_QUOTES);
    return 
$str;
}

function 
gatherFiles($dir){
   
$d dir($dir);
   
$files = array();
   while( (
$a $d->read()) !== false ){
       if (
preg_match('#^\.+$#'$a)) continue;
       if (
is_dir($dir."/".$a)){
          
$files array_merge($filesgatherFiles($dir."/".$a));
       }
       if (!
preg_match('#.mp3$#'$a)) continue;
       
$files[] = $dir."/".$a;
   }
   return 
$files;
}

function 
resizeForiTunes($file){
    
$info getimagesize($file);
    
$h = ($info[1] / $info[0]) * 300;

    
$thumb imagecreatetruecolor(300$h);
    
$func "imagecreatefrom".str_replace('image/'''$info['mime']);
    
$source $func($file);
    
imagecopyresampled($thumb$source0000300$h$info[0], $info[1]);
    
imagedestroy($source);
    
$func "image".str_replace('image/'''$info['mime']);
    
$func($thumb$file);
    echo 
"called $func for $file";
}

?>