<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee-source/sushee/private/matchSoundArt.inc.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
function matchSoundArt($name,&$xml,$requestName,$current_path,$firstNode,$firstNodePath){
	require_once(dirname(__FILE__)."/../file/file_functions.inc.php");
	require_once(dirname(__FILE__)."/../file/file_config.inc.php");
	require_once(dirname(__FILE__)."/../common/getid3/getid3.php");
	require_once(dirname(__FILE__)."/../private/metaSearch.inc.php");
	require_once(dirname(__FILE__)."/../common/dependencies.inc.php");
	
	$db_conn =db_connect();
	
	// checking the module exists and the user has rights to create 
	$moduleInfo = moduleInfo('sound_art');
	if ($moduleInfo->loaded==FALSE){
		$query_result = generateMsgXML(1,"The informations about the module couldn't be found.",0,'',$name);
		//echo $this->_lastError."<br/>";
		return $query_result;
	}
	if(!$moduleInfo->getActionSecurity( "UPDATE",array('Type'=>'Album') )){
		$query_result = generateMsgXML(3,"You're not authorized to modifiy elements in this module.",0,'',$name);
		return $query_result;
	}
	$ID = $IDs_string = $xml->getData($current_path."/*[1]/@ID");
	if ($IDs_string==FALSE){
		//$query_result = "<MESSAGE msgType='0'>No ID were set -> no update has been processed.</MESSAGE>";
		$query_result = generateMsgXML(0,"No ID were set -> no update has been processed.",0,0,$name);
		return $query_result;
	}
	global $directoryRoot;
	// checking the file permissions
	$target = $xml->getData($firstNodePath."/@source");
	$target = transformPath(unhtmlentities($target));
	$right =  getPathSecurityRight($target);
	if ($right===0)
		return generateMsgXML(3,"You're not authorized to handle this file.",0,'',$name);
	$path = $directoryRoot.$target;
	
	// checking an album has not already been imported using this directory
	$sql = 'SELECT * FROM '.$moduleInfo->tableName.' WHERE Directory="'.$xml->getData($firstNodePath."/@source").'" AND Activity=1 AND ID!=\''.$IDs_string.'\';';
	$row = $db_conn->GetRow($sql);
	
	if($row){
		$query_result = generateMsgXML(1,"This directory is already used for another album.",0,'',$name);
		return $query_result;
	}
	if (file_exists($path) && is_dir($path) ){
		// recovering info of the parent album
		$album = getInfo($moduleInfo,$ID);
		$fields_array = $moduleInfo->getFieldsBySecurity('R');
		$profile_array = array('LANGUAGES'=>true,'DATE'=>true,'PLACE'=>true,'CONTEXT'=>true);
		$parent_info = generateInfoXML($moduleInfo,$album,$fields_array,$profile_array,'html',false);
		//echo $parent_info;die();
		$getID3 = new getID3;
		$depType= depType('sound_artTrack');
		// also recovering the babbeleer and curieuzeneus of the parent album
		$curieuzDep= depType('sound_artKurieuzeneus');
		$babeldep=depType('sound_artBabbeleer');
		$dep_rs = getDependenciesFrom(0,$ID,$depType->ID);
		$curieuz_rs = getDependenciesFrom(0,$ID,$curieuzDep->ID);
		$babel_rs = getDependenciesFrom(0,$ID,$babeldep->ID);
		$parent_dep.='<DEPENDENCIES>';
		$parent_dep.='<DEPENDENCY type="'.$curieuzDep->name.'" module="contact">';
		$parent_dep.= generateDependenciesXML($curieuz_rs);
		$parent_dep.='</DEPENDENCY>';
		$parent_dep.='<DEPENDENCY type="'.$babeldep->name.'" module="contact">';
		$parent_dep.= generateDependenciesXML($babel_rs);
		$parent_dep.='</DEPENDENCY>';
		$parent_dep.='</DEPENDENCIES>';
		if (substr($path,-1)!='/')
			$path = $path.'/';
		if (substr($target,-1)!='/')
			$target = $target.'/';
		$now = date("Y-m-d");
		$total_duration = 0;
		$dir = @opendir($path);
		// taking the tracks of the album
		$track_index = 1;
		while (false !== ($file = readdir($dir))) {
			$isFileVisible=true;
			// if the name is not a directory and the name is not the name of this program file
			if($file == "." || $file == ".." || $file == "$ThisFileName")
				$isFileVisible = false;
			if (!is_dir($path.$file) && $isFileVisible){
				$right =  getPathSecurityRight($target.$file);
				if ( $right===0 )
					$isFileVisible = false;
				//if this file is hidden, do net show it
				if (!hidecheck($file))
					$isFileVisible=false;
				// if there were no matches the file should not be hidden
				if($isFileVisible && (getFileExt($file)=='mp3' || getFileExt($file)=='MP3')) {
					$f_arr[$f++] = $file;
				}
			}
			
		}
		sort( $f_arr ); 
		reset( $f_arr );
		// here looping on sorted list of files
		for( $k=0; $k < count( $f_arr ); $k++ ) {
			$file = $f_arr[$k];
			if (preg_match('/.*sample.*\.mp3$/i',$file)){
				$sample_file = reTransformPath($target.$file);
			}else{
				// we take it as a sound_art
				$file_info = $getID3->analyze($path.$file);
				getid3_lib::CopyTagsToComments($file_info);
				if (empty($fileinfo['error'])){
					$row = $dep_rs->FetchRow();
					if ($row)
						$track="<SOUND_ART ID='".$row['TargetID']."'><INFO>";
					else
						$track="<SOUND_ART><INFO>";
					$track.="<TYPE>track</TYPE>";
					if(!$row){
						$track_padded=sprintf("%02d",$track_index);
						$track.="<TITLE>".sprintf("%04d",$album['AlbumID']).' - Track '.$track_padded."</TITLE>";
						//if ($file_info['comments_html']['title'][0])
						//$track.="<TITLE>".$track_padded.'-'.unhtmlentities($file_info['comments_html']['title'][0])."</TITLE>";
						//else
						//$track.="<TITLE>".$track_padded.'-'.getFilenameWithoutExt($file)."</TITLE>";
						$track.="<ARTIST>".unhtmlentities($file_info['comments_html']['artist'][0])."</ARTIST>";
						//$tracks.="<DATE>".$now."</DATE>";
						// on récupère des infos du parent
						$track.=$parent_info;
					}
					$track.="<FILE>".reTransformPath($target.$file)."</FILE>";
					
					$duration = date("H:i:s",strtotime("00:".$file_info['playtime_string']));
					$track.="<DURATION>".$duration."</DURATION>";
					$track.="<ALBUMID>".$album['AlbumID']."</ALBUMID>";
					$track.="<CONTEXTNOTE>".$album['ContextNote']."</CONTEXTNOTE>";
					$track.="<CLOSED>".$album['Closed']."</CLOSED>";
					// adding the hours
					$total_duration+=substr($duration,0,2)*60*60;
					// adding the minutes
					$total_duration+=substr($duration,3,2)*60;
					// adding the seconds
					$total_duration+=substr($duration,-2);
					$track.="</INFO>";
					if (!$row) // recovering the deps of the parent
						$track.=$parent_dep;
					$track.="</SOUND_ART>";
					
					if ($row){
						$old_track="<UPDATE>".$track."</UPDATE>";
						//echo $old_track;
						update(new XML(iso_To_UnicodeEntities($old_track)),"/UPDATE[1]","/UPDATE[1]/SOUND_ART[1]");
					}else
						$new_tracks.=$track;
				}
				$track_index++;
			}
		}
		$filename = basename($path);
		//$informations = explode('-',$filename);
		$query = '<?xml version="1.0"?>';
		$query.= '<UPDATE><SOUND_ART ID="'.$ID.'"><INFO>';
		$query.="<TYPE>album</TYPE>";
		$query.="<FILE>$sample_file</FILE>";
		$query.="<DIRECTORY>".reTransformPath($target)."</DIRECTORY>";
		$hours = sprintf("%02d",floor($total_duration/3600));
		$total_duration-= $hours*3600;
		$minutes = sprintf("%02d",floor($total_duration/60));
		$total_duration-= $minutes*60;
		$seconds = sprintf("%02d",$total_duration);
		$query.="<DURATION>".$hours.":".$minutes.":".$seconds."</DURATION>";
	
		$query.='</INFO><DEPENDENCIES><DEPENDENCY type="sound_artTrack" operation="append">'.$new_tracks.'</DEPENDENCY></DEPENDENCIES></SOUND_ART></UPDATE>';
		$modificationDate = update(new XML(iso_To_UnicodeEntities($query)),"/UPDATE[1]","/UPDATE[1]/SOUND_ART[1]");
	
	}else
		return generateMsgXML(1,"File doesn't exist.".$path,0,'',$name);
	return generateMsgXML(0,"Match successful ",0,$IDs_string,$name,'',$modificationDate);
}
?>
