Location: PHPKode > projects > Audio-Portal > update.php
<?php
require_once('functions/func.php');

adminonly();

$page="Import Album";

$act=(isset($_POST['act']))?$_POST['act']:'';

eval(tpl('header'));
echo "
<table align=\"center\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\"> 
 <tr> 
  <td valign=\"top\" align=\"center\" width=\"16%\">";

eval(tpl('menu'));

echo "
  </td>
  <td width=\"1%\"></td>
  <td valign=\"top\" align=\"center\" width=\"83%\">";

//$act='get';

function opdir($dir) {
if (is_dir($dir)) return opendir($dir);
else return false;    
};

function readir($dh) {
$fl=readdir($dh);
while (($fl=='.') or ($fl=='..')) $fl=readdir($dh);
return $fl;
};

$extcov=array('jpg','bmp','gif');

function is_mp3($fl) {
global $extar,$extcov;

if (($ps=strrpos($fl,'.'))>0) {
    $x=substr($fl,$ps+1);
    $nm=substr($fl,0,$ps);
    foreach($extar as $k=>$ex) if ($ex==$x) return array('mp3',$k,$nm);
    foreach($extcov as $ex) if ($ex==$x) return array('cov',$ex,$nm);
    }
return array('',0,'');
};


mquery("SELECT cdecid,cdecname FROM codec",$codlist,MYSQL_NUM);
mquery("SELECT genid,genname FROM genre",$genlist,MYSQL_NUM);

function getid($ar,$nm) {

$n=strtolower($nm);
foreach($ar as $r) {
    if ($n==strtolower($r[1])) return $r[0];
    };
return 0;
};

function readmp3($loc) {
global $covers,$cddir,$getID3,$bitrate,$codec,$genre,$yar,$bitvar;
global $codlist,$genlist,$bitavrcnt;
$ar=array();
if ($dh=opdir($loc)) {
    while ($fl=readir($dh)) {
	list($flg,$typ,$nam)=is_mp3($fl);
	if ($flg=='mp3') {
	    // Hier moet ie :) result in ThisFileInfo
	    $fldoc = $getID3->analyze($loc.'/'.$fl);
	    getid3_lib::CopyTagsToComments($fldoc);
	    $bitavrcnt+=(float) $fldoc['audio']['bitrate']/1000;
	    if ($bitrate<1) $bitrate=round($fldoc['audio']['bitrate']/1000);
	    if ($codec=='') $codec=getid($codlist,$fldoc['audio']['dataformat']);
	    if ($genre=='') $genre=getid($genlist,$fldoc['id3v1']['genre']);
	    if ($yar=='') $yar=$fldoc['id3v1']['year'];
//	    if ($siz=='') $siz=number_format(($fldoc['filesize']/1024),2,'.','');
	    if (($bitvar!='cbr') or ($bitvar!='vbr')) $bitvar=$fldoc['audio']['bitrate_mode'];
	    $ar[]=array($typ,$nam,$fldoc);
	    };
	if ($flg=='cov') { $covers[]=array('ext'=>$typ,'name'=>$nam,'cddir'=>$cddir); };
	};
    };
closedir($dh);        
return $ar;    
};

function getnum($nm,$brk=false) {
$ps=$gt=0;
while ($ps<strlen($nm)) {
    if (($lc=strpos('0123456789',$nm[$ps]))!==false) {
	$gt=$gt*10+$lc;
	}
    else { 
	if ($brk and ($gt!=0)) return $gt;
	else $gt=0;
	};
    $ps++;
    };
return $gt;
};

function findalbpath($nm,$arid) {
$qry="SELECT alid FROM album WHERE path=".sqlesc($nm);
if ($arid>0) $qry.=" AND arid=$arid";
list($id)=query_arr($qry);
return $id;
};

function findalb($nm,$arid) {
list($id)=query_arr("SELECT alid FROM album WHERE alname=".sqlesc($nm)." AND arid=$arid");
return $id;
};

function findart($nm) {
list($id)=query_arr("SELECT arid FROM artist WHERE arname=".sqlesc($nm));
if ($id<1) return 0;
return $id;
};

function findyear($nm) {
$tt=strlen($nm)-4;
$lc=0;
while ($lc<$tt) {
    if ($nm[$lc]=='(') {
	$nr=getnum(substr($nm,$lc+1),true);
	if (($nr>1900) and ($nr<2100)) return $nr;
	};
    $lc++;	
    };
$lc=0;    
while ($lc<$tt) {
    $nr=getnum(substr($nm,$lc),true);
    if (($nr>1900) and ($nr<2100)) return $nr;
    $lc++;
    };
return '';
};

$act='get';

if ($act=='get') {

require_once('functions/getid3/getid3.php');
$getID3= new getID3();

$extar=array(1=>'mp3',2=>'ogg',3=>'flac',4=>'ape');

$artid=(isset($_GET['artist']))?$_GET['artist']:'';
$alid=(isset($_GET['album']))?$_GET['album']:'';

$qry=($artid!='')?"al.hdarid=".$artid:"al.alid=".$alid;

mquery("SELECT al.path, al.alname, ar.arname FROM album al
  JOIN artist ar ON ar.arid=al.arid WHERE ".$qry,$ar,MYSQL_ASSOC);


$cntr=1; $debug='';
foreach($ar as $a) {

$art=$a['arname'];
$alb=$a['alname'];
$relpath=$a['path'];

$debug.="Dir : ".$relpath."<br />Art : ".$art." |> Alb : ".$alb."<br />";


//    while (($aldir=readir($dh))!==false) {
	@set_time_limit(0);
	$mp3ar=array();


/*
	$debug.="rec =".$recur." | artist =".$artist;
	if ($recur=='1') {
	    list($art,$alb)=explode(' - ',$aldir,2); 
	    if (strlen($alb)<1) {$alb=$aldir;$art=$artist;};
	    }
	else {
	    if ($artist=='') list($art,$alb)=explode(' - ',$aldir,2); 
	    else { $art=$artist; $alb=$aldir; };
	    };

	$art=trim($art);$artist=trim($artist);$alb=trim($alb);
	$hdartid=0;
	if (($art!=$artist) and (strlen($artist)>0)) {
	    $debug.=" sub found ";
	    $hdartid=findart($artist);
	    };
//	$debug.=" Art2 -> ".$art." | Alb2 -> ".$alb." <br />";
	$debug.="<br />";
*/

	if ((strlen($art)>0) and (strlen($alb)>0)) {
	//    $relpath=$aldir;
	    $yar=$codec=$bitrate=$genre=$cddir=$cdnr='';
	    $bitvar='na';$bitavrcnt=0;
	    $covers=$cdname=array();
	    $nrofmp3=count($basear=readmp3($relpath));
	    if ($nrofmp3==0) {
		if ($dh2=opdir($relpath)) {
		    while (($cddir=readir($dh2))!==false) {
			if (is_dir($relpath.'/'.$cddir)) {
			    $path=$cddir;
			    $cdnr=getnum($cddir);
			    $nrmp3=count($basear=readmp3($relpath.'/'.$cddir));
			    if ($nrmp3>0) {
				$nrofmp3+=$nrmp3;
				$mp3ar[$cdnr]=$basear;
				$cdname[$cdnr]=$cddir;
				};
		    	    };
			};
		    closedir($dh2);	
		    };
		}
	    else {$mp3ar[1]=$basear;$cdname[1]='';};
	    $bitrate=round($bitavrcnt/$nrofmp3);
	    $totnrmp3+=$nrofmp3;
	    };
	$err='';        
	if (count($mp3ar)>0) {
//            $debug.="Art -> ".$art." | Alb -> ".$alb;

            $alblist.="<tr><td align=\"right\">".$cntr++." </td>";
            $alblist.="<td align=\"left\"><font color=\"yellow\">&nbsp;".$art."</font></td>";
	    $dummy=(strlen($alb)>60)?substr($alb,0,55)."...":$alb;
            $alblist.="<td align=\"left\"><font color=\"yellow\">".$dummy."</font></td>";
	    $alid=0;
	    $arid=findart($art);
	    if ($arid>0) $alid=findalbpath($relpath,$arid);
	    else $arid=0;
	    if ($alid<1) $alid=findalb($alb,$arid);// path unknow
	    // alid>0  album found
	    
	    
	    if ($alid>0) { // album found
		$res=query_arr("SELECT * FROM album WHERE alid=$alid",MYSQL_ASSOC);
		if ($res['arid']<1) $err="unknown artist";
		if ($res['hdarid']<1) $err.=" unknown hd artist";
		if ($res['arid']>0) {
		    $resar=query_arr("SELECT * FROM artist WHERE arid=$arid",MYSQL_ASSOC);
		    if ($resar['arname']!=$art) $err.=" artist name not same";
		    //query("INSERT INTO artist ( arname ) VALUES (".sqlesc($art).")");
		    //$arid=mysql_insert_id();
		    //query("INSERT INTO artdescr ( arid, ardescr ) VALUES ('".$arid."', '')");
		    };
		if ($yar<1) $yar=findyear($aldir);
		if ($hdartid<1) $hdartid=$arid;

		if ($alb!=$res['alname']) $err.=" album name not same";
		if ($yar!=$res['year']) $err.=" year not same";
		if ($nrofmp3!=$res['tracks']) $err.=" nr tracks not same";


				    
//		$debug.=" | Alb -> ".$alb." <br/> ";
//		query("INSERT INTO album (arid,hdarid,alname,path,year,tracks,added,bitrate,bitmod,codec,genre) VALUES 
//		    ('$arid','$hdartid',".sqlesc($alb).",".sqlesc($relpath).",'$yar','$nrofmp3','".time()."','$bitrate','$bitvar','$codec','$genre')");
//		$alid=mysql_insert_id();
		$albsiz=$pltalb=0;
		foreach($mp3ar as $cds=>$cdnr) {
		    $rscd=query_arr("SELECT * FROM cdlist WHERE cdnr=$cds AND alid=$alid");
		    $cdid=$rscd['cdid'];
		    if ($cdname[$cds]!=$rscd['cdname']) $err.=" cd not same";
		    if (count($mp3ar)!=$cds) $err.=" cd not found or nr fail";	
		    
//		    $debug.=count($mp3ar)." MM $cds <br />";
		
		
		    
//		    query("INSERT INTO cdlist (alid,cdnr,cdname) VALUES ($alid,$cds,'".$cdname[$cds]."')");
//		    $cdid=mysql_insert_id();
		    $cdsiz=$plttot=0;
//		    $debug.=" cdid $cdid ";
		    $tcnt=mquery("SELECT tk.*, '' AS flg FROM track tk WHERE cdid=$cdid",$mtrk,MYSQL_ASSOC);
		    if ($tcnt!=count($cdnr)) $err.=" nr tracks diff";
//		    $debug.=" cnts trk $tcnt db With ".count($cdnr)."tracks <br />";
		    foreach($cdnr as $track) {
			$tdiff=false;
			list($typ,$name,$audio)=$track;
			$plt=round($audio['playtime_seconds']);
			$plttot+=$plt;
			$trksize=$audio['filesize'];
			$cdsiz+=$trksize;
			$trknr=0+$audio['comments']['track_number'][0];
			if ($trknr<1) $trknr=0+substr(trim($name),0,4);
//			$debug.=" $trknr MM ";
			$restcnt=0;$restrk=array();
			foreach($mtrk as $key=>$trkl) {
			    if (strlen($trkl['flg'])<1) {
//				$debug.=".".$trkl['trknr'].".";
				if (($trknr>0) and ($trknr==$trkl['tracknr'])) {
//				    $debug.="found ".$trkl['trname'];
				    $restrk=$trkl;$mtrk[$key]['flg']=$trknr;}
				else $restcnt++;
				};
			    };
//			$debug.="<br />";
//			$restrk=query_arr("SELECT * FROM track WHERE cdid=$cdid");
//			$debug.=$restrk['trname']." TT $name CC $cdid<br />";
			if ($restrk['trname']!=$name) {$err.=" trk name err";$tdiff=true;};
			if ($restrk['extid']!=$typ) {$err.=" ext trk id not same";$tdiff=true;};
			if ($restrk['playtime']!=$plt) {$err.=" play time not same";$tdiff=true;};
			if ($restrk['size']!=$trksize) {$err.=" track size diff";$tdiff=true;};
//			if ($update and $tdiff) query("UPDATE track SET cdid=$cdid,trname=".sqlesc($name).",
//			    extid=$typ,playtime=$plt,tracknr='".$trknr."',size='$trksize',
//			    tkmd5='".$audio['md5_data']."' WHERE tkid=".$restrk['tkid']);
			};
		    if ($restcnt>0) $err.=" some files are not found";	
		    $debug.=" $restcnt left over <br />";
//		    query("UPDATE cdlist SET playtime='$plttot', cdsize='$cdsiz' WHERE cdid=$cdid");	
		    $albsiz+=$cdsiz;
		    $pltalb+=$plttot;
		    if ($rscd['playtime']!=$plttot) $err.=" cd playtime diff";
		    if ($rscd['cdsize']!=$cdsiz) $err.=" cd size diff";
		    };
		$lastid=0; $cvrsaved=''; $cvrfnd='-';
		foreach($covers as $cover) {
		    $cdnr=getnum($cover['cddir']);
		    if (($cvrsaved=='') and (stripos($cover['name'],'front')!==false)) {
                        $cvrsav=$dr."/".$aldir."/".$cover['name'].".".$cover['ext'];
			@savecover($cvrsav,($cfg['cvrdir'].$alid.".jpg"));
			$cvrsaved=", cvrsaved='yes'";
			$cvrfnd='Saved';
			$debug.=" Cover -> Yes";
                        };
//		    query("INSERT INTO covers (nxtid,cddir,name,ext,alid,cdid) VALUES ('$lastid','".
//		    $cover['cddir']."','".$cover['name']."','".$cover['ext']."','$alid','$cdnr')"); 
//		    $lastid=mysql_insert_id();
		    };
		if ($res['playtime']!=$pltalb) $err.=" alb playtime diff";
		if ($res['alsize']!=$albsiz) $err.=" alb size diff";
//		query("UPDATE album SET playtime='$pltalb', alsize='$albsiz', coverid='$lastid' $cvrsaved WHERE alid=$alid");
		if (strlen($err)<1) $err="same";
		$alblist.="<td align=\"left\"><font color=\"orange\">".$cvrfnd."</font></td>";
		$alblist.="<td align=\"rightt\"><font color=\"limegreen\">$err</font></td></tr>";
        	$newalbum++; $debug.="<br /><br />";
		}
	    else {
		// album not found
		$err="album not found";
	        $alblist.="<td align=\"right\" colspan=\"2\">
                            <font color=\"red\">Album doesn't exists&nbsp;&nbsp;</font></td></tr>";
	        $exist++;
		};
	    };
        //debug("filename: $aldir : filetype: ".filetype($dr.$aldir));
	}
//    closedir($dh);
//    }



if ($debug!='') debug($debug);


list($albums,$playtim,$alsiz)=query_arr("SELECT COUNT(alid), SUM(playtime), SUM(alsize) FROM album");
list($artists)=query_arr("SELECT COUNT(arid) FROM artist");
list($tracks)=query_arr("SELECT COUNT(trid) FROM track");

$stats=query("UPDATE stats SET nr_albums=".sqlesc($albums).", nr_artists=".sqlesc($artists).",
 nr_tracks=".sqlesc($tracks).", catalog_size=".sqlesc($alsiz).", play_time=".sqlesc($playtim));

if ($stats) $upd="Your stats were successfully saved";
else $upd="An Error occured updating Stats";

$output= "
 <tr> 
  <td valign=\"top\" align=\"left\">
   Existing Albums found : ".$exist."
  </td>
 </tr>
 <tr> 
  <td valign=\"top\" align=\"left\">
   Nr of Audio files found : ".$totnrmp3."
  </td>
 </tr>
 <tr> 
  <td valign=\"top\" align=\"left\">
   New Albums found : ".$newalbum."
  </td>
 </tr>
 <tr> 
  <td valign=\"top\" align=\"left\">".$upd."
  </td>
 </tr>";

eval(tpl('update_mess'));


// End 'act'
} else {

  eval(tpl('update'));
  };

echo "
  </td>
 </tr>
</table>";
eval(tpl('footer'));
?>
Return current item: Audio-Portal